Send event to Google Analytics 4

You can send recommended events and custom events to Google Analytics via the Measurement Protocol .

The following example 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);
  }
};

Please note that it takes 24-48 hours for the event to show up in reports.

For more examples, you can visit our Gist page on Github.