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

Symfony Stripe UTM tracking: Checkout Sessions in PHP

By Devendra Variya, co-founder of Virling. Published 2026-11-24, updated 2026-11-27.

In Symfony, the visitor ID is one entry in Request::$cookies. A Symfony form posts the buy button to a controller, the controller reads $request->cookies->get('virling_vid'), and stripe-php sends it to Stripe as the Checkout Session's client_reference_id. This post wires that up with an autowired StripeClient, a key kept in .env.local or the secrets vault, and the Form component's CSRF check.

Stripe Checkout runs on Stripe's own domain, so UTM tags in your landing URL stay behind; the Virling script stores them under the visitor ID, and Virling joins the payment to every visit behind it. Payment Links and metadata limits are covered in the general guide to Stripe Checkout UTM parameters. Other PHP and server stacks: Laravel, Django, Rails and Phoenix.

Start free trial

The secret key: .env.local or secrets

Symfony loads .env, which is committed, and then .env.local, which is not (Symfony configuration). Commit an empty entry and keep your test key on your machine:

# .env (committed)
STRIPE_SECRET_KEY=

# .env.local (not committed)
STRIPE_SECRET_KEY=sk_test_...

For production, set a real environment variable on the server, or store the live key in the encrypted vault with php bin/console secrets:set STRIPE_SECRET_KEY --env=prod (Symfony secrets). The encrypted value can be committed; the decryption key config/secrets/prod/prod.decrypt.private.php must not, and goes to the server as a file or as SYMFONY_DECRYPTION_SECRET. Code reads a secret exactly like an environment variable, so nothing below changes.

StripeClient as a service

Install stripe-php with composer require stripe/stripe-php (stripe-php) and register its client once, with the key as its constructor argument:

# config/services.yaml
services:
    # ... the default _defaults and App\ entries

    Stripe\StripeClient:
        arguments: ['%env(STRIPE_SECRET_KEY)%']

Any controller action can now type-hint StripeClient and receive it (Symfony autowiring), already holding the key.

The script tag in base.html.twig

Add the tag before </head> in templates/base.html.twig (Symfony templates). Put it outside {% block javascripts %} and the other blocks, since a child template that overrides a block without parent() would drop it. On a self-hosted server, change app.virling.com to your own host.

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

Request::cookies in the controller

Type-hint Request in the action and read the cookie from its cookies bag (HttpFoundation). It holds what PHP put in $_COOKIE, so get() returns the string the script wrote, or null:

$vid = $request->cookies->get('virling_vid');

Symfony does not encrypt or sign cookies by default, so there is no exception list to edit, as there is in some other PHP frameworks.

A Symfony form for the buy button

One action renders the form on GET and creates the session on a valid POST. createFormBuilder() with a SubmitType is enough, and with symfony/security-csrf installed the form adds and checks a CSRF token without extra code (Symfony forms, CSRF protection):

<?php
// src/Controller/PricingController.php
namespace App\Controller;

use Stripe\StripeClient;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class PricingController extends AbstractController
{
    #[Route('/pricing', name: 'pricing', methods: ['GET', 'POST'])]
    public function pricing(Request $request, StripeClient $stripe): Response
    {
        $form = $this->createFormBuilder()
            ->add('buy', SubmitType::class, ['label' => 'Buy'])
            ->getForm();
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $params = [
                'line_items' => [['price' => 'price_...', 'quantity' => 1]],
                'mode' => 'payment',
                'success_url' => 'https://yourdomain.com/thanks',
            ];
            if ($vid = $request->cookies->get('virling_vid')) {
                $params['client_reference_id'] = $vid;
            }

            $session = $stripe->checkout->sessions->create($params);

            return $this->redirect($session->url, Response::HTTP_SEE_OTHER);
        }

        return $this->render('pricing.html.twig', ['form' => $form]);
    }
}

$stripe->checkout->sessions->create() is the stripe-php call from Stripe's API reference, and Stripe accepts up to 200 characters in client_reference_id. The template renders the whole form, hidden _token field included:

{# templates/pricing.html.twig #}
{% extends 'base.html.twig' %}

{% block body %}
    {{ form(form, {attr: {'data-turbo': 'false'}}) }}
{% endblock %}

The data-turbo attribute only matters with Symfony UX Turbo, which submits forms with fetch and cannot follow a redirect to checkout.stripe.com; turning it off lets the browser navigate (Turbo handbook). Without the Form component, a plain <form> with csrf_token('checkout') and isCsrfTokenValid() in the action does the same job.

When client_reference_id holds your user's ID

If the signed-in user's ID already goes in client_reference_id, move the visitor ID to the session's metadata. Virling checks metadata.virling_vid before client_reference_id (Stripe docs):

$params['client_reference_id'] = (string) $this->getUser()->getId(); // your User entity
if ($vid = $request->cookies->get('virling_vid')) {
    $params['metadata'] = ['virling_vid' => $vid];
}

Use the numeric or UUID primary key, not getUserIdentifier(), which is often an email address. Metadata placed only in subscription_data lands on the subscription, which Virling does not read.

Subscriptions and renewals

Set 'mode' => 'subscription' with a recurring price and leave the cookie lines alone. Later charges keep the channel of the customer's first payment, as explained in renewals, and if your User entity stores a Stripe customer ID, passing it as 'customer' ties a second plan to that same first payment.

Checking it on staging

With the test key in .env.local and a restricted key starting with rk_test_ connected in Virling, run one tagged visit through test your setup. The Symfony local server on 127.0.0.1:8000 is skipped by the script unless the tag has data-dev, and only your site's domain and subdomains are tracked, so a host like staging.yourdomain.com is the place for the full path. To compare IDs, autowire LoggerInterface $logger into the action and log the session, then match it against window.virling.vid() in the browser console:

$logger->info('checkout', ['id' => $session->id, 'ref' => $session->client_reference_id]);

Common problems

SymptomCauseFix
The CSRF token is invalid on the formThe fields are rendered one by one and the hidden _token field is missingEnd the form with form_end(form), or render it with form(form)
The button does nothing and the console shows a CORS errorTurbo submits with fetch and tries to follow the redirect to StripeAdd data-turbo="false" to the form
Environment variable not found: "STRIPE_SECRET_KEY"The key is in neither the environment, .env.local nor the vault for this environmentSet it, or run secrets:set with the right --env and deploy the decryption key
Cannot autowire argument $stripeStripeClient is not registered as a serviceAdd the entry to config/services.yaml
No visitor ID, though the browser has the cookieThe session is created in a Messenger handler or console command, where no browser request existsRead the cookie in the controller and put the value in the message
The ID shows on the subscription onlyIt went into subscription_data.metadataSet metadata on the Checkout Session itself
Some payments are UnattributedThose buyers had no cookie, because the script was blocked or the site runs cookielessNothing: the if leaves the field out and the revenue still counts

Never substitute a Symfony session ID or user ID for a missing visitor ID, since Virling has no visits under it. More causes are in Unattributed revenue, the Stripe integration page lists what Virling imports, and the checkout snippet generator covers other providers.

Frequently asked questions

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

Send one visitor ID rather than the tags. In the action that creates the Checkout Session, read $request->cookies->get('virling_vid') and add it to the stripe-php parameters as client_reference_id. Virling holds the UTM tags of each visit recorded under that ID.

Do I have to exclude the cookie from encryption in Symfony?

No. Symfony does not encrypt or sign cookies by default, and $request->cookies holds what PHP put in $_COOKIE. The value arrives exactly as the script wrote it.

Should STRIPE_SECRET_KEY go in .env or in Symfony secrets?

Neither file should hold a live key in git. Keep a test key in .env.local, which is not committed, and in production use a server environment variable or php bin/console secrets:set STRIPE_SECRET_KEY --env=prod. Both are read with %env(STRIPE_SECRET_KEY)%, so the StripeClient service does not change.

Does the Symfony form need its own CSRF code?

No. With symfony/security-csrf installed, the form adds a hidden _token field and isValid() checks it. Render the form with form(form) or end it with form_end(form) so the field is included.

What if the virling_vid cookie is missing?

$request->cookies->get('virling_vid') returns null, which happens when the script is blocked or the site runs cookieless. The controller leaves client_reference_id out, Stripe takes the payment as usual, and Virling counts it as Unattributed revenue.

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