How to use AliExpress Affiliates with NodeJS
Resolve Affiliate tagging issues on AliExpress links with a quick tutorial.
Published at: 2024/3/5
I have created an Affiliate Links project called FinDrop.link where I can retrieve products form AliExpress based on dropshipping URLs or images. Everything was perfect until I have faced a problem when I was close to wrap up the project.
The problem came when I tried to use my Affiliate Account from AliExpress to tag my Affiliate ID to each link, something that sounds simple but it has been a headache since I started investigating how to do it.
Here I drop a quick tutorial on how to get affiliate links from actual AliExpress links.
- Create an account on portals.aliexpress.com
- Get your app key, and secret key
- Create a new affiliate tracking ID in Portals
- Create a server side function that looks like this:
import axios from 'axios';
import * as crypto from 'crypto';
const APP_KEY = 'YOUR_APP_KEY';
const SECRET_KEY = 'YOUR_SECRET_KEY';
function getAffiliateLink(link: string) {
const signMethod = 'sha256';
const affiliateLinkMethod = 'aliexpress.affiliate.link.generate';
// A timestamp is needed to use their API
const timestamp = new Date().getTime();
// Affiliate link parameters (Replace with your affiliate tracking ID)
const trackingId = 'YOUR_AFFILIATE_TRACKING_ID';
// Include the signature in your API request
const url = 'https://api-sg.aliexpress.com/sync';
const params = {
app_key: APP_KEY,
method: affiliateLinkMethod,
timestamp: timestamp,
v: '2.0',
tracking_id: trackingId,
promotion_link_type: 0,
source_values: link,
sign_method: signMethod,
};
// Sort all parameters and values according to the parameter name in ASCII table
const sortedParams = Object.keys(params).sort().reduce((acc, key) => {
acc[key] = params[key];
return acc;
}, {} as Record<string, string>);
// Concatenate the sorted parameters and their values into a string
const sortedParamsString = Object.entries(sortedParams)
.map(([key, value]) => `${key}${value}`)
.join('');
// Create the signature using HMAC-SHA256
const signature = crypto.createHmac(signMethod, SECRET_KEY)
.update(sortedParamsString)
.digest('hex').toUpperCase();
// Add the signature to the parameters
params['sign'] = signature;
try {
const data = (await axios.get(url, { params })).data;
// You will get back a JSON with the affiliate links
} catch (error) {
console.log(error);
}
}
I hope it helps you, and you can save some time.