Skip to content

Instantly share code, notes, and snippets.

@cloudhooks
Created December 14, 2023 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudhooks/761f98dbb7beda35863e1af39e894d17 to your computer and use it in GitHub Desktop.
Save cloudhooks/761f98dbb7beda35863e1af39e894d17 to your computer and use it in GitHub Desktop.
Sends a purchase event to Google Analytics (the hook expects an order payload)
const API_SECRET = '[Your GA4 API secret]';
const MEASUREMENT_ID = '[Your GA4 measurement id]';
module.exports = async function(payload, actions, context) {
const gaUrl = 'https://www.google-analytics.com/mp/collect' +
`?api_secret=${API_SECRET}` +
`&measurement_id=${MEASUREMENT_ID}`;
const gaData = {
client_id: 'Cloudhooks',
user_id: payload.customer.id.toString(),
events: [
{
name: 'purchase',
params: {
transaction_id: payload.order_number.toString(),
currency: payload.currency,
value: parseFloat(payload.current_total_price),
items: payload.line_items.map( (item) => {
return {
item_name: item.name,
quantity: item.quantity,
price: parseFloat(item.price)
};
})
}
}
]
};
try {
// Google Analytics always returns HTTP 200
// No need to check return value
await actions.http.post(
gaUrl, gaData,
{headers: {'Content-Type': 'application/json'}}
);
} catch (err) {
console.log('GA error: ' + err);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment