FastAPI Stripe UTM tracking: Checkout in Python
By Devendra Variya, co-founder of Virling. Published 2026-11-22.
In a FastAPI app, Stripe UTM tracking touches two places: the Jinja2 base template, which loads the Virling script, and the path operation that creates the Stripe Checkout Session, which reads the virling_vid cookie and sends it to Stripe as client_reference_id. Without that ID a payment carries nothing that points back to the campaign, so it lands in Direct or Unattributed. With it, Virling joins the payment to every visit that had the same ID, as link checkout to visits explains.
The examples use current FastAPI with Pydantic v2 and the stripe Python library. If you run Flask or Django instead, see Flask Stripe UTM tracking or Django Stripe UTM tracking.
Step 1: load the script from the Jinja2 base template
With Jinja2Templates, every page that extends base.html inherits its <head>. Put the tag there, outside any {% block %}, so a child template that overrides the head block cannot drop it:
{# templates/base.html #}
<!doctype html>
<html lang="en">
<head>
{% block head %}{% endblock %}
<script defer src="https://app.virling.com/v.js"
data-site="yourdomain.com"></script>
</head>
<body>{% block content %}{% endblock %}</body>
</html># main.py
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/pricing")
def pricing(request: Request):
return templates.TemplateResponse(request, "pricing.html")
@app.get("/thanks")
def thanks(request: Request):
return templates.TemplateResponse(request, "thanks.html")A self-hosted Virling serves v.js from your own instance, so point src there. If a separate frontend renders the pages and FastAPI only serves the API, the tag goes in that frontend's HTML instead.
Step 2: read the cookie with Cookie() or Request
The script keeps the visitor ID in a first-party cookie named virling_vid. FastAPI can hand it to you in two ways:
Cookie(). Declare a parameter namedvirling_vidwithAnnotated[str | None, Cookie()] = None. The parameter name is the cookie name.Request. Callrequest.cookies.get("virling_vid")when you already take the request, for example in middleware.
A small dependency keeps the check in one place and drops any value that is not a visitor ID:
import re
from typing import Annotated
from fastapi import Cookie
VID = re.compile(r"[A-Za-z0-9-]{8,64}")
def visitor_id(virling_vid: Annotated[str | None, Cookie()] = None) -> str | None:
if virling_vid and VID.fullmatch(virling_vid):
return virling_vid
return NoneStep 3: a Pydantic model for the checkout request
Let the browser name a plan, never a Stripe price ID. A Literal field makes FastAPI answer anything else with a 422 before your code runs, and a response model documents the reply in the OpenAPI schema:
import os
from typing import Literal
import stripe
from fastapi import Depends
from pydantic import BaseModel, Field
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
PRICES = {"starter": "price_...", "pro": "price_..."}
class CheckoutIn(BaseModel):
plan: Literal["starter", "pro"]
seats: int = Field(default=1, ge=1, le=50)
class CheckoutOut(BaseModel):
url: str
@app.post("/checkout")
def checkout(
body: CheckoutIn,
request: Request,
vid: Annotated[str | None, Depends(visitor_id)],
) -> CheckoutOut:
params = {
"line_items": [{"price": PRICES[body.plan], "quantity": body.seats}],
"mode": "subscription",
"success_url": str(request.url_for("thanks")),
}
if vid:
params["client_reference_id"] = vid
checkout_session = stripe.checkout.Session.create(**params)
return CheckoutOut(url=checkout_session.url)On a page rendered from the base template, a same-origin fetch sends the cookie without extra options:
<script>
async function subscribe(plan) {
const res = await fetch("/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ plan }),
});
location.href = (await res.json()).url;
}
</script>
<button type="button" onclick="subscribe('pro')">Subscribe</button>If the API lives on a subdomain such as api.yourdomain.com, it still gets the cookie, but the call is cross-origin: use credentials: "include" in the browser, and add CORSMiddleware with allow_credentials=True and your site listed in allow_origins, since a wildcard origin is not allowed with credentials.
Step 4: def or async def
stripe.checkout.Session.create() waits on a network call to Stripe. In a def path operation FastAPI runs it in a thread pool, which is why the route above is a plain def. Called inside an async def route, it would hold up every other request on that worker until Stripe answers. If the route has to be async def, for example because it awaits an async database driver, install "stripe[async]" and await the async method instead:
@app.post("/checkout")
async def checkout(
body: CheckoutIn,
request: Request,
vid: Annotated[str | None, Depends(visitor_id)],
) -> CheckoutOut:
... # same params as above
checkout_session = await stripe.checkout.Session.create_async(**params)
return CheckoutOut(url=checkout_session.url)Running behind a proxy
When Nginx, Caddy or a load balancer ends TLS in front of Uvicorn, the app sees plain HTTP, and request.url_for("thanks") builds an http:// success URL unless Uvicorn trusts the proxy's X-Forwarded-Proto header. Uvicorn reads it only from the addresses in --forwarded-allow-ips, which defaults to 127.0.0.1. If the proxy runs on another host, list its address:
uvicorn main:app --host 0.0.0.0 --forwarded-allow-ips="10.0.0.5"
If the proxy serves the app under a path prefix such as /api and strips it, also pass --root-path /api so generated URLs keep the prefix. The proxy passes the Cookie header through untouched, so virling_vid still arrives as long as the public hostname is your domain or one of its subdomains.
When client_reference_id is already used
If client_reference_id holds your own user ID, leave it and send the visitor ID as metadata:
if vid:
params["metadata"] = {"virling_vid": vid}The guide to Stripe Checkout UTM parameters covers which field to choose and Payment Links, and the Stripe docs list the order Virling checks them in. The Stripe integration page shows what Virling imports, and Stripe for SaaS shows the subscription view.
Optional: keep the UTM tags in Stripe too
Virling does not need the tags on the payment, since the visitor ID points to every visit. If you also want them readable in the Stripe Dashboard, save them from the landing URL in Starlette's SessionMiddleware (it needs the itsdangerous package) 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":
from starlette.middleware.sessions import SessionMiddleware
UTM_KEYS = ("utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term")
@app.middleware("http")
async def keep_utm(request: Request, call_next):
tags = {k: request.query_params[k] for k in UTM_KEYS if request.query_params.get(k)}
if tags:
request.session["utm"] = tags
return await call_next(request)
# added last, so it runs first and request.session exists in keep_utm
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"])
# in checkout(), before stripe.checkout.Session.create(**params):
utm = request.session.get("utm", {})
if utm:
params["metadata"] = {**params.get("metadata", {}), **utm}
params["subscription_data"] = {"metadata": utm}These tags record one visit, the last tagged one. Keep passing the visitor ID: it is what ties the payment to the whole path.
Check that it works
Renewals and plan changes need no extra code; they keep the channel of the first payment, as renewals describes. To test the first payment, follow test your setup on the deployed site. In the browser's network tab, the POST /checkout request should carry the virling_vid cookie. If it does not, the page skipped the base template or the request went to another domain. A 422 reply means the JSON body did not match CheckoutIn.
The SaaS page shows what you get per channel once payments come in.
Frequently asked questions
How do I pass UTM parameters to Stripe Checkout in FastAPI?
Read the virling_vid cookie in the path operation that creates the Checkout Session, with Cookie() or request.cookies, and pass it to stripe.checkout.Session.create() as client_reference_id. Virling then credits the payment from the tagged visits recorded under that ID.
How do I read the virling_vid cookie in FastAPI?
Add a parameter named virling_vid with Cookie() to your path operation, or read request.cookies.get("virling_vid") from the Request. It is a first-party cookie on your domain, so the browser sends it with every request to your app.
Should the checkout route be async def or def?
Use def with stripe.checkout.Session.create(), since it blocks; FastAPI runs def routes in a thread pool. If the route must be async def, install stripe[async] and await stripe.checkout.Session.create_async() instead.
Why does my success_url start with http:// behind a proxy?
Uvicorn only trusts X-Forwarded-Proto from the addresses in --forwarded-allow-ips, 127.0.0.1 by default. If your proxy runs on another host, add its address, and request.url_for() will build https URLs.
What happens if the cookie is missing?
If the script is blocked or runs in cookieless mode, the visitor_id dependency gets None, so client_reference_id is left out of the params dict. Checkout still works, and Virling counts the payment as Unattributed revenue.
Do Stripe Payment Links in a FastAPI 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.
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.