Platform technology-API calling protocol
The API of the Open Platform (TOP) is called based on the HTTP protocol. Developers (ISVs) can directly use the official SDK provided by TOP (supports multiple languages, including request encapsulation, signature encryption, response explanation, performance optimization, etc.) to call, or you can encapsulate HTTP requests for calls according to the TOP protocol. The following is a detailed explanation of the principle of self-encapsulating HTTP requests for API calls.
Calling process
According to the TOP protocol: fill in parameters> Generate signature> Assemble HTTP request> Initiate HTTP request> Get HTTP response> Interpret json/xml results, the following is General schematic diagram of the calling process:
Calling entry point
Service URL address for calling the API. The open platform currently provides 4 environments for ISVs to use: Sandbox Test environment, formal test environment, formal environment, overseas environment.
- Sandbox test environment: The test environment for ISV software, which can be used after the application is created. This environment provides a simplified version of Taobao, supporting API calls in most scenarios. The permissions and traffic of the sandbox environment are unlimited and can be used freely.
- Formal test environment: The formal simulation environment before the ISV software is launched. It can be used after the application is successfully created. This environment is mainly used for some scenarios where testing cannot be completed in the sandbox. The API calls are limited to 5,000 times/day, the number of authorized users is 5, and the APIs that can be called are consistent with the permissions and capabilities of the application.
- Formal environment: The environment used after the ISV software is online. The entrance to this environment is the same as the formal test environment. However, after the application is online, the traffic limit will be turned on. The specific traffic limit is related to the application. It depends on the category it belongs to. For example, for service market applications, API calls are limited to 1 million times per day.
- Overseas environment: Overseas environment is also a type of formal environment. It is mainly used by overseas (European and American countries) ISVs. For overseas ISVs, the performance of using the overseas environment will be better than that of the domestic environment. Twice as high.
Calling environment | Service address (HTTP) | Service address (HTTPS) |
---|
Sandbox environment | http://gw.api.tbsandbox.com/router/rest | https:// gw.api.tbsandbox.com/router/rest |
Formal environment | http://gw.api.taobao.com/router/rest | https://eco.taobao.com/router/rest |
Overseas environment | http://api.taobao.com/router/rest | https://api.taobao.com/router/rest |
Public parameters
Parameters that must be passed in when calling any API. Currently supported public parameters are:
Parameter name | Parameter type | Is it required? | Parameter description |
---|
##method | String | is the | API interface name. |
app_key | String | is the AppKey assigned to the application by | . It should be noted here that the AppKey of the formal environment and the sandbox environment are different (including AppSecret), and you should pay attention to the distinction when using it; enter the open platform console "Application Management-Overview" and "Application Management-Sandbox Environment Management" to respectively Check the AppKey and AppSecret of the formal environment and sandbox environment
|
session | String | No | User login authorization After success, TOP issues authorization information to the application. For details, please click here. When the label of this API document indicates: "Authorization required", this parameter must be passed; "Authorization not required", then this parameter does not need to be passed; "Optional authorization", then this parameter is optional. |
timestamp | String | is the | timestamp in the format of yyyy-MM-dd HH:mm:ss, time zone is GMT 8, for example: 2016-01-01 12:00:00. The Taobao API server allows a maximum time error of 10 minutes for client requests. |
format | String | No | Response format. The default is xml format, optional values: xml, json. |
v | String | is the | API protocol version, optional value: 2.0. |
partner_id | String | No | Partner ID. |
target_app_key | String | No | The called target AppKey, only when the called API is provided by a third-party ISV valid. |
simplify | Boolean | No | Whether to use simplified JSON return format, only valid when format=json, default value is: false. |
sign_method | String | is the digest algorithm of | signature. Optional values are: hmac, md5. |
sign | String | is the | API input parameter signature result. For the signature algorithm, refer to the introduction below. |
Business parameters
In addition to public parameters that must be included in API calls, if the API itself has business-level parameters, they must also be passed in. Please refer to the API documentation for the business-level parameters of each API.
Signature Algorithm
In order to prevent malicious tampering by hackers during the API call process, any API call needs to carry a signature. The TOP server will verify the signature based on the request parameters. The signature is illegal. The request will be denied. TOP currently supports two signature algorithms: MD5 (sign_method=md5), HMAC_MD5 (sign_method=hmac). The general signature process is as follows:
- For all API request parameters (including public parameters and business parameters) , but excluding sign parameters and byte[] type parameters), sorted according to the order of the ASCII code table of parameter names. For example: foo=1, bar=2, foo_bar=3, foobar=4, the sorted order is bar=2, foo=1, foo_bar=3, foobar=4.
- Assemble the sorted parameter names and parameter values together. The result obtained according to the above example is: bar2foo1foo_bar3foobar4.
- Encode the assembled string into UTF-8, and use the signature algorithm to digest the encoded byte stream. If you use the MD5 algorithm, you need to add the secret of the app before and after the assembled string, and then summarize it, such as: md5(secret bar2foo1foo_bar3foobar4 secret); if you use the HMAC_MD5 algorithm, you need to initialize the digest algorithm with the secret of the app, and then Digest, such as: hmac_md5(bar2foo1foo_bar3foobar4).
- Use hexadecimal representation of the byte stream result obtained from the summary, such as: hex("helloworld".getBytes("utf-8")) = "68656C6C6F776F726C64"
Note: MD5 and HMAC_MD5 are both 128-bit digest algorithms, expressed in hexadecimal. One hexadecimal character can represent 4 bits, so the length of the signed string is fixed to 32 hexadecimal characters. .
JAVA signature sample code
##public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
// Step 1: Check whether the parameters have been sorted
String[] keys = params.keySet().toArray(new String[0]);
Arrays.sort(keys);
// Step 2: String all parameter names and parameter values Together
StringBuilder query = new StringBuilder();
if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
query.append(secret);
}
for (String key: keys) {
use using using using using ‐ through out using using using using using out out out out out out out out out out of ’ s ’ to through ‐ ‐ ‐‐‐‐ ‐ -
}
// Step 3: Use MD5/HMAC encryption
byte[] bytes;
if (Constants.SIGN_METHOD_HMAC.equals(signMethod)) {
bytes = encryptHMAC (query.toString(), secret);
} else {
query.append(secret);
bytes = encryptMD5(query.toString());
}
// Step 4: Convert binary to uppercase hexadecimal
return byte2hex(bytes);
}
public static byte[] encryptHMAC(String data, String secret) throws IOException {
byte[] bytes = null;
try {
SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), "HmacMD5");
Mac mac = Mac.getInstance(secretKey .getAlgorithm());
mac.init(secretKey);
bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8));
} catch (GeneralSecurityException gse) {
throw new IOException(gse.toString());
}
return bytes;
}
public static byte[] encryptMD5(String data) throws IOException {
return encryptMD5(data.getBytes(Constants.CHARSET_UTF8));
}
public static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i ) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
##C# Signature Sample Code
public static string SignTopRequest(IDictionary<string, string> parameters, string secret, string signMethod)
{
// Step 1: Sort the dictionary in alphabetical order by Key
IDictionary< ;string, string> sortedParams = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
/ / Step 2: String all parameter names and parameter values together
StringBuilder query = new StringBuilder();
if (Constants.SIGN_METHOD_MD5.Equals(signMethod))
{
query.Append( secret);
}
while (dem.MoveNext())
{
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
// Step 3: Use MD5/HMAC encryption
byte[] bytes;
if (Constants.SIGN_METHOD_HMAC.Equals(signMethod))
{
HMACMD5 hmac = new HMACMD5(Encoding.UTF8. GetBytes(secret));
bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
}
else
{
query.Append(secret) ;
Step: Convert binary to uppercase hexadecimal
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytes.Length; i )
{
result.Append(bytes[i].ToString("X2"));
}
return result.ToString();
}
For other language signature sample codes, please refer to TOP official SDK source code.
Call example
Take taobao.item.seller.get call as an example. The specific steps are as follows:
1. Set parameter value
Public parameters:
- method = "taobao.item.seller.get"
- app_key = "12345678"
- session = "test"
- timestamp = "2016-01-01 12:00:00"
- format = "json"
- v = "2.0"
- sign_method = "md5 ”
Business parameters:
- fields = “num_iid,title,nick,price,num”
- num_iid = 11223344
2. Sort in ASCII order
- app_key = “12345678”
- fields = “num_iid,title,nick,price,num”
- format = “json”
- method = “taobao.item.seller.get”
- num_iid = 11223344
- session = “test”
- sign_method = “md5”
- timestamp = “2016-01-01 12:00:00”
- v = “2.0”
3. Splice parameter names and parameter values
##app_key12345678fieldsnum_iid,title,nick,price,numformatjsonmethodtaobao.item.seller.getnum_iid11223344sessiontestsign_methodmd5timestamp2016-01-01 12:00:00v2 .0
4. Generate signature Assuming that the secret of the app is helloworld, the signature result is: hex(md5(helloworld) Spliced in order Good parameter names and parameter values helloworld)) = “66987CB115214E59E6EC978214934FB8”
5. Assemble the HTTP requestUse utf-8 to URL encode all parameter names and parameter values (parameter order optional, but must include signature parameters), and then initiate a request through GET or POST (including byte[] type parameters), such as:
http://gw. api.taobao.com/router/rest?method=taobao.item.seller.get&app_key=12345678&session=test×tamp=2016-01-01 12:00:00&format=json&v=2.0&sign_method=md5&fields=num_iid,title,nick,price, num&num_iid=11223344&sign=66987CB115214E59E6EC978214934FB8
##
Notes
- All request and response data encodings are in UTF-8 format. Please URL encode all parameter names and parameter values in the URL. If the Content-Type of the request is application/x-www-form-urlencoded, all parameter values in the HTTP Body are also URL-encoded; if it is in multipart/form-data format, the parameter values of each form field do not need to be encoded. But the charset part of each form field needs to be specified as utf-8.
- When the length of the URL assembled by the parameter name and parameter value is less than 1024 characters, you can use GET to initiate the request; when the parameter type contains byte[] type or the assembled request URL is too long, you must use POST to initiate the request. . All APIs can use POST to initiate requests.
- If you need to test in a sandbox environment, please obtain the app_key corresponding to the sandbox environment on the sandbox management page of the application console (usually "10" is added in front of the app_key of the official environment) and app_secret, corresponding The session value is also obtained through sandbox account login authorization. Sandbox environment authorization is similar to formal environment authorization. For details, please refer to the user authorization introduction.
- Generating a signature (sign) is only required when making API calls without using the TOP official SDK. If the TOP official SDK is used, the SDK will automatically complete this step.
FAQ
The interface call reports a signature error "Invalid signature"