Django Stripe UTM tracking: Checkout in Python
By Devendra Variya, co-founder of Virling. Published 2026-11-20, updated 2026-11-29.
In Django, attribution lives in the view that creates the Stripe Checkout Session: read virling_vid from request.COOKIES and pass it to stripe.checkout.Session.create() as client_reference_id. This post shows that as a function view and as a class-based view, the CSRF token the checkout form needs, and where the Stripe key goes in your settings.
Stripe Checkout runs on checkout.stripe.com, so the UTM tags in your landing URL never reach it. The Virling script stores them against a visitor ID in a first-party cookie, and Virling joins any payment that carries the ID to the visits behind it; Payment Links and metadata limits are in the general guide to Stripe Checkout UTM parameters. Other stacks: Flask, Next.js, Laravel, Symfony, Phoenix and Spring Boot with stripe-java. Selling through Paddle instead? Paddle UTM tracking in Django passes the same cookie to Paddle Checkout as custom data.
The Stripe key in settings
Keep the secret key out of the repository and expose it as a setting. With django-environ, read it from the environment or a .env file next to manage.py:
# settings.py
import environ
env = environ.Env()
environ.Env.read_env(BASE_DIR / ".env")
STRIPE_SECRET_KEY = env("STRIPE_SECRET_KEY")Without django-environ, STRIPE_SECRET_KEY = os.environ["STRIPE_SECRET_KEY"] does the same. Code elsewhere reads it as settings.STRIPE_SECRET_KEY from django.conf. Checkout that redirects to session.url needs no publishable key.
The script tag in base.html
Add the tag before </head> in the template your pages extend, usually templates/base.html. The template engine only touches {{ }} and {% %}, so the tag is sent as written. On a self-hosted server, change app.virling.com to your own host.
<!-- templates/base.html --> <script defer src="https://app.virling.com/v.js" data-site="yourdomain.com"></script>
A function view
request.COOKIES is a plain dictionary of the cookies the browser sent, so .get() gives the visitor ID or None. Use it rather than get_signed_cookie(): the script writes the cookie in the browser, and there is no Django signature on it to verify.
# billing/views.py
import stripe
from django.conf import settings
from django.shortcuts import redirect
from django.views.decorators.http import require_POST
stripe.api_key = settings.STRIPE_SECRET_KEY
@require_POST
def checkout(request):
params = {
"line_items": [{"price": "price_...", "quantity": 1}],
"mode": "subscription",
"success_url": "https://yourdomain.com/thanks",
}
vid = request.COOKIES.get("virling_vid")
if vid:
params["client_reference_id"] = vid
session = stripe.checkout.Session.create(**params)
return redirect(session.url)Route it in billing/urls.py with path("checkout/", views.checkout, name="checkout"). @require_POST answers any other method with 405, and Django's cache stores only GET and HEAD responses, so a session is never served to a second buyer. A plain def view can make the blocking Stripe call directly; for the same call in an async framework, the FastAPI and Stripe Checkout guide compares def and async def routes.
Or a class-based view
A subclass of View answers only the methods it defines, so a post() method is all you need. The request is the method's argument, and also self.request:
# billing/views.py, below the imports above
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
class CheckoutView(LoginRequiredMixin, View):
def post(self, request):
params = {
"line_items": [{"price": "price_...", "quantity": 1}],
"mode": "subscription",
"success_url": "https://yourdomain.com/thanks",
"client_reference_id": str(request.user.pk),
}
vid = request.COOKIES.get("virling_vid")
if vid:
params["metadata"] = {"virling_vid": vid}
session = stripe.checkout.Session.create(**params)
return redirect(session.url)The URL entry is path("checkout/", CheckoutView.as_view(), name="checkout"). This one keeps your own user's primary key in client_reference_id, so the visitor ID moves to the session's metadata.virling_vid, which Virling checks first. Metadata set only in subscription_data lands on the subscription, which Virling does not read. The full lookup order, including PaymentIntents you create for Elements as in Stripe Elements UTM tracking, is in the Stripe docs.
CSRF on the checkout form
CsrfViewMiddleware rejects a POST without a token with 403 CSRF verification failed, so the form needs {% csrf_token %}. Do not mark the checkout view @csrf_exempt: it acts on the buyer's cookies, which is exactly what CSRF protection is for.
<form action="{% url 'checkout' %}" method="post">
{% csrf_token %}
<button type="submit">Subscribe</button>
</form>If a button posts with fetch instead, send the value of the csrftoken cookie in an X-CSRFToken header and return the session URL as JSON rather than a redirect, as in Django's CSRF guide.
Renewals
Only the first payment carries the visitor ID. Renewals and plan changes keep that payment's channel, as described in renewals, and if the buyer already has a Stripe customer, passing its ID as customer matches a later plan to that first payment.
Check that it works
Put a test secret key in .env, connect a restricted key starting with rk_test_ in Virling, and follow test your setup with one tagged visit. While testing, log the new session in the view and compare it with window.virling.vid() in the browser console:
print(session.id, session.client_reference_id, session.metadata)
The script records nothing on runserver's 127.0.0.1:8000 unless the tag has data-dev, and visits are kept only on your site's domain and its subdomains. Run the full path on a host such as staging.yourdomain.com and add it to ALLOWED_HOSTS. If the view passes customer, use a fresh one per test, since a second payment by the same customer counts as a renewal.
Common mistakes
In Virling, an Unattributed payment with no Visitor under Details means checkout carried no ID.
| What you see | Cause | Fix |
|---|---|---|
BadSignature, or no visitor ID | get_signed_cookie() expects a Django signature the script never adds | Read request.COOKIES.get("virling_vid") |
403 CSRF verification failed | The form has no {% csrf_token %}, or fetch sends no X-CSRFToken header | Add the tag or the header, as in the CSRF section |
| 405 on the checkout URL | A link sends GET to a view that only handles POST | Use the form from the CSRF section |
| No visitor ID, though the browser has the cookie | The session is created in a Celery task or a webhook view, where no buyer request exists | Read the cookie in the view and pass the value to the task as an argument |
The cookie is set on 127.0.0.1:8000 but missing on localhost:8000 | Browsers treat the two as different hosts | Stay on one host from landing page to checkout |
| Two buyers get the same Checkout Session | A GET view that creates sessions is wrapped in cache_page | Create sessions in a POST view; Django's cache only stores GET and HEAD responses |
| Visitor on the payment is a user's primary key | client_reference_id holds request.user.pk | Also set metadata.virling_vid, as in the class-based view |
| The ID shows on the subscription only | It went into subscription_data.metadata | Set metadata on the session itself |
| A few payments are Unattributed | Those visitors had no cookie, for example because the script was blocked or consent is pending | None needed: the view leaves the field out and the revenue still counts |
Checkout requests must reach Django with their cookies, so keep them out of any CDN cache, as in page caching and CDNs. Other causes are in Unattributed revenue, and a payment made before a fix stays as it was, so test with a new one. The Stripe integration page lists what Virling imports.
Frequently asked questions
How do I pass UTM parameters to Stripe Checkout in Django?
Pass one visitor ID instead of the tags. In the view that creates the Checkout Session, read request.COOKIES.get("virling_vid") and give it to stripe.checkout.Session.create() as client_reference_id. Virling already holds the UTM tags of every visit behind that ID.
Can I use a class-based view instead of a function view?
Yes. Subclass View, put the code in its post() method and route it with CheckoutView.as_view(). The request arrives as the method's argument, so request.COOKIES works the same, and mixins such as LoginRequiredMixin can sit in front of it.
Where does the visitor ID go when client_reference_id holds my user's ID?
Put it in the session's metadata with metadata={"virling_vid": vid} and keep request.user.pk in client_reference_id. Virling reads metadata.virling_vid before client_reference_id.
Should I use get_signed_cookie for virling_vid?
No. The script sets virling_vid as a plain cookie in the browser, so Django has no signature to check. Read it with request.COOKIES.get("virling_vid").
What if a buyer has no virling_vid cookie?
request.COOKIES.get() returns None and the view leaves client_reference_id out, which happens when the script is blocked or the site is in cookieless mode. Stripe takes the payment as usual and Virling counts it as Unattributed revenue.
See which campaigns bring Stripe revenue
Virling is open source under AGPL. Self-host it free, or use the hosted version with a 14-day free trial. It connects to Stripe, Paddle, Shopify, WooCommerce, Polar, LemonSqueezy, Dodo, Creem and RevenueCat.