@liuliang520500/pdd-sdk-new
Version:
拼多多开放平台 SDK,支持多多进宝商品推广、订单查询等接口
84 lines (83 loc) • 2.63 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PddClient = void 0;
const axios_1 = __importDefault(require("axios"));
const crypto_1 = __importDefault(require("crypto"));
/**
* 拼多多开放平台客户端
*/
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_1.default.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_1.default.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;
}
}
}
exports.PddClient = PddClient;