I have a gateway that allows users pay for subscriptions. So once the user makes a payment a notification is sent through a webhook to our site along with the order id, amount, product name etc... and we update the database accordingly.
What i want to do is integrate Google eCommerce tracking. The problem is that the gateway does not redirect back to our site, instead it posts the values to the webhook.
Below is my tracking code.
ga('ecommerce:addTransaction', {
'id': '<?php $_POST['orderid'] ?>',
'affiliation': '<?php $_POST['company'] ?>',
'revenue': '<?php $_POST['amount'] ?>',
'shipping': '<?php $_POST['shipping_cost'] ?>',
'tax': '<?php $_POST['tax'] ?>',
'currency': 'EUR'
});
although i have added the above code to the webhook, it updates the database but it does not trigger the analytics event. I think its because the page needs to be opened in order to execute the JS code.
The same code has been added to another page and it works fine.
Is it possible to trigger the JS event when the data is posted to the webhook?
Are you missing the echo
keyword to output the strings? Also, you really need to escape those variables.
I would highly recommend getting PHP to do the grunt work here:
ga('ecommerce:addTransaction', <?php
echo json_encode([
"id" => $_POST['orderid'],
"affiliation" => $_POST['company'],
"revenue" => $_POST['revenue'],
"shipping" => $_POST['shipping'],
"tax" => $_POST['tax'],
"currency" => "EUR"
], JSON_PRETTY_PRINT);
?>);
Using json_encode
ensures that all your values are properly escaped and that you output valid JSON (which is also valid javascript).
It's not possible to know if this will solve your issue based on the information you have provided; if it doesn't work and you need more help, please post a stackblitz example or a more complete version.