Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Making an API call to the AliExpress Affiliate API. Explains how to sign the request and create the correct hash.
import crypto from "crypto";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
dayjs.extend(utc);
dayjs.extend(timezone);
const API_URL = "http://gw.api.taobao.com/router/rest";
const API_SECRET = "FIND THIS IN THE AE CONSOLE";
const API_KEY = "FIND THIS IN THE AE CONSOLE";
const hash = (method, s, format) => {
const sum = crypto.createHash(method);
const isBuffer = Buffer.isBuffer(s);
if (!isBuffer && typeof s === "object") {
s = JSON.stringify(sortObject(s));
}
sum.update(s, "utf8");
return sum.digest(format || "hex");
};
const sortObject = (obj) => {
return Object.keys(obj)
.sort()
.reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
};
const signRequest = (parameters) => {
const sortedParams = sortObject(parameters);
const sortedString = Object.keys(sortedParams).reduce((acc, objKey) => {
return `${acc}${objKey}${sortedParams[objKey]}`;
}, "");
const bookstandString = `${API_SECRET}${sortedString}${API_SECRET}`;
const signedString = hash("md5", bookstandString, "hex");
return signedString.toUpperCase();
};
export const getProductById = async (productId: string) => {
const timestamp = dayjs().tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss");
const payload = {
method: "aliexpress.affiliate.productdetail.get",
app_key: API_KEY,
sign_method: "md5",
timestamp,
format: "json",
v: "2.0",
product_ids: productId,
target_currency: "USD",
target_language: "EN",
};
const sign = signRequest(payload);
const allParams = {
...payload,
sign,
};
const res = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
},
body: new URLSearchParams(allParams),
});
return await res.json()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment