Skip to content

Instantly share code, notes, and snippets.

@roelvan
Last active April 9, 2020 23:38
Show Gist options
  • Save roelvan/6a839cf098d818be839d2603f50e153d to your computer and use it in GitHub Desktop.
Save roelvan/6a839cf098d818be839d2603f50e153d to your computer and use it in GitHub Desktop.
TradeTracker redirect handler for node.js
// Tradetracker Direct Linking Redirect Page.
// https://sc.tradetracker.net/implementation/overview?f%5Btarget%5D=&f%5Bname%5D=General&f%5Bversion%5D=All&f%5BversionInfo%5D=Redirect
const crypto = require('crypto');
// Set domain name on which the redirect-page runs, WITHOUT "www.".
const DOMAIN_NAME = '';
// Set tracking group ID if provided by TradeTracker.
const TRACKING_GROUP_ID = '';
// Don't change this line
const ONE_YEAR_IN_SECS = 31536000;
const handler = async (req, res) => {
const { tt, r: redirectUrl = '' } = req.query;
// Set the P3P compact policy.
res.setHeader('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
if (!tt) {
res.writeHead(301, { Location: '/' });
return res.end();
}
const trackingParams = tt.split('_');
const [campaignId = '', materialId = '', affiliateId = '', reference = ''] = trackingParams;
// Calculate MD5 checksum.
const checkSum = crypto
.createHash('md5')
.update(`CHK_${campaignId}::${materialId}::${materialId}::${reference}`)
.digest('hex');
const timestamp = Math.floor(new Date().getTime() / 1000);
// Set tracking data.
const trackingData = encodeURIComponent(
`${materialId}::${affiliateId}::${reference}::${checkSum}::${timestamp}`
);
const cookyExpiresAt = new Date(Date.now() + ONE_YEAR_IN_SECS * 1000).toUTCString();
res.setHeader('Set-Cookie', [
// Set regular tracking cookie.
`TT2_${campaignId}=${trackingData}; Expires=${cookyExpiresAt}; Max-Age=${ONE_YEAR_IN_SECS}; Path=/; Domain=.${DOMAIN_NAME}`,
// Set session tracking cookie.
`TTS_${campaignId}=${trackingData}; Path=/; Domain=.${DOMAIN_NAME}`,
// Set tracking group cookie, if any
...(TRACKING_GROUP_ID.length > 0
? [
`__tgdat${TRACKING_GROUP_ID}=${trackingData}_${campaignId}; Expires=${cookyExpiresAt}; Max-Age: ${ONE_YEAR_IN_SECS}; Path=/; Domain=.${DOMAIN_NAME}`,
]
: []),
]);
// Set track-back URL.
const trackBackUrl = `https://tc.tradetracker.net/?c=${campaignId}&m=${materialId}&a=${affiliateId}&r=${encodeURIComponent(
reference
)}&u=${encodeURIComponent(redirectUrl)}`;
// Redirect to TradeTracker.
res.writeHead(301, { Location: trackBackUrl });
// res.setHeader('Location', trackBackUrl);
return res.end();
};
module.exports = handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment