@liuliang520500/pdd-sdk-new
Version:
拼多多开放平台 SDK,支持多多进宝商品推广、订单查询等接口
77 lines (76 loc) • 2.29 kB
JavaScript
import axios from 'axios';
import crypto from 'crypto';
/**
* 拼多多开放平台客户端
*/
export class PddClient {
/**
* 构造函数
* @param config 客户端配置
*/
constructor(config) {
this.clientId = config.clientId;
this.clientSecret = config.clientSecret;
this.accessToken = config.accessToken;
this.serverUrl = config.serverUrl || 'https://gw-api.pinduoduo.com/api/router';
this.debug = config.debug || false;
this.axios = axios.create({
baseURL: this.serverUrl,
timeout: 30000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
/**
* 生成签名
* @param params 请求参数
* @returns 签名字符串
*/
generateSign(params) {
const sortedKeys = Object.keys(params).sort();
let signStr = this.clientSecret;
for (const key of sortedKeys) {
const value = params[key];
if (key !== 'sign' && value !== undefined && value !== null && value !== '') {
signStr += key + value;
}
}
signStr += this.clientSecret;
return crypto.createHash('md5')
.update(signStr)
.digest('hex')
.toUpperCase();
}
/**
* 执行接口请求
* @param params 业务参数
* @returns 接口响应
*/
async execute(params) {
const commonParams = {
client_id: this.clientId,
timestamp: Math.floor(Date.now() / 1000).toString(),
data_type: 'JSON',
version: 'V1'
};
if (this.accessToken) {
commonParams.access_token = this.accessToken;
}
const requestParams = {
...commonParams,
...params
};
requestParams.sign = this.generateSign(requestParams);
try {
const response = await this.axios.post('', new URLSearchParams(requestParams));
if (response.data.error_response) {
throw new Error(JSON.stringify(response.data.error_response));
}
return response.data;
}
catch (error) {
throw error;
}
}
}