文档中心 > Miravia Open Platform

Miravia - Call API with HTTP request

更新时间:2022/11/29 访问次数:583

1. API calling process

Miravia Open Platform APIs are called through HTTP requests. You can call the API by using the platform provided SDK (recommended), or by assembling the request with a certain format according to the Miravia Open Platform protocols (only if no official SDK is provided for a programming language). This section introduces how to assemble HTTP requests to call the Miravia APIs.

API calls require data for input and return output as the responses. The general steps for calling an API through generating HTTP requests are as follows:
1. Populate parameters and values
2. Generate signature
3. Assemble HTTP requests
4. Initiate HTTP requests
5. Get HTTP responses
6. Interpret JSON/XML responses

1.1 HTTP request sample

Taking the GetOrder (/order/get) API call as example, the steps of assembling the HTTP request is as follows:

Step 1. Populate parameters and values

Common parameters:

    • app_key = “123456”
    • access_token = “test”
    • timestamp = “1517820392000”
    • sign_method = “sha256”

Business parameters:

    • order_id = “1234”

Step 2. Sort all parameters and values according to the parameter name in ASCII table

    • access_token = “test”
    • app_key = “123456”
    • order_id = “1234”
    • sign_method = “sha256”
    • timestamp = “1517820392000”

Step 3. Concatenate the sorted parameters and their values into a string

access_tokentestapp_key123456order_id1234sign_methodsha256timestamp1517820392000

Step 4. Add the API name in front of the concatenated string

/order/getaccess_tokentestapp_key123456order_id1234sign_methodsha256timestamp1517820392000

Step 5. Generate signature

Assuming that the App Secret is “helloworld”, the signature is:

hex(sha256(/order/getaccess_tokentestapp_key123456order_id1234sign_methodsha256timestamp1517820392000))=4190D32361CFB9581350222F345CB77F3B19F0E31D162316848A2C1FFD5FAB4A

Step 6. Assemble HTTP request

Encode all the parameters and values (with the “sign” parameter) using UTF-8 format (the order of parameters can be arbitrary).

https://api.miravia.es/rest/order/get?app_key=123456&access_token=test&timestamp=1517820392000&sign_method=sha256&order_id=1234&sign=4190D32361CFB9581350222F345CB77F3B19F0E31D162316848A2C1FFD5FAB4A

2. API endpoint URLs

Miravia Open Platform provides an online production environment for each Miravia venture. The data under the production environment are all true online data, providing limited times and authority of interface calling. The production environment shares data with the online system, and the true data of an online shop are directly influenced by the interface for writing class, so you must operate with caution.

The following table lists the URL of the production environment for each venture.

Venture

Server URL

spain

https://api.miravia.es

3. Requests and responses

Miravia Open Platform API supports both HTTP and HTTPS communication protocol. To ensure data security, it is recommended to make API requests using HTTPS protocol.

While most APIs are called via GET, some calls that get additional request data are sent via POST. However, sometimes the data that need to be supplied are more than what can be transported in request parameters. In those cases, additional data is sent to the server using a POST request. The request body must be in XML format. All data (including parameter names and values) must be UTF8-encoded.

Each HTTP request URL must include the path of an API. For example, the request for the “/order/get” API should be "https://api.miravia.es/rest/order/get". The common parameters and business parameters are included in the request or sent via post.

All API calls return a response document, which indicates the status of the operation (either Success or Error) and optionally provides results and/or details related to the specified action. The response is in JSON format.

4. Calling parameters

Calls to the API must include system parameters in addition to the parameters associated with the application. Different application specific parameters are needed for different specific APIs.

4.1 System parameters

System parameters are required in the HTTP request of every API call, listed in the following table:

Name

Type

Mandatory?

Description

app_key

String

Yes

The App Key that is assigned to the application.

access_token

String

Conditional

The seller authorization token, which is mandatory for the APIs that require seller authorization.

timestamp

String

Yes

Time when the request is sent, in UTC or digital format, like “2017-11-11T12:00:00Z or 1517886554000”. Note that the difference between the timestamp and UTC time should not exceed 7200 seconds.

sign_method

String

Yes

The algorithm used to generate the signature.

sign

String

Yes

The cryptographic signature, authenticating the request.

4.2 Business parameters

In addition to the system parameters that must be included in the API call request, the business parameters for the request are also required. Refer to the API documentation for details about the business parameters of each API.

5 Signature algorithm

Miravia Open Platform verifies the identity of each API request, and the server will also verify whether the call parameters are valid. Therefore, each HTTP request must contain the signature information. The requests with invalid signature will be rejected.


Miravia Open Platform verifies the identity of the requests by the App Key and Secret that are assigned to your application. The App Secret is used to generate the signature string in the HTTP request URL and server-side signature string. It must be kept strictly confidential.


If you compose HTTP request manually (instead of using the official SDK), you need to understand the following signature algorithm.


The process of generating the signature is as follows:


  • Sort all request parameters (including system and application parameters, but except the “sign” and parameters with byte array type) according to the parameter name in ASCII table. For example:
Before sort: foo=1, bar=2, foo_bar=3, foobar=4
After sort: bar=2, foo=1, foo_bar=3, foobar=4


  • Concatenate the sorted parameters and their values into a string. For example:
bar2foo1foo_bar3foobar4


  • Add the API name in front of the concatenated string. For example, adding the API name “/test/api”:
/test/apibar2foo1foo_bar3foobar4
  • Encode the concatenated string in UTF-8 format and make a digest by the signature algorithm (using HMAC_SHA256). For example:
hmac_sha256(/test/apibar2foo1foo_bar3foobar4)
  • Convert the digest to hexadecimal format. For example:
hex("helloworld".getBytes("utf-8")) = "68656C6C6F776F726C64"


Sample code for JAVA

/**
     * Sign the API request with body.
     */
    public static String signApiRequest(Map<String, String> params, String body, String appSecret, String signMethod, String apiName) throws IOException {
        // first: sort all text parameters
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // second: connect all text parameters with key and value
        StringBuilder query = new StringBuilder();
       query.append(apiName);
        for (String key : keys) {
            String value = params.get(key);
            if (areNotEmpty(key, value)) {
                query.append(key).append(value);
            }
        }

        // third:put the body to the end
        if (body != null) {
            query.append(body);
        }

        // next : sign the whole request
        byte[] bytes = null;
        
        if(signMethod.equals(Constants.SIGN_METHOD_HMAC)) {
            bytes = encryptWithHmac(query.toString(), appSecret);
        } else if(signMethod.equals(Constants.SIGN_METHOD_SHA256)) {
            bytes = encryptHMACSHA256(query.toString(), appSecret);
        }

        // finally : transfer sign result from binary to upper hex string
        return byte2hex(bytes);
    }

    
    private static byte[] encryptHMACSHA256(String data, String secret) throws IOException  {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), Constants.SIGN_METHOD_HMAC_SHA256);
            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;
    }

    /**
     * Transfer binary array to HEX string.
     */
    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();
    }


Sample code for C#

 public static string SignRequest(IDictionary<string, string> parameters, string body, string appSecret, string signMethod, string apiName)
        {
            // first : sort all key with asci order
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);

            // second : contact all params with key order
            StringBuilder query = new StringBuilder();
            query.Append(apiName);
            foreach (KeyValuePair<string, string> kv in sortedParams)
            {
                if (!string.IsNullOrEmpty(kv.Key) && !string.IsNullOrEmpty(kv.Value))
                {
                    query.Append(kv.Key).Append(kv.Value);
                }
            }

            // third : add body to last
            if (!string.IsNullOrEmpty(body))
            {
                query.Append(body);
            }

            // next : sign the string
            byte[] bytes = null;
            if (signMethod.Equals(Constants.SIGN_METHOD_SHA256))
            {
                HMACSHA256 sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(appSecret));
                bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
            }

            // finally : transfer binary byte to hex string
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                result.Append(bytes[i].ToString("X2"));
            }

            return result.ToString();
        }


Sample code for PYTHON

def sign(secret,api, parameters):
    #===========================================================================
    # @param secret
    # @param parameters
    #===========================================================================
    sort_dict = sorted(parameters)
    
    parameters_str = "%s%s" % (api,
        str().join('%s%s' % (key, parameters[key]) for key in sort_dict))

    h = hmac.new(secret.encode(encoding="utf-8"), parameters_str.encode(encoding="utf-8"), digestmod=hashlib.sha256)

    return h.hexdigest().upper()



FAQ

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