Guide: How to use the AliExpress Affiliate API with Nodejs

●5 MIN READ

Guide: How to use the AliExpress Affiliate API with Nodejs

For my Aliexpress price tracker, AliWatcher, I wanted to implement the AliExpress API to not be solely dependant on datafeeds for the product data. With the API I can search product, fetch product information, get product recommendations, and more. Good stuff!

However, it took me some figuring out to get things working. The docs are mostly in Chinese (but readable/understandable with Google Translate), the signing of the API call was not 100% clear to me and the SDK was download only (no official NPM package).

So let’s see how I managed to get it working, for example to get recommendations (as you can see in the bottom of any product on AliWatcher).

If you’re having trouble to manage to get it working but you already made an account, you can just copy this code. Below the code I explain how to make a developer account, and go through the code line by line.

Code Sample

With this code sample you can fetch product detail of a product on AliExpress by ID. You can find the ID of a product in the URL, e.g https://www.aliexpress.com/item/**4000669887458**.html

I put the code in this blogpost as a Github gist here: How to make an API request to the AliExpress Affiliate API

If you have any questions about the code, feel free to comment on the gist!


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()
}

Making an AliExpress Affiliate App

When you’ve created a developer account on AliExpress’ developer platform you can go to the console. Remember, Google Translate is your friend if you don’t speak any Chinese.

If you are redirected through Taobao.com, that’s completely fine. I found that AliExpress and Taobao are really interwoven. Example of this in the code snippet above: to fetch product details from AliExpress we have to send an api request to the Taobao API.

When you’re in the console you can create an app. The first thing required is to select the app type. For this we want the “Affiliates API”.

When you created the app and click on it, you’ll see the App Key and the App Secret. Those two you need to make calls to the AliExpress API.

To get access to the hot products query and the smart match api, you will need to obtain extra API permissions. The Standard API for Publishers is “gained” by default.

Making your first API call

The main docs for the AliExpress affiliate API can be found here.

These are (in my opinion) the most handy API endpoints:

API method Action
aliexpress.affiliate.product.query Search for a product by keyword, price, delivery days and country availability
aliexpress.affiliate.hotproduct.query Get the top selling products
aliexpress.affiliate.productdetail.get Get a product detail by product ID
aliexpress.affiliate.product.smartmatch Recommends product by either device_id (adid or idfa) or product_id (like a recommendation engine)

Signing your API

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();
};

The hardest part of the API was signing the API request. Per the docs here, this is how you sign a request:

  1. Check which parameters you need. The ones required are: method, app_key, timestamp (in the right timezone), v, sign_method and sign.
  2. Sort all the request parameters, minus the “sign” key.
  3. Then make a long string with all those parameters concatenated, just _key_value_key_value_key_value
  4. As we use the md5 algorithm to encode it, we create a new string where our previously created longstring of parameters is between our secret key, like two bookstands: secret_keylongstringsecret_key
  5. Then hash the last string with the md5 algorithm, to hex.
  6. This is now the value we send with our params as the sign key in our request
  7. Now we send a POST request to the API endpoint (always POST, even if the method looks like a GET, e.g. aliexpress.affiliate.productdetail.get.
  8. Make sure the Content-Type in the headers equals to application/x-www-form-urlencoded;charset=utf-8.
  9. With fetch you can set the body as new URLSearchParams(ourParams). If you use something like axios, I assume it’s the same but it’s better to check the docs to make sure.

Remarks

I use dayjs to create the correct timestamp with the right Timezone. However, you can use any dateformatting library (such as Momentjs) you are comfortable with. Just make sure the timestamp is in the format YYYY-MM-DD HH:mm:ss.

I implemented the md5 hash method by myself, as I didn’t get the crypto-js hash method to work. If you’re more familiar with crypto-js than I am, feel free to comment how to do that on the github gist I created.


This is how I make API requests with my AliExpress Price Tracker called AliWatcher. With the API you can fetch product info, category information, top selling products, product recommendations and more.

I hope this guide helped you to make API requests.

Keep on hacking!

Jelle

More polaroids I want to share

CLICK OR DRAG THE TOP ONE ASIDE

You've reached the end of the shoebox. More polaroids and other posts live on my Instagram.

@GMJELLE →
Polaroid of a calm lake at dusk reflecting pink clouds and dark hills, at a wild campsite near Adana, Turkey
Polaroid of Josip Broz Tito's marble tomb seen through plant leaves in Belgrade, Serbia
Polaroid of a motorcycle parked at a Soviet-era bus stop decorated with a flower mosaic in Moldova
Polaroid of a large stone statue of a bearded man in a long coat on a hillside near Buzludzha, Bulgaria
Polaroid of the saucer-shaped Buzludzha Monument on a distant hilltop above the trees in Bulgaria
Polaroid of a man standing in front of the Buzludzha Monument and its tower in Bulgaria
Polaroid of a valley of pale, cone-shaped rock formations in Cappadocia, Turkey
Polaroid of hot air balloons silhouetted against the dawn sky in Cappadocia, Turkey
Polaroid of the brutalist Cosmos Hotel tower in Chisinau, Moldova
Polaroid of the Tomb of Cyrus the Great on its stepped stone base at Pasargadae, Iran
Polaroid of a close view of the Tomb of Cyrus the Great at Pasargadae, Iran
Polaroid of a converted red fire truck camper and a motorcycle at a campsite on the west coast of Turkey
Polaroid of a mosque minaret and domes silhouetted against a cloudy sky in Edirne, Turkey
Polaroid of the Mimar Sinan statue in front of the Selimiye Mosque in Edirne, Turkey
Polaroid of the courtyard of a historic house with a fountain and colored-glass windows in Isfahan, Iran
Polaroid of a man standing next to an Isfahan city emblem sign on a sidewalk in Isfahan, Iran
Polaroid of the tiled dome and entrance portal of the Sheikh Lotfollah Mosque in Isfahan, Iran
Polaroid of the tiled entrance portal and twin minarets of the Shah Mosque in Isfahan, Iran
Polaroid of a columned palace silhouetted at sunset behind a fountain pool on Naqsh-e Jahan Square, Isfahan, Iran
Polaroid of a dark interior lit through colorful stained-glass windows in a historic house in Isfahan, Iran
Polaroid of rocky ridges and rock formations under a cloudy sky near Goreme, Cappadocia, Turkey
Polaroid of a loaded motorcycle parked by a desert road with mountains behind it in Iran
Polaroid of a loaded motorcycle with a helmet on the mirror, parked on a coastal road near Izmir, Turkey
Polaroid of a Soviet-era mosaic of workers and a motorcyclist on a building wall in Lutsk, Ukraine
Polaroid of a Soviet-era mosaic of a crowned woman holding scales, framed by tree leaves in Lviv, Ukraine
Polaroid of the Lviv Opera House facade with a fountain in front in Lviv, Ukraine
Polaroid of a Soviet WWII memorial column with a stork's nest on top in northern Moldova
Polaroid of a large Soviet-era mural of figures on a wall beside a tree in Moldova
Polaroid of royal tombs carved into the cliff face at Naqsh-e Rustam near Persepolis, Iran
Polaroid of a stone relief of a Persian soldier holding a spear at Persepolis, Iran
Polaroid of the Gate of All Nations with its winged bull statues and columns at Persepolis, Iran
Polaroid of four men sharing dinner at a table in a traditional hostel in Shiraz, Iran
Polaroid of the tiled courtyard and reflecting pool of the Nasir al-Mulk (Pink) Mosque in Shiraz, Iran
Polaroid of two men smiling at a restaurant table in Tabriz, Iran
Polaroid of the mirrored hall of Golestan Palace lit by large chandeliers in Tehran, Iran
Polaroid of the bronze statue of Leonidas raising a spear at the Thermopylae monument, Greece
Polaroid of a man looking up at the wooden Trojan Horse from the Troy film in Canakkale, Turkey
Polaroid of a backgammon board on a table overlooking the sea at a campsite in Turkey
Polaroid of a Soviet-era mosaic of a woman in traditional dress under a Ukrainian coat of arms in Ukraine
Polaroid of a motorcycle parked at a bus stop with a mosaic of three knights in Ukraine
Polaroid of a man standing on a boardwalk in front of the stairway of the Ziggurat of Ur, Iraq
Polaroid looking up the brick stairway of the Ziggurat of Ur, Iraq
Polaroid of eroded mud-brick ruins with a small sign in front at Uruk, Iraq
Polaroid of a man and two boys crouching by a freshly slaughtered sheep on grass on the road to Van, Turkey
Polaroid looking up at the curved glass Zlota 44 skyscraper in Warsaw, Poland
Polaroid of the Palace of Culture and Science lit at dusk in Warsaw, Poland
Polaroid of the Zoroastrian Fire Temple with a round reflecting pool in Yazd, Iran