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

Spring Boot Stripe UTM tracking: Checkout metadata with stripe-java

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

Spring Boot Stripe UTM tracking comes down to one value. Load the Virling script in your Thymeleaf layout or frontend, then read the virling_vid cookie with @CookieValue in the controller that creates the Stripe Checkout Session and pass it as client_reference_id, or as metadata.virling_vid. Stripe keeps that one ID, and Virling joins the payment to every visit behind it, with the UTM tags of each, so you see which channel brought the buyer.

This post covers a Java backend with Spring Boot and stripe-java. The same steps for other stacks are in ASP.NET Core Stripe UTM tracking, Go Stripe UTM tracking and Next.js Stripe UTM tracking. For Payment Links, metadata limits and where the values show up in Stripe, see the general guide to Stripe Checkout UTM parameters.

Start free trial

Step 1: add the script to the Thymeleaf layout

Paste the tag before </head> in the template that every page uses, such as src/main/resources/templates/layout.html or a shared head fragment. If your pages are served by a separate frontend, such as React or Vue, put it in that app's index.html instead. If you self-host, replace app.virling.com with your Virling server.

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

The script sets the first-party virling_vid cookie on your domain and records the UTM tags of each visit against it.

Step 2: create the Checkout Session in a controller

Your server receives the cookie with every request from the browser on the same domain. Read it with @CookieValue where you create the session and pass it with setClientReferenceId:

package com.example.billing;

import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.checkout.Session;
import com.stripe.param.checkout.SessionCreateParams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class CheckoutController {

    public CheckoutController(@Value("${stripe.secret-key}") String secretKey) {
        Stripe.apiKey = secretKey;
    }

    @PostMapping("/checkout")
    public String checkout(
            @CookieValue(name = "virling_vid", required = false) String vid)
            throws StripeException {
        SessionCreateParams.Builder params = SessionCreateParams.builder()
                .setMode(SessionCreateParams.Mode.SUBSCRIPTION)
                .addLineItem(SessionCreateParams.LineItem.builder()
                        .setPrice("price_...")
                        .setQuantity(1L)
                        .build())
                .setSuccessUrl("https://yourdomain.com/thanks");
        if (vid != null && !vid.isEmpty()) {
            params.setClientReferenceId(vid);
        }

        Session session = Session.create(params.build());
        return "redirect:" + session.getUrl();
    }
}

Add com.stripe:stripe-java to your pom.xml or build.gradle, and keep the secret key in an environment variable with stripe.secret-key=${STRIPE_SECRET_KEY} in application.properties, not the key itself. Post to the controller from a plain form in your Thymeleaf page, so the browser follows the redirect to Stripe's domain. With th:action, Spring Security adds its CSRF token to the form for you:

<form method="post" th:action="@{/checkout}">
  <button type="submit">Subscribe</button>
</form>

Using metadata instead

If client_reference_id already holds your own user or order ID, put the visitor ID in the session's metadata. Virling reads either:

if (vid != null && !vid.isEmpty()) {
    params.putMetadata("virling_vid", vid);
}

With a separate frontend

If a React or Vue app on your domain or a subdomain calls the Spring Boot API, a plain form sends the virling_vid cookie and the controller above works as is. With fetch, return the URL as JSON as below, and when the API is on another subdomain also set credentials: "include" and allow it in CORS, as in common mistakes. If the API is on another domain, the cookie is not sent, so read the ID in the browser with window.virling?.vid?.() and send it in the request body. It returns nothing when the script is blocked or not loaded yet, so check the value before using it:

const vid = window.virling?.vid?.() || null;
const res = await fetch("https://api.example.com/checkout", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ vid }),
});
const { url } = await res.json();
window.location.href = url;

On the server, take vid from a @RequestBody in a @RestController, build the same SessionCreateParams, and return session.getUrl() as JSON instead of a redirect.

The full lookup order, including PaymentIntents you create for Elements, is in the Stripe docs, and the Stripe for SaaS page shows what you get per channel. How to pass the visitor ID with other providers is in link checkout to visits, and the script tag for other frameworks in the framework docs.

Subscriptions and renewals

Only the first payment needs the visitor ID: each renewal keeps the channel of the customer's first payment, with no code on your side, as described in renewals.

Check that it works

Run one tagged visit and one test payment through the form that posts to the controller, as in test your setup. Connect a restricted Stripe key that starts with rk_test_ in Virling; your app keeps its own test secret key in STRIPE_SECRET_KEY and uses a price created in test mode.

To see the visitor ID on the Checkout Session, add this right after Session.create(params.build()) and remove it afterwards. ClientReferenceId, or virling_vid in the session's metadata, should match window.virling.vid() in the browser console:

System.out.println(session.getId() + " " + session.getClientReferenceId() + " " + session.getMetadata());

If your code calls setCustomer, use a new customer for each test: a later payment by the same customer is a renewal and keeps the first payment's channel.

Payments without a visitor ID still count toward revenue, as Unattributed. How the join works from visit to payment is in how to track Stripe revenue by traffic source.

Common mistakes

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

SymptomCauseFix
400 with Required cookie 'virling_vid' for some visitors@CookieValue is required by default, so a visitor without the cookie cannot check outSet required = false and check for null, as in step 2 (@CookieValue)
POST /checkout answers 403Spring Security finds no valid CSRF token. A form with a plain action does not get oneUse th:action, which adds the token. From a single-page app on the same origin, use csrf.spa() and send the token with the request (Spring Security CSRF)
The page shows redirect:https://checkout.stripe.com/... as textThe class is a @RestController, so the returned string is the body and not a view nameUse @Controller for the form, as in step 2 (redirect prefix)
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 @CrossOrigin(origins = "https://www.yourdomain.com", allowCredentials = "true"). With credentials, * is not allowed as origin (Spring MVC CORS)
The CORS preflight fails although the controller allows the originSpring Security answers the preflight first, because it carries no cookiesAdd .cors(withDefaults()) to the security filter chain, so it uses the CORS settings of Spring MVC (Spring Security CORS)
The browser reports a CORS error for checkout.stripe.comThe button uses fetch, which follows the redirect to Stripe's domainPost a plain form, or return the URL as JSON from a @RestController and set window.location.href (@ResponseBody)
After paying, the buyer lands on an http:// or internal addressThe success URL is built with ServletUriComponentsBuilder, and the app ignores the headers of the reverse proxyOn Spring Boot 4.2, set server.request.header.forwarded.strategy=web-server (Spring Boot proxies), and on 4.1 or older server.forward-headers-strategy=native (4.1 docs). Or use a fixed URL, as in step 2
Your Stripe webhook fails signature verification, or Stripe gets 403The body was read into an object, so it is no longer the exact text, or Spring Security wants a CSRF token from StripeTake @RequestBody String payload and pass it to Webhook.constructEvent(). Permit the path without login, and leave it out of CSRF with ignoringRequestMatchers("/webhook") (@RequestBody, Spring Security CSRF, Stripe signature docs)
No visitor ID, though the browser has the cookieThe session is created in an @Async or scheduled method, or in a webhook controller, where there is no cookie of the buyerRead the cookie in the controller the browser posts to and pass the value on (link checkout to visits)
No virling_vid cookie in local developmentThe script does nothing on localhost and 127.* without data-devAdd data-dev to the tag in the layout 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 IDClientReferenceId 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 Spring Boot?

Read the visitor ID with @CookieValue(name = "virling_vid", required = false) in the controller method that creates the Checkout Session and set it with setClientReferenceId on SessionCreateParams. The Virling script records the UTM tags of every visit against that ID, so the payment is joined to all of them.

How do I add Stripe Checkout metadata in Spring Boot?

Call putMetadata("virling_vid", vid) on the SessionCreateParams builder. Use it when client_reference_id already holds your own user or order ID. Virling reads either metadata.virling_vid or client_reference_id on the session.

Does this work with a React or Vue frontend?

Yes. On your own domain, the browser sends the virling_vid cookie and the controller reads it. With fetch to a subdomain, set credentials: "include" and allow credentials in CORS. If the API is on another domain, read the ID in the browser with window.virling?.vid?.() and send it in the request body. The stripe-java code stays the same.

What happens if the cookie is missing?

With required = false, the parameter is null, and the session is created without a visitor ID, for example when the script is blocked or runs in cookieless mode. The payment still counts toward revenue, as Unattributed.

Why does POST /checkout return 403 in Spring Boot?

Spring Security rejects a POST without a valid CSRF token. In a Thymeleaf form, use th:action so the token is added for you, because a plain action attribute does not add it. From JavaScript, send the token with the request.

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