virling Pricing Self-host Demo Changelog Agencies GitHub Start free trial
blog / 2026-11-25

Django Paddle UTM tracking: pass the visitor ID to checkout

By Devendra Variya, co-founder of Virling. Published 2026-11-25.

Django hands you the cookie Virling sets as request.COOKIES.get("virling_vid"). Django Paddle UTM tracking takes a view that reads it, json_script to print it without opening an XSS hole, and either Paddle.js or a transaction your own view creates with urllib.

Paddle records only the custom data you send, and Virling looks for virling_vid in a transaction's custom_data to tie the payment to every visit behind it, tags included (see the Paddle setup docs). Hosted checkout links are in Paddle checkout UTM parameters, Stripe on Django in Django Stripe UTM tracking, and the same flow in Ruby in Rails Paddle UTM tracking.

Start free trial

Step 1: add the scripts to the base template

They go in templates/base.html, before </head>; self-hosted installs swap app.virling.com for their own host. The head block lets the pricing template add its config there.

{# templates/base.html #}
<script defer src="https://app.virling.com/v.js"
  data-site="yourdomain.com"></script>
<script src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>
{% block head %}{% endblock %}

Keep the Paddle values in settings, read from the environment. The client-side token is safe to print in a page; the API key is not. The API URL and key are only needed by the server-created transaction below.

# settings.py
import os

PADDLE_CLIENT_TOKEN = os.environ["PADDLE_CLIENT_TOKEN"]
PADDLE_PRICE_ID = os.environ["PADDLE_PRICE_ID"]
PADDLE_API_URL = os.environ.get("PADDLE_API_URL")
PADDLE_API_KEY = os.environ.get("PADDLE_API_KEY")

Step 2: read the cookie in a view

Django's get_signed_cookie() expects a signature the script never adds, so read the raw value from request.COOKIES.

# billing/views.py
from django.conf import settings
from django.shortcuts import render
from django.views.decorators.cache import never_cache


@never_cache
def pricing(request):
    paddle = {
        "token": settings.PADDLE_CLIENT_TOKEN,
        "priceId": settings.PADDLE_PRICE_ID,
        "vid": request.COOKIES.get("virling_vid"),
    }
    return render(request, "pricing.html", {"paddle": paddle})

The page now holds one visitor's ID, so never_cache keeps shared caches from serving it to someone else. Map it with path("pricing/", views.pricing, name="pricing"). A Remix loader that returns the ID has the same caching risk, and Paddle UTM tracking in Remix sends Cache-Control: private for it.

Step 3: print it as safe JSON

{# templates/pricing.html #}
{% extends "base.html" %}
{% load static %}

{% block head %}
{{ paddle|json_script:"paddle-config" }}
<script defer src="{% static 'checkout.js' %}"></script>
{% endblock %}

{% block content %}
<button type="button" id="subscribe">Subscribe</button>
{% endblock %}

A cookie is input: its owner can set it to anything. json_script writes the dictionary into a <script type="application/json"> tag and escapes <, > and &, so a value cannot close the tag (source: Django, json_script). Do not build the JavaScript with {{ paddle|safe }}. Everything in the dictionary is readable in the page source, so keep the API key out of it.

Step 4: open the overlay checkout

// static/checkout.js
const config = JSON.parse(
  document.getElementById("paddle-config").textContent
);
if (config.token.startsWith("test_")) {
  Paddle.Environment.set("sandbox");
}
Paddle.Initialize({ token: config.token });

document.getElementById("subscribe").addEventListener("click", () => {
  const vid = window.virling?.vid?.() || config.vid;
  Paddle.Checkout.open({
    items: [{ priceId: config.priceId, quantity: 1 }],
    ...(vid && { customData: { virling_vid: vid } }),
  });
});

window.virling?.vid?.() is tried first because the request for a visitor's first page goes out before the cookie exists; config.vid covers the rest. With neither, the spread leaves customData out, as Paddle accepts it only with at least one key (source: Paddle.Checkout.open). Inline checkout takes the same option.

Or create the transaction in a view

A view can also create the transaction itself and put the cookie in custom_data. urllib from the standard library sends the request:

# billing/views.py
import json
from urllib.request import Request, urlopen

from django.conf import settings
from django.shortcuts import redirect
from django.views.decorators.http import require_POST


@require_POST
def checkout(request):
    body = {"items": [{"price_id": settings.PADDLE_PRICE_ID, "quantity": 1}]}
    vid = request.COOKIES.get("virling_vid")
    if vid:
        body["custom_data"] = {"virling_vid": vid}

    api_request = Request(
        f"{settings.PADDLE_API_URL}/transactions",
        data=json.dumps(body).encode(),
        headers={
            "Authorization": f"Bearer {settings.PADDLE_API_KEY}",
            "Content-Type": "application/json",
        },
    )
    with urlopen(api_request, timeout=10) as response:
        transaction = json.load(response)["data"]
    return redirect(transaction["checkout"]["url"])

Route it with path("checkout/", views.checkout, name="checkout") and post to it from the template in place of the button. The {% csrf_token %} tag is required: CsrfViewMiddleware answers a POST to your own view without it with a 403.

<form action="{% url 'checkout' %}" method="post">
  {% csrf_token %}
  <button type="submit">Subscribe</button>
</form>

Drop the click listener from checkout.js but keep Paddle.Initialize, and set Paddle's default payment link to a page that runs checkout.js, such as /pricing/. Paddle sends the buyer there with ?_ptxn=, and Paddle.js opens the checkout (source: Paddle, Pass a transaction to a checkout). settings.PADDLE_API_URL is https://api.paddle.com in production and https://sandbox-api.paddle.com in the sandbox; the key needs transaction.write (source: Paddle, Create a transaction) and should not be the read-only key Virling uses.

A Celery task or a webhook view never sees the buyer's cookies, so do this in the view the form posts to. Transactions made this way get origin api, and Virling starts a free trial only from a $0 subscription transaction of origin web, so trial plans should stay on the overlay from step 4. Renewals and plan changes need nothing from Django: they keep the channel of the customer's first payment, as Renewals explains.

Test it on a Django staging site

  1. Connect a sandbox key (pdl_sdbx_) in Virling with the permissions in the Paddle docs, and give Django's environment the sandbox values: a test_ token, API key, API URL, price ID and default payment link.
  2. Serve the app on a real host such as staging.yourdomain.com and list it in ALLOWED_HOSTS; Virling does not record localhost visits for your site.
  3. Load https://staging.yourdomain.com/pricing/?utm_source=test&utm_medium=email in a private window, press Subscribe, and pay with Paddle's test card 4242 4242 4242 4242 (source: Paddle, Sandbox). The transaction's custom data should hold the ID that window.virling.vid() shows in the console.
  4. After the next sync, the payment appears at /app/yourdomain.com/payments under source test and channel Email. Use a fresh email address on each run, because a repeat customer's payment counts as a renewal.

More checks are in Test your setup.

Django symptoms, causes and fixes

SymptomCauseFix
Paddle shows the transaction without virling_vidcustomData was not passed; v.js never adds it to Paddle on its ownOpen checkout as in step 4
vid is null in the JSON on a visitor's first pageThe view ran before the browser had the cookieRead window.virling?.vid?.() on click and use config.vid as the fallback
The view fails with BadSignatureget_signed_cookie() was used, and the cookie is plainRead request.COOKIES.get("virling_vid")
config.token is undefinedThe view passed a json.dumps() string, so it was encoded twicePass the dictionary itself to json_script
A JavaScript syntax error shows &#x27;The template prints {{ paddle }}, which is an escaped Python dictionary, not JSONUse json_script and JSON.parse, as in steps 3 and 4
Payments from different buyers share one visitor IDA cached page or {% cache %} block served one visitor's vid to buyers with no ID of their ownUse never_cache on the view and keep json_script out of cached blocks
Paddle.Initialize is called twice on one pageTwo templates or scripts call itCall it once, in checkout.js
The payment link page loads but no checkout opensThe default payment link points to a page without Paddle.js and its tokenPoint it to a page that runs checkout.js
The form answers 403The CSRF token is missingAdd {% csrf_token %} to the form

Other reasons a Paddle payment ends up Unattributed are in Unattributed revenue.

Frequently asked questions

Should I put UTM parameters in Paddle custom data from Django?

Pass request.COOKIES.get('virling_vid') as virling_vid instead. Virling already stores the tags of each visit under that ID, so one value covers the landing visit and every visit before the payment.

How do I pass Django data to Paddle.js safely?

Put it in a dictionary in the view and print it with the json_script filter, then read it in JavaScript with JSON.parse on the textContent of that element. Django escapes the HTML characters, so a changed cookie cannot close the script tag. Do not use the safe filter, and send only values the buyer may see.

Why is request.COOKIES.get('virling_vid') None in my Django view?

A brand-new visitor's first page is requested before v.js runs, so there is no cookie to send. Celery tasks and webhook views never get it, and with cookieless mode or a blocked script it does not exist. Read window.virling?.vid?.() in the browser as the first choice.

Why does my Django checkout form return 403 Forbidden?

Django's CsrfViewMiddleware rejects a POST without a valid CSRF token. Add the csrf_token tag inside the form that posts to your checkout view. Do not mark the view csrf_exempt: it reads the buyer's cookie and starts a payment.

See which campaigns bring Paddle 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.

Start free trial See the demo