Skip to main content

Affiliation Setup for Conversions Tracking: Custom Google Tag Manager - Server Side Setup (technical integration)

Liz Schenck avatar
Written by Liz Schenck
Updated over a week ago

Server Side Setup (optional)

Tag template

const encodeUri = require('encodeUri');
const getEventData = require('getEventData');
const log = require('logToConsole');
const sendHttpGet = require('sendHttpGet');
const getRequestHeader = require('getRequestHeader');

const LEFTY_API_BASE = "https://a.lefty.io";
const LEFTY_API_TRACK = LEFTY_API_BASE + "/track";

const emitLeftyConversion = (orderId, amount, currencyCode, products, host, ipAddress, userAgent, pixelId) => {
let uri = "type=conversion";
uri += "&orderId=" + orderId;
uri += "&amount=" + amount;
uri += "&currency=" + currencyCode;
uri += "&ref=" + host;
uri += "&ipAddress=" + ipAddress;
uri += "&userAgent=" + userAgent;
uri += "&pixelId=" + pixelId;

if (products && products.length !== 0) {
const pIds = products.map((item) => "pId=" + item.id).join("&");
const pNames = products.map((item) => "pName=" + item.name).join("&");
const itemQty = products
.map((item) => "itemQty=" + item.quantity)
.join("&");
const itemAmount = products
.map((item) => "itemAmount=" + item.amount)
.join("&");

uri += "&" + pIds;
uri += "&" + pNames;
uri += "&" + itemQty;
uri += "&" + itemAmount;
}

const url = LEFTY_API_TRACK + "?" + encodeUri(uri);

sendHttpGet(url).then((result) => {
if (result.statusCode >= 200 && result.statusCode < 300) {
data.gtmOnSuccess();
} else {
data.gtmOnFailure();
}
}).catch((error) => {
log("Error sending HTTP request to Lefty: " + error.message + ". URL: " + url);
data.gtmOnFailure();
});
};

const eventName = data.eventName || getEventData('event_name');
if (eventName !== 'lefty_conversion') {
data.gtmOnFailure();
return;
}

const host = getRequestHeader('host');

// AUTOMATIC Event Data
const ipAddress = getEventData('ip_override');
const userAgent = getEventData('user_agent');
const pixelId = '[[ YOUR_PIXEL_ID ]]';

const orderId = getEventData('orderId');
if (!orderId) {
log("Order ID not found");
data.gtmOnFailure();
return;
}

const amount = getEventData('amount');
if (!amount) {
log("Order amount not found");
data.gtmOnFailure();
return;
}

const currencyCode = getEventData('currencyCode');
if (!currencyCode) {
log("Order currency not found");
data.gtmOnFailure();
return;
}

const products = getEventData('products') || [];

emitLeftyConversion(
orderId,
amount,
currencyCode,
products,
host,
ipAddress,
userAgent,
pixelId
);

Emit event:

gtag('event', 'lefty_conversion', {
orderId: string,
amount: number,
// ex: "USD"
currencyCode: string,
// products list
products: [
{
id: string,
name: string,
quantity: number,
amount: number,
},
{
id: string,
name: string,
quantity: number,
amount: number,
},
{
id: string,
name: string,
quantity: number,
amount: number,
},
]
});

Did this answer your question?