文档中心 > Dropshipping(已废弃)

How to Invoke API

更新时间:2020/07/17 访问次数:70076

APIs in Aliexpress Open Platform need to be invoked based on the Hypertext Transfer Protocol (HTTP). To invoke a specific API: The developer (such as the ISV) has two choices:

  • They can directly use the official SDK provided by the TOP to invoke an API. This official SDK supports multiple languages and various features, such as request encapsulation, signature encryption, response interpretation, and performance optimization.
  • They can also encapsulate an HTTP request in compliance with TOP protocols to invoke an API.

Basically, the developers could choose developing their own HTTP invocation and interpretation module or using TOP SDK to interact with TOP server. The following sections describes the procedures of API invocation based on the second option. However, even if using SDK directly, it is still recommended for developers to read the following sections.

Invoking Process

The API invocation process mainly has the following steps.
- Fill in parameters.
- Generate a signature.
- Encapsulate an HTTP request.
- Initiate the HTTP request
- Receive an HTTP response.
- Interpret json/xml results

image

Invoking Entry

Based on the service URL used to invoke APIs, the AliExpress open platform currently provides two environments for ISVs: Chinese environment, and overseas environment. The seller could initiate a performance test before deciding which url to choose.

Invocation Environment Service URL (HTTP) Service URL (HTTPS)
Chinese 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

Note: The default service url in the SDK is http://gw.api.taobao.com/router/rest

Public Parameters

Public parameters need to be set for every API. The following table lists all public parameters.

Parameter Name Parameter Type Mandatory or Optional Parameter Description
method String Mandatory Indicates the API name.
app_key String Mandatory Indicates the AppKey allocated by the TOP to an application. An ISV can choose Open Platform Console > Application Management > Overview to check the AppKey and AppSecret of the formal environment.
session String Mandatory Indicates the authorization granted by the TOP to an application after a user logs in and grants authorization successfully. For details, click here
timestamp String Mandatory Indicates the time stamp in the format of yyyy-MM-dd HH:mm:ss and in the time zone of GMT+8. For example, 2016-01-01 12:00:00. The Taobao API server allows a maximum time error of 10 minutes for a request from a client.
format String Optional Indicates the response format. The default value is xml. The value can be set to xml or json.
v String Mandatory Indicates the API protocol version. The value can be set to 2.0.
simplify Boolean Optional Indicates whether the simplified JSON return format is used. This parameter is valid only if format is set to json. The default value is false.
sign_method String Mandatory Indicates the signature digest algorithm. The value can be set to hmac or md5.
sign String Mandatory Indicates the obtained signature of API input parameters. For details about the signature algorithm, see the following description.

Service Parameters for every API

Besides public parameters, for each specific API, there are some input parameters.

Signature Algorithm

To prevent data from being tampered maliciously by a hacker during API invocation, each request for API invocation must carry a signature. The TOP server verifies the signature based on request parameters and rejects the request carrying an invalid signature. Currently, the TOP supports two signature algorithms: MD5(sign_method=md5) and HMAC_MD5(sign_method=hmac). The signature process is generally described as follows:

  • Sort all request parameters of an API (including public parameters and service parameters, but excluding the sign parameter and parameters of the byte[] type) based on the sequence of their parameter names in the ASCII tabl. For example, parameters foo:1, bar:2, foo_bar:3, and foobar:4 are sorted as follows: bar:2, foo:1, foo_bar:3, foobar:4.
  • Splice the sorted parameter names and values together to obtain a character string. For example, the character string obtained in the preceding example is bar2foo1foo_bar3foobar4.
  • Encode the spliced character string based on UTF-8 encoding and use a signature algorithm to produce a digest for the encoded byte stream. If the MD5 algorithm is used, add the secret value of the corresponding application before and after the spliced character string, and then produce a digest, for example, md5(secret+bar2foo1foo_bar3foobar4+secret). If the HMAC_MD5 algorithm is used, initialize the digest algorithm based on the secret value of the corresponding application, and then produce a digest, for example, hmac_md5(bar2foo1foo_bar3foobar4).
  • Denote the byte stream obtained after the digest in hexadecimal, for example, hex(“helloworld”.getBytes(“utf-8”)) = “68656C6C6F776F726C64”.

Note: Both MD5 and HMAC_MD5 digest algorithms produce a 128-bit value represented in hexadecimal. As each hexadecimal character represents four bits, the length of the signature character 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 parameters have been sorted.
         String[] keys = params.keySet().toArray(new String[0]);
         Arrays.sort(keys);

         //Step 2: Splice all sorted parameter names and values together.
         StringBuilder query = new StringBuilder();
         if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
                  query.append(secret);
         }
         for (String key : keys) {
                  String value = params.get(key);
                  if (StringUtils.areNotEmpty(key, value)) {
                           query.append(key).append(value);
                  }
         }

         //Step 3: Use the MD5 or HMAC_MD5 algorithm to encrypt the spliced character string.
         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 characters into capitalized hexadecimal characters. (A correct signature must be a character string consisting of 32 capitalized hexadecimal characters. This step is performed as required.)
         //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 based on the alphabetical order of Key.
    IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);
    IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

    //Step 2: Splice all sorted parameter names and 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))
        {
            query.Append(key).Append(value);
        }
    }

    //Step 3: Use the MD5 or HMAC_MD5 algorithm to encrypt the spliced character string.
    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);
        MD5 md5 = MD5.Create();
        bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
    }

    //Step 4: Convert binary characters into capitalized hexadecimal characters.
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < bytes.Length; i++)
    {
        result.Append(bytes[i].ToString("X2"));
    }

    return result.ToString();
}

For details about signature sample code in other languages, see source code of the TOP official SDK.

Example

The following uses the API aliexpress.solution.order.fulfill(order fullfillment) as an example. The procedure for invoking this API is as follows:

1. Set parameter values.

Public parameters:

  • method = “aliexpress.solution.order.fulfill”
  • app_key = “12345678”
  • session = “test”
  • timestamp = “2016-01-01 12:00:00”
  • format = “json”
  • v = “2.0”
  • sign_method = “md5”

Service parameters:

  • service_name = “SPAIN_LOCAL_CORREOS”
  • out_ref = “1000006270175804”
  • send_type=“all”
  • logisitics_no=“ES2019COM0000123456”

2. Sort parameters based on the sequence of their parameter names in the ASCII chart.

  • app_key = “12345678”
  • format = “json”
  • logisitics_no=“ES2019COM0000123456”
  • method = “aliexpress.solution.order.fulfill”
  • out_ref = “1000006270175804”
  • send_type=“all”
  • service_name = “SPAIN_LOCAL_CORREOS”
  • session = “test”
  • sign_method = “md5”
  • timestamp = “2019-01-01 12:00:00”
  • v = “2.0”

3. Splice parameter names and values.

app_key12345678formatjsonlogisitics_noES2019COM0000123456methodaliexpress.solution.order.fulfillout_ref1000006270175804send_typeallservice_namSPAIN_LOCAL_CORREOSesessiontestsign_methodmd5timestamp2019-01-01 12:00:00v2.0

4. Generate a signature.

Assume that secret of the application is helloworld. The obtained signature is as follows: hex(md5(helloworld+Sorted and spliced parameter names and values+helloworld)) = “F7A5E0B28DEFFE9E1E6E5C0E8B0530EC”().

5. Encapsulate an HTTP request.

Perform URL encoding for all parameter names and values based on UTF-8 encoding. The sequence of parameters can be random, but the sign parameter must be included. Then, use the GET or POST method (containing parameters of the byte[] type) to initiate the HTTP request. For example:

http://gw.api.taobao.com/router/rest?method=aliexpress.solution.order.fulfill&app_key=12345678&session=test&timestamp=2019-01-01 12:00:00&format=json&v=2.0&sign_method=md5&logistics_no=ES2019COM0000123456&out_ref=1000006270175804&send_type=all&service_name=SPAIN_LOCAL_CORREOS&sign=F7A5E0B28DEFFE9E1E6E5C0E8B0530EC

Notes

  • All requests and response data should be encoded in UTF-8 format. URL encoding is required for all parameter names and parameters in the request URL. If Content-Type is application/x-www-form-urlencoded in a request, URL encoding is required for all parameter values in the HTTP body. If a request is in multipart/form-data format, encoding is not required for parameter values of each form field, but charset of each form field must be set to utf-8.
  • If a request URL spliced by parameter names and values is shorter than 1,024 characters, this request can be initiated by means of the GET method. If parameters of the byte[] type are included or a spliced request URL is excessively long, this request must be initiated by means of the POST method. The POST method applies to requests for all APIs.
  • Signature generation (sign) is required only if an ISV does not use the TOP official SDK to invoke an API. If the TOP official SDK is used, the SDK will automatically generate a signature.

Next Step

Business API Overall View

FAQ

关于此文档暂时还没有FAQ
返回
顶部