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

Flask Stripe UTM tracking: Checkout in Python

By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-29.

A Flask app needs one change, in the route that creates the Stripe Checkout Session: take virling_vid from request.cookies and hand it to stripe.checkout.Session.create() as client_reference_id. Below is that route in a Blueprint registered by an app factory, the Jinja form that posts to it, and what to set when gunicorn runs behind nginx or a load balancer.

UTM tags sit in the URL of your landing page, and nothing carries them over to Stripe's hosted checkout. The Virling script ties each visit and its tags to an ID kept in a first-party cookie, and a payment that carries the ID is joined to those visits. Payment Links and where the values show up in Stripe are covered in the general guide to Stripe Checkout UTM parameters; for other stacks see Django and Next.js.

Start free trial

The tag in your Jinja layout

Put the script in the layout your templates extend with {% extends "base.html" %}, before </head>. Jinja's autoescaping applies only to values inside {{ }}, so the tag renders unchanged. Self-hosting? Point src at your own Virling server.

<!-- templates/base.html -->
<script defer src="https://app.virling.com/v.js"
  data-site="yourdomain.com"></script>

A checkout route in a Blueprint

The factory reads the key once and registers the billing Blueprint under /billing:

# myapp/__init__.py
import os

import stripe
from flask import Flask


def create_app():
    app = Flask(__name__)
    app.config["STRIPE_SECRET_KEY"] = os.environ["STRIPE_SECRET_KEY"]
    stripe.api_key = app.config["STRIPE_SECRET_KEY"]

    from . import billing
    app.register_blueprint(billing.bp, url_prefix="/billing")
    return app

In the route, request.cookies.get() returns the visitor ID or None. The cookie is the script's own, apart from the signed cookie behind Flask's session, which is also why the Stripe object is called checkout_session here:

# myapp/billing.py
import stripe
from flask import Blueprint, redirect, request

bp = Blueprint("billing", __name__)


@bp.post("/checkout")
def checkout():
    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

    checkout_session = stripe.checkout.Session.create(**params)
    return redirect(checkout_session.url, code=303)

@bp.post needs Flask 2.0 or later; before that, write @bp.route("/checkout", methods=["POST"]). Inside a Blueprint the endpoint is named after it, so the form builds its URL with url_for('billing.checkout'):

<form action="{{ url_for('billing.checkout') }}" method="post">
  <button type="submit">Subscribe</button>
</form>

With Flask-WTF's CSRFProtect, add <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> to the form. When client_reference_id already holds your own user or order ID, set params["metadata"] = {"virling_vid": vid} instead; Virling reads the session's metadata first, and the Stripe docs give the full lookup order. For other payment providers, the checkout snippet generator writes the matching code. With Paddle, the ID goes in the checkout's custom data instead, and the Django Paddle guide shows that step in a Python view and template.

gunicorn behind nginx

In production the factory usually runs under gunicorn, for example gunicorn -w 4 "myapp:create_app()", with nginx or a load balancer in front. The proxy passes the Cookie header through, so the route reads the visitor ID exactly as in development. What it loses is the public scheme and host: without help, url_for(..., _external=True) builds http://127.0.0.1:8000/..., and a success_url built that way sends buyers to an address they cannot open.

# in create_app(), when one proxy sets X-Forwarded-*
from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)

The numbers count trusted proxies, so match them to your setup, and have nginx send proxy_set_header X-Forwarded-Proto $scheme; and proxy_set_header X-Forwarded-Host $host;, as in Flask behind a proxy. Each gunicorn worker runs create_app() for itself, so read every key and app.secret_key from the environment rather than generating them at startup. If a Python service runs on Uvicorn instead, Stripe UTM tracking in FastAPI covers its --forwarded-allow-ips setting.

Optional: the UTM tags in Stripe too

Virling needs only the visitor ID. To also read the last tagged visit's tags in the Stripe Dashboard, keep them in Flask's session and copy them into metadata. Stripe does not copy session metadata to the Subscription, so set subscription_data.metadata as well, or payment_intent_data.metadata for mode="payment":

# myapp/billing.py
from flask import session

UTM_KEYS = ("utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term")


@bp.before_app_request
def keep_utm():
    tags = {k: request.args[k] for k in UTM_KEYS if request.args.get(k)}
    if tags:
        session["utm"] = tags

# in checkout(), before stripe.checkout.Session.create(**params):
    utm = session.get("utm", {})
    if utm:
        params["metadata"] = {**params.get("metadata", {}), **utm}
        params["subscription_data"] = {"metadata": utm}

before_app_request runs for every request of the app, not only the Blueprint's, so it sees the landing page. Virling ignores this subscription metadata; renewals keep the first payment's channel on their own, as in renewals.

Check that it works

Export a test secret key as STRIPE_SECRET_KEY, connect a restricted key starting with rk_test_ in Virling, and make one tagged visit and one payment as in test your setup. To confirm the route sent the ID, print the session and compare it with window.virling.vid() in the browser console:

print(checkout_session.id, checkout_session.client_reference_id, checkout_session.metadata)

If your code sets customer, create a new customer for each test, because a second payment by one customer is treated as a renewal. How the join works from visit to payment is in how to track Stripe revenue by traffic source, and the SaaS page shows the per-channel view.

Common mistakes

Open an Unattributed payment and look for Visitor under Details. If there is none, checkout did not carry the ID.

SymptomCauseFix
session.get("virling_vid") is always NoneFlask's session is its own signed cookie. The script sets a plain one next to itRead request.cookies.get("virling_vid") (Flask cookies)
BuildError for checkoutThe route is in a Blueprint, so its endpoint is billing.checkoutCall url_for('billing.checkout') (Flask Blueprints)
Checkout answers 400 for some visitors onlyrequest.cookies["virling_vid"] raises a key error when the cookie is missing, and Flask answers 400Use .get() and leave the field out when it is empty, as in the Blueprint route (Flask cookies)
400 with The CSRF token is missingFlask-WTF's CSRFProtect checks every POST, also from fetchAdd the hidden field from the Blueprint section to the form, or send the token in the X-CSRFToken header from pages of the same app (Flask-WTF CSRF)
No visitor ID when a frontend on www. calls api.yourdomain.comfetch to another origin sends no cookies by defaultUse credentials: "include" (fetch credentials) and CORS(app, origins=["https://www.yourdomain.com"], supports_credentials=True) from Flask-CORS, with CSRF protection (Flask-CORS)
The browser reports a CORS error for checkout.stripe.comThe button uses fetch, which follows the 303 redirect to Stripe's domainPost a plain form, or return {"url": checkout_session.url}, which Flask sends as JSON, and set location.href (Flask JSON)
After paying, the buyer lands on an http:// or internal addresssuccess_url comes from url_for(..., _external=True), and Flask does not know about the reverse proxyWrap the app in ProxyFix with the number of proxies that set each header, such as x_proto=1, x_host=1, or use a fixed URL as in the Blueprint route (Flask behind a proxy)
Your Stripe webhook fails signature verification, or gets 400 before your code runsrequest.get_json() was passed instead of the raw body, or CSRFProtect rejects Stripe's POSTPass request.get_data() to stripe.Webhook.construct_event() and mark that one view @csrf.exempt (get_data, Flask-WTF CSRF, Stripe signature docs)
The session is unavailable because no secret key was setThe optional UTM code uses Flask's session without a secret key. The visitor ID alone does not need itSet app.secret_key to the same value in every worker (Flask sessions)
Working outside of request context, or no visitor IDThe session is created in a Celery task, a thread or a webhook view, where there is no request of the buyerRead the cookie in the route the browser posts to and pass the value to the task (Flask request context)
No virling_vid cookie in local developmentThe script does nothing on localhost and 127.* without data-devAdd data-dev to the tag in templates/base.html while you develop, and test the whole path on a subdomain of your site, where visits are kept
Visitor on the payment is your own user or order IDclient_reference_id holds your ID and is read as the visitor IDPut the visitor ID in the session's metadata.virling_vid, which is read first (Stripe docs)
Some payments are UnattributedThe visitor had no cookie: the script was blocked, or the site is in cookieless mode or still waiting for consentNothing to fix in the code. Create the session without the ID; the payment still counts toward revenue (Unattributed revenue)

The webhook row is about your own endpoint, for example one that unlocks an account. Virling reads Stripe with the restricted key and needs no webhook in your app. Checkout requests have to reach your server with their cookies, so keep them out of any cache and do not let a proxy or CDN remove the Cookie header, as in page caching and CDNs. A payment made before a fix usually stays Unattributed, so make a new one to check.

Frequently asked questions

How do I pass UTM parameters to Stripe Checkout in Flask?

You pass one visitor ID rather than the tags. In the route that creates the session, read request.cookies.get("virling_vid") and set it as client_reference_id in stripe.checkout.Session.create(). Virling has the UTM tags of each visit behind that ID.

Does the route need changes behind gunicorn and nginx?

Not to read the cookie: nginx forwards the Cookie header and request.cookies works as in development. Wrap the app in werkzeug's ProxyFix so url_for(..., _external=True) builds https URLs on your public host, and load the Stripe key and secret key from the environment in every worker.

Is virling_vid stored in the Flask session?

No. The script sets virling_vid as its own plain cookie in the browser, outside Flask's signed session cookie. Read it with request.cookies.get("virling_vid").

What if request.cookies has no virling_vid?

The route gets None from .get() and creates the Checkout Session without client_reference_id, for example when the script is blocked. Avoid request.cookies["virling_vid"], which makes Flask answer 400. The payment counts as Unattributed revenue.

Do Stripe Payment Links in a Flask app need code?

No. Use a normal link to buy.stripe.com on a page that runs the script. The script adds client_reference_id to the link when the page loads and again on click, unless the link already has one.

Does a Flask app need a Stripe webhook for this?

No. Virling reads charges from Stripe with a restricted key and finds the visitor ID on the Checkout Session. Keep your own webhook if your app needs one, for example to unlock an account, and pass request.get_data() to stripe.Webhook.construct_event() so the signature matches.

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.

Start free trial See the demo