Skip to content

Instantly share code, notes, and snippets.

@vovafeldman
Last active April 8, 2021 16:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vovafeldman/a19a6c92838dcaa416ec7063a01dc6c9 to your computer and use it in GitHub Desktop.
Save vovafeldman/a19a6c92838dcaa416ec7063a01dc6c9 to your computer and use it in GitHub Desktop.
Freemius Purchase Completion JavaScript Callback Filter
<?php
// Add GA tracking only if user opted-in OR if non-WP.org compliant product.
function my_after_purchase_js( $js_function ) {
return 'function ( response ) {
/**
* Since the user just entered their personal & billing information, agreed to the TOS & privacy,
* know they are running within a secure iframe from an external domain, they implicitly permit tracking
* this purchase. So initizlizing GA here (after the purchase), is legitimate.
*/
ga('create', 'UA-XXXXXXX', 'auto');
console.log("checkout", "purchaseCompleted");
}';
}
function my_checkout_enrich ( $html ) {
return '<script type="text/javascript">
(function() {
if ( null == ga ) {
// Add code to include GA.
}
})();
</script>' . $html;
}
my_freemius()->add_filter('checkout/purchaseCompleted', 'my_after_purchase_js');
my_freemius()->add_filter('templates/checkout.php', 'my_checkout_enrich');
?>
@hqwebs
Copy link

hqwebs commented Mar 26, 2021

Hi,

Below is an example with Google Tag Manager.

my_freemius()->add_filter('checkout/purchaseCompleted', function ($js_function) {
	return "function ( response ) {
	    window.dataLayer = window.dataLayer || []
	    function gtag(){dataLayer.push(arguments)}
	    gtag('js', new Date())
            gtag('config', 'UA-XXXXXXXXXXX', {
	      'cookie_domain': 'example.com'
	    });
           var
		isTrial = (null != response.purchase.trial_ends),
		isSubscription = (null != response.purchase.initial_amount),
		total = isTrial ? 0 : (isSubscription ? response.purchase.initial_amount : response.purchase.gross).toString()
	    window.dataLayer.push({
		'event': 'purchase',
		'price': total
	    })
	}"
});

my_freemius()->add_filter('templates/checkout.php', function ($html) {
	return '<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXXXX"></script>' . $html;
});

@brjosue73
Copy link

@hqwebs This might be a silly question, but where should I add this code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment