API Agreement

5 min read

interface address

  • The unified interface address and request method of the new development platform provide a unified HTTP POST request method call

Public parameters

Parameter nameIs it necessaryExampleRemarks
app_keyyes2312521Media application appkey original siteid
timestampyes1596592757Second-level timestamp
serviceyescps-mesh.cpslink.links.postinterface service name
signyes5D17CCCD5B29F98171D6D0D43136B366sign

Signing process

The following is an example of the calling process by promoting the transfer chain

Parameter example

//Common Parameter
app_key=test&timestamp=1596699247&service=cps-mesh.cpslink.links.post
//API Parameter
{"url":"https://www.jd.com","site_id":"27"}

1. Sort the requested public parameters in lexicographic order and then key+value splicing

app_keytestservicecps-mesh.cpslink.links.posttimestamp1596699247

2. The post request json parameters are spliced ​​at the end, please ignore the GET request

app_keytestservicecps-mesh.cpslink.links.posttimestamp1596699247 {"url":"https://www.jd.com","site_id":"27"}

3. Splicing on both sides app_secret=(media push hash) View hash

app_secretapp_keytestservicecps-mesh.cpslink.links.posttimestamp 1596699247app_secret

4. Convert the signature string MD5 to uppercase to get the sign signature parameter

1326B1AA19903FC2DBCB9AF8CB365A10

5. Splice the public parameters as Query parameters to get the request url

https://open.duomai.com/apis?app_key=test×tamp=1596699247&service=cps-mesh.cpslink.links.post&sign=1326B1AA19903FC2DBCB9AF8CB365A10

6. Set HTTP request header information, and use API parameters as JSON BODY

POST /apis?app_key=test&timestamp=1596699247&service=cps-mesh.cpslink.links.post&sign=1326B1AA19903FC2DBCB9AF8CB365A10 HTTP/1.1
Host: open.duomai.com
Content-Type: application/json

{"url":"https://www.jd.com","site_id":"27"}

Code example

php

    $appKey = "your siteId";
    $appSecret = "your hash";
    $header = [
        "Content-Type" => "application/json"
    ];
    $query = [
        "app_key" => $appKey,
        "timestamp" => time(),
        "service"=> "cps-mesh.cpslink.links.post"
    ];
    ksort($query);
    $signStr = '';
    foreach ($query as $kev => $val) {
        $signStr .= $kev . $val;
    }
    $body = json_encode([
        "url"=>"https://www.jd.com",
        "site_id"=>"27",
    ]);
    $query["sign"] = strtoupper(md5($appSecret . $signStr . $body . $appSecret));
    try {
        $client = new \GuzzleHttp\Client();
        $response = $client->request('POST', "https://open.duomai.com/apis", [
            "verify"=>false,
            "headers" => $header,
            "query" => $query,
            "body"=> $body
        ]);
    } catch (ClientException $e) {
        $response = $e->getResponse();
    }
    echo $response->getStatusCode();
    echo $response->getHeaderLine('content-type');
    echo $response->getBody()->getContents();die;

golang

    AppKey := "test"
    AppSecret := "test"
    Router:= "https://open.duomai.com/apis/"
    Service:="cps-mesh.cpslink.links.post"
    var body []byte
    params := map[string]string{
        "url":"https://www.jd.com",
        "site_id":"27",
    }
    body,_ = json.Marshal(params)

    nowTime := time.Now().Local()
    // 设置get参数
    val := url.Values{}
    val.Set("timestamp", fmt.Sprintf("%d", nowTime.Unix()))
    val.Set("app_key", AppKey)
    val.Set("service", Service)
    var buf strings.Builder
    keys := make([]string, 0, len(val))
    for k := range val {
        keys = append(keys, k)
    }
    sort.Strings(keys)
    for _, k := range keys {
        vs := val[k]
        keyEscaped := url.QueryEscape(k)
        for _, v := range vs {
            buf.WriteString(keyEscaped)
            buf.WriteString(url.QueryEscape(v))
        }
    }
    // 签名string
    signStr := fmt.Sprintf("%s%s%s%s", AppSecret, buf.String(), string(body), AppSecret)
    // 设置签名
    hash := md5.New()
    hash.Write([]byte(signStr))
    val.Set("sign", strings.ToUpper(fmt.Sprintf("%x", hash.Sum(nil))))
    // 请求
    reqest, _ := http.NewRequest("POST", fmt.Sprintf("%s%s?%s", Router, Service, val.Encode()), bytes.NewBuffer(body))
    reqest.Header.Add("Content-Type", "application/json")
    httpClient := &http.Client{}
    var response *http.Response
    response, err := httpClient.Do(reqest)
    if err != nil {
        return
    }
    defer response.Body.Close()
    byteData, err := ioutil.ReadAll(response.Body)

java

    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.time.Instant;
    import java.util.ArrayList;
    import java.util.Base64;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.TreeMap;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class ApiRequest {
    
        public static void main(String[] args) {
            String appKey = "test";
            String appSecret = "test";
            String router = "https://open.duomai.com/apis/";
            String service = "cps-mesh.cpslink.links.post";
    
            Map<String, String> params = Map.of(
                "url", "https://www.jd.com",
                "site_id", "27"
            );
    
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                String body = objectMapper.writeValueAsString(params);
    
                long timestamp = Instant.now().getEpochSecond();
    
                Map<String, String> query = new TreeMap<>();
                query.put("timestamp", String.valueOf(timestamp));
                query.put("app_key", appKey);
                query.put("service", service);
    
                List<String> keys = new ArrayList<>(query.keySet());
                Collections.sort(keys);
    
                StringBuilder buf = new StringBuilder();
                for (String key : keys) {
                    buf.append(key).append(query.get(key));
                }
    
                String signStr = appSecret + buf + body + appSecret;
                String sign = generateMD5(signStr).toUpperCase();
                query.put("sign", sign);
    
                StringBuilder queryString = new StringBuilder();
                for (Map.Entry<String, String> entry : query.entrySet()) {
                    if (queryString.length() > 0) {
                        queryString.append("&");
                    }
                    queryString.append(entry.getKey()).append("=").append(entry.getValue());
                }
    
                URL url = new URL(router + service + "?" + queryString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);
    
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = body.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
    
                int responseCode = connection.getResponseCode();
                System.out.println("Response Code: " + responseCode);
                String response = new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
                System.out.println("Response: " + response);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static String generateMD5(String input) throws Exception {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder(2 * hash.length);
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        }
    }

python

   import requests
   import time
   import hashlib
   import json
   
   app_key = "your siteId"
   app_secret = "your hash"
   headers = {
       "Content-Type": "application/json"
   }
   query = {
       "app_key": app_key,
       "timestamp": int(time.time()),
       "service": "cps-mesh.cpslink.links.post"
   }
   
   # 排序并生成签名字符串
   sign_str = ''.join(f"{key}{value}" for key, value in sorted(query.items()))
   
   body = json.dumps({
       "url": "https://www.jd.com",
       "site_id": "27",
   })
   
   # 计算签名
   sign = hashlib.md5((app_secret + sign_str + body + app_secret).encode()).hexdigest().upper()
   query["sign"] = sign
   
   try:
       response = requests.post("https://open.duomai.com/apis", headers=headers, params=query, data=body, verify=False)
       print(response.status_code)
       print(response.headers['content-type'])
       print(response.text)
   except requests.exceptions.RequestException as e:
       print(e)