Go Stripe UTM tracking: Checkout with net/http and stripe-go
By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-26.
In a Go backend, attribution is a few lines in the handler that creates the Stripe Checkout Session: read the virling_vid cookie with r.Cookie and hand its value to stripe-go as ClientReferenceID. This post shows a net/http handler, the stripe-go types it uses, and what changes behind nginx or with a router such as chi.
Checkout runs on Stripe's domain, so the UTM tags of your landing page never reach it by themselves. The Virling script stores them against a visitor ID in a first-party cookie, and Virling joins any payment that carries that ID to the visits behind it. Payment Links, metadata limits and where the values show up in Stripe are in the general guide to Stripe Checkout UTM parameters; other stacks are covered in Next.js, Rails, Spring Boot and ASP.NET Core.
Load the script from your html/template layout
Put the tag before </head> in the layout your handlers execute. html/template only escapes values you insert with {{ }}, so a literal script tag is written out as is. When the Go service is only an API behind a separate frontend, the tag belongs in that frontend's layout. 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>The net/http handler
The script sets the cookie on your registrable domain, so the browser sends it with the form POST that reaches your handler. r.Cookie returns http.ErrNoCookie and a nil cookie when it is absent, so check the error before reading c.Value:
package main
import (
"log"
"net/http"
"os"
"github.com/stripe/stripe-go/v82"
"github.com/stripe/stripe-go/v82/checkout/session"
)
func createCheckout(w http.ResponseWriter, r *http.Request) {
params := &stripe.CheckoutSessionParams{
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
LineItems: []*stripe.CheckoutSessionLineItemParams{
{Price: stripe.String("price_..."), Quantity: stripe.Int64(1)},
},
SuccessURL: stripe.String(os.Getenv("PUBLIC_URL") + "/thanks"),
}
if c, err := r.Cookie("virling_vid"); err == nil && c.Value != "" {
params.ClientReferenceID = stripe.String(c.Value)
}
s, err := session.New(params)
if err != nil {
http.Error(w, "checkout failed", http.StatusInternalServerError)
return
}
http.Redirect(w, r, s.URL, http.StatusSeeOther)
}
func main() {
stripe.Key = os.Getenv("STRIPE_SECRET_KEY")
http.HandleFunc("POST /checkout", createCheckout)
log.Fatal(http.ListenAndServe(":8080", nil))
}stripe-go params use pointer fields so that an unset field is left out of the request. Wrap values with stripe.String and stripe.Int64, and leave ClientReferenceID nil when there is no cookie rather than sending an empty string. The import path carries the library's major version, so match it to your go.mod. The method in "POST /checkout" needs Go 1.22 or later; older code checks r.Method itself.
If you use the client from stripe.NewClient instead of the global stripe.Key, the call is sc.V1CheckoutSessions.Create(r.Context(), params) with stripe.CheckoutSessionCreateParams. ClientReferenceID and AddMetadata work the same there.
Submit a plain form to the handler. The 303 redirect then takes the buyer to checkout.stripe.com, while a fetch call would follow it in the background and leave the page where it is:
<form method="post" action="/checkout"> <button type="submit">Subscribe</button> </form>
Metadata and subscriptions
When ClientReferenceID already carries your own user or order ID, call params.AddMetadata("virling_vid", c.Value) instead. That puts the ID in the session's metadata, which Virling checks before client_reference_id. Do not put it only in params.SubscriptionData.Metadata: that map lands on the subscription object, which Virling does not read.
params.SubscriptionData = &stripe.CheckoutSessionSubscriptionDataParams{
Metadata: map[string]string{"plan": "pro"}, // on the subscription, not read
}
if c, err := r.Cookie("virling_vid"); err == nil && c.Value != "" {
params.AddMetadata("virling_vid", c.Value) // on the session, read
}Renewals need no code: each one keeps the channel of the subscription's first payment, as described in renewals. The full lookup order, including PaymentIntents you create for Elements, is in the Stripe docs.
Behind nginx, Caddy or a load balancer
A reverse proxy passes the Cookie header through untouched, so r.Cookie behaves the same as it does on your laptop. What changes is what the request says about itself. nginx's proxy_pass sends the upstream address as Host unless you add proxy_set_header Host $host, and r.TLS is nil when TLS ends at the proxy. That is why the handler builds SuccessURL from a PUBLIC_URL setting instead of r.Host.
A Go API on api.yourdomain.com still receives the cookie when the page is on yourdomain.com, because the script sets it on the parent domain. If the page calls that API with fetch and redirects to the returned URL, pass credentials: "include" and have the API answer with Access-Control-Allow-Origin set to the page's origin and Access-Control-Allow-Credentials: true. Keep checkout on POST: nginx's proxy_cache stores only GET and HEAD responses by default, so a cached GET handler is the one way several buyers end up on one session.
With chi, Gin or Echo
chi routes take ordinary http.HandlerFunc values, so the handler above mounts unchanged:
rt := chi.NewRouter()
rt.Post("/checkout", createCheckout)
log.Fatal(http.ListenAndServe(":8080", rt))In Gin, c.Cookie("virling_vid") returns the value as a string and an error; in Echo, c.Cookie("virling_vid") returns an *http.Cookie like the standard library. If you add CSRF middleware such as gorilla/csrf, it rejects the plain form with a 403 until the template includes its hidden field from csrf.TemplateField(r).
Check that it works
Connect a restricted key that starts with rk_test_ in Virling, keep your test secret key in STRIPE_SECRET_KEY, and follow test your setup with one tagged visit. While you test, log the session right after the error check and compare it with window.virling.vid() in the browser console:
log.Printf("%s ref=%s metadata=%v", s.ID, s.ClientReferenceID, s.Metadata)On localhost:8080 the script records nothing unless the tag has data-dev, and visits are kept only on the data-site domain and its subdomains, so run the test on a subdomain such as staging.yourdomain.com.
Common mistakes
| What you see | Cause | Fix |
|---|---|---|
| A nil pointer panic for some visitors | The error from r.Cookie is dropped and c.Value is read on a nil cookie | Read c.Value only when err == nil |
After paying, buyers land on http://127.0.0.1:8080/thanks | SuccessURL is built from r.Host behind a proxy | Read the public URL from config |
No visitor ID when the frontend calls the API with fetch | A cross-origin request without credentials: "include" sends no cookies | Add it, plus the CORS credentials headers, or post a form |
| No visitor ID from a background job | The session is created in a goroutine, queue worker or webhook handler that never saw the buyer's request | Read the cookie in the browser-facing handler and pass the value along |
| 403 from the checkout form | CSRF middleware wants a token the form does not send | Add csrf.TemplateField(r) to the form |
| The ID is on the subscription in Stripe, the payment is Unattributed | It was set only through SubscriptionData.Metadata | Use params.AddMetadata or ClientReferenceID |
A payment from a visitor with no cookie, for example one whose browser blocks the script, still counts toward revenue as Unattributed. Every other cause is in Unattributed revenue, and the Stripe integration page shows what Virling imports.
Frequently asked questions
How do I pass UTM parameters to Stripe Checkout in Go?
You pass one visitor ID instead of the tags. In the net/http handler that creates the session, read r.Cookie("virling_vid") and set params.ClientReferenceID = stripe.String(c.Value). Virling already holds the UTM tags of every visit behind that ID.
Does this work with chi, Gin or Echo?
Yes. chi passes the standard *http.Request, so r.Cookie works unchanged. Gin uses c.Cookie("virling_vid"), which returns a string, and Echo uses c.Cookie("virling_vid"), which returns an *http.Cookie. The stripe-go code is identical.
ClientReferenceID or AddMetadata?
ClientReferenceID is the simplest. If your app already stores its own user ID there, call params.AddMetadata("virling_vid", value) instead, which Virling reads first.
What if r.Cookie returns http.ErrNoCookie?
Leave ClientReferenceID nil and create the session anyway. That happens when the script is blocked or runs in cookieless mode, and the payment still counts toward revenue as Unattributed.
Why does stripe-go need stripe.String for ClientReferenceID?
stripe-go params use pointer fields, so the library can tell an unset field from an empty one and leave unset fields out of the API request. stripe.String returns a pointer to the value; a nil ClientReferenceID is simply not sent.
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.