API开发接入
接口地址
-
新开放平台统一接口地址与请求方式,提供了 HTTP POST 请求方式的调用
公共参数
参数名称 | 是否必须 | 示例 | 备注 |
---|---|---|---|
app_key | 是 | 2312521 | 媒体应用 AppKey 查看获取方式 |
timestamp | 是 | 1596592757 | 秒级时间戳 |
service | 是 | cps-mesh.cpslink.links.post | 接口服务名称 |
sign | 是 | 5D17CCCD5B29F98171D6D0D43136B366 | 签名 |
签名过程
下面以推广转链做调用过程示例
参数示例
//公共参数
app_key=test×tamp=1596699247&service=cps-mesh.cpslink.links.post
//api参数
{"url":"https://www.jd.com","site_id":"10000"}
1、将请求的公共参数按字典序排序后 key+value 拼接
app_keytestservicecps-mesh.cpslink.links.posttimestamp1596699247
2、尾部拼接 post 请求 json 参数
app_keytestservicecps-mesh.cpslink.links.posttimestamp1596699247{"url":"https://www.jd.com","site_id":"27"}
3、两边拼接 app_secret=(媒体的推送 hash) 如何获取 AppSecret
app_secretapp_keytestservicecps-mesh.cpslink.links.posttimestamp1596699247app_secret
4、对签名字符串 MD5 后转大写得到 sign 签名参数
1326B1AA19903FC2DBCB9AF8CB365A10
5、将公共参数作为 Query 参数拼接得到请求 url
6、设置 HTTP 请求头信息,将 API 参数作为 JSON BODY
POST /apis?app_key=test×tamp=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"}
代码示例
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)