Created
December 14, 2023 12:40
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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