'use strict'; const pddSign = require('./pdd_sign'); const DEFAULT_BASE_URL = 'https://gw-api.pinduoduo.com/api/router'; /** * 判断输入是否为普通对象。 * @param {*} value 任意输入值。 * @return {boolean} 是否为普通对象。 */ function isPlainObject(value) { return Object.prototype.toString.call(value) === '[object Object]'; } /** * 获取当前秒级时间戳。 * @return {string} 秒级 UNIX 时间戳。 */ function nowSec() { return String(Math.floor(Date.now() / 1000)); } /** * 拼多多开放平台 API 客户端。 * 负责组装请求体、生成签名、发送请求。 */ class PddClient { /** * @param {object} ctx - Egg 上下文对象。 * @param {object} [options={}] - 客户端默认配置。 */ constructor(ctx, options = {}) { this.ctx = ctx; this.options = options; } /** * 解析客户端凭据。 * @param {object} [options={}] 请求级配置。 * @return {{ clientId: string, clientSecret: string }} 凭据。 */ resolveCredentials(options = {}) { const config = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {}; const clientId = options.clientId ?? this.options.clientId ?? config.client_id ?? config.clientId ?? ''; const clientSecret = options.clientSecret ?? this.options.clientSecret ?? config.client_secret ?? config.clientSecret ?? ''; return { clientId: String(clientId || '').trim(), clientSecret: String(clientSecret || '').trim(), }; } /** * 构建请求体。 * @param {object} [options={}] 请求参数。 * @return {{ requestBody: object, signText: string, sortedPairs: Array<[string, string]> }} 请求体和签名信息。 */ buildRequest(options = {}) { const { type, bizParams = {}, request = {}, accessToken, dataType = 'JSON', version, timestamp = nowSec(), } = options; const { clientId, clientSecret } = this.resolveCredentials(options); const payload = isPlainObject(bizParams) ? { ...bizParams } : {}; if (isPlainObject(request)) { Object.assign(payload, request); } const signed = pddSign.buildRequestBody({ type, clientId, timestamp, dataType, accessToken, version, bizParams: payload, clientSecret, }); return signed; } /** * 发起拼多多 API 请求。 * @param {object} [options={}] 请求参数。 * @return {Promise} 接口响应。 */ async request(options = {}) { const { baseUrl = DEFAULT_BASE_URL, headers = {}, timeout, responseType = 'json', } = options; if (!baseUrl) { throw new Error('baseUrl 不能为空'); } const { requestBody } = this.buildRequest(options); const response = await this.ctx.curl(String(baseUrl), { method: 'POST', dataType: responseType, timeout, headers: { 'Content-Type': 'application/json', ...(headers || {}), }, data: requestBody, }); return response && response.data !== undefined ? response.data : response; } /** * 同步调用接口,和 request 等价。 * @param {object} [options={}] 请求参数。 * @return {Promise} 接口响应。 */ async syncInvoke(options = {}) { return this.request(options); } /** * 异步调用接口,和 request 等价。 * @param {object} [options={}] 请求参数。 * @return {Promise} 接口响应。 */ async asyncInvoke(options = {}) { return this.request(options); } } module.exports = PddClient;