Skip to content

Commit

Permalink
GA4 Data Layer Push for purchase events (#2246)
Browse files Browse the repository at this point in the history
  • Loading branch information
JenniWhitman authored Jul 24, 2024
1 parent 69912d6 commit b50a3f4
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 8 deletions.
10 changes: 7 additions & 3 deletions ecommerce/templates/checkout_interstitial.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,19 @@
<div class="content-col">
<div class="text">
<h1 class="mt-4">Redirecting to the payment processor...</h1>

<form id="checkout_form" method="post" action="{{ checkout_payload.url }}">
{% for key, value in form.items %}
<input type="hidden" readonly="readonly" name="{{ key }}" value="{{ value }}" />
{% endfor %}
</form>

{% if ga_purchase_flag %}
<script type="text/javascript">
const ga_purchase_payload = JSON.parse({{ ga_purchase_payload|safe }});
gtag("event", "purchase", ga_purchase_payload);
</script>
{% endif %}
<script type="text/javascript">
document.getElementById('checkout_form').submit();
document.getElementById('checkout_form').submit();
</script>
</div>
</div>
Expand Down
59 changes: 58 additions & 1 deletion ecommerce/views/v0/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import RedirectView, TemplateView, View
from mitol.common.utils import now_in_utc
from mitol.olposthog.features import is_enabled as is_posthog_enabled
from mitol.payment_gateway.api import PaymentGateway
from rest_framework import mixins, status
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
Expand Down Expand Up @@ -68,6 +69,7 @@
from flexiblepricing.api import determine_courseware_flexible_price_discount
from flexiblepricing.models import FlexiblePriceTier
from flexiblepricing.serializers import FlexiblePriceTierSerializer
from main import features
from main.constants import (
USER_MSG_TYPE_PAYMENT_ACCEPTED,
USER_MSG_TYPE_PAYMENT_CANCELLED,
Expand Down Expand Up @@ -705,6 +707,41 @@ def get_redirect_url(self, *args, **kwargs):
class CheckoutInterstitialView(LoginRequiredMixin, TemplateView):
template_name = "checkout_interstitial.html"

def _create_ga4_context(self, order):
lines = order.lines.all()
payload_items = []
if len(lines) > 0:
for line in lines:
related_learning_object = line.purchased_object
if related_learning_object:
line_object = {
"item_id": line.purchased_object_id,
"item_name": line.item_description,
"affiliation": "MITx Online",
"discount": line.discounted_price,
"price": line.total_price,
"quantity": line.quantity,
"item_category": "Series",
}
if line.purchased_content_type.model == "programrun":
line_object["item_category"] = (
related_learning_object.program.program_type
)
payload_items.append(line_object)
ga_purchase_payload = {
"transaction_id": order.reference_number,
"value": order.total_price_paid,
"tax": 0.00,
"shipping": 0.00,
"currency": "USD",
"items": payload_items,
}
if order.discounts.count() > 0:
ga_purchase_payload["coupon"] = ",".join(
[discount.discount_code for discount in order.discounts]
)
return ga_purchase_payload

def get(self, request): # noqa: PLR0911
try:
checkout_payload = api.generate_checkout_payload(request)
Expand All @@ -721,10 +758,30 @@ def get(self, request): # noqa: PLR0911
if "invalid_discounts" in checkout_payload:
return checkout_payload["response"]

context = {
"checkout_payload": checkout_payload,
"form": checkout_payload["payload"],
}

ga_purchase_flag = is_posthog_enabled(
features.ENABLE_GOOGLE_ANALYTICS_DATA_PUSH,
False, # noqa: FBT003
self.request.user.id,
)
ga_purchase_payload = None
if ga_purchase_flag:
order = Order.objects.get(
reference_number=checkout_payload["payload"]["reference_number"]
)
if order:
ga_purchase_payload = self._create_ga4_context(order)
context["ga_purchase_flag"] = ga_purchase_flag
context["ga_purchase_payload"] = ga_purchase_payload

return render(
request,
self.template_name,
{"checkout_payload": checkout_payload, "form": checkout_payload["payload"]},
context,
)


Expand Down
2 changes: 2 additions & 0 deletions main/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
IGNORE_EDX_FAILURES = "IGNORE_EDX_FAILURES"
SYNC_ON_DASHBOARD_LOAD = "SYNC_ON_DASHBOARD_LOAD"
ENABLE_AUTO_DAILY_FEATURED_ITEMS = "mitxonline-auto-daily-featured-items"

ENABLE_GOOGLE_ANALYTICS_DATA_PUSH = "mitxonline-4099-dedp-google-analytics"
12 changes: 8 additions & 4 deletions main/templates/partials/gtm_body.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
{% if APIKEYS.GTM_TRACKING_ID %}
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={{ APIKEYS.GTM_TRACKING_ID }}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ APIKEYS.GTM_TRACKING_ID }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', '{{ APIKEYS.GTM_TRACKING_ID }}');
</script>
{% endif %}

0 comments on commit b50a3f4

Please sign in to comment.