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

Rails Stripe UTM tracking: Checkout and the Pay gem

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

In a Rails app, the controller action that creates the Stripe Checkout Session reads cookies[:virling_vid] and hands it to the stripe gem as client_reference_id. Three things are particular to Rails: which cookie jar returns the value, how the redirect to Stripe gets past Turbo and the open redirect check, and where the Pay gem takes the ID.

Why UTM tags never reach Stripe's checkout page, and how Virling joins a payment to the visits behind its visitor ID, is in the general guide to Stripe Checkout UTM parameters. The PHP version of this setup is Laravel Stripe UTM tracking, Elixir is in Phoenix Stripe UTM tracking, and Paddle on Rails is in Rails Paddle UTM tracking.

Start free trial

The tag in application.html.erb

Put it in the <head> of app/views/layouts/application.html.erb, next to javascript_importmap_tags or javascript_include_tag. On a self-hosted install, src points at your own Virling server.

<!-- app/views/layouts/application.html.erb -->
<script defer src="https://app.virling.com/v.js"
  data-site="yourdomain.com"></script>

Turbo Drive replaces the <body> on each link click and merges the <head>, so the script loads once and keeps running. Turbo changes the address with history.pushState, which the script listens to, so each Turbo visit is still a pageview.

Read cookies[:virling_vid], not the signed jar

Rails has a plain cookie jar and two that check a signature: cookies.signed and cookies.encrypted only accept values Rails wrote itself with secret_key_base. The script writes virling_vid in the browser, so those two return nil for it, while cookies[:virling_vid] returns the value the browser sent.

With the stripe gem, set the secret key once in an initializer, then create the session with Stripe::Checkout::Session.create:

# config/initializers/stripe.rb
Stripe.api_key = Rails.application.credentials.dig(:stripe, :secret_key)

# app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  def create
    session_params = {
      line_items: [{ price: "price_...", quantity: 1 }],
      mode: "subscription",
      success_url: "https://yourdomain.com/thanks",
    }
    vid = cookies[:virling_vid]
    session_params[:client_reference_id] = vid if vid.present?

    checkout_session = Stripe::Checkout::Session.create(session_params)
    redirect_to checkout_session.url, allow_other_host: true, status: :see_other
  end
end

Route it with resource :checkout, only: :create in config/routes.rb. When the script is blocked or the site runs in cookieless mode, vid.present? is false and the session goes out without the key.

The redirect to Checkout, with Turbo

Two lines of the action exist because of Rails. Apps on Rails 7.0 defaults or later raise ActionController::Redirecting::UnsafeRedirectError when redirect_to points at another host, so the call passes allow_other_host: true for checkout.stripe.com. Turbo Drive expects a 303 See Other after a form POST, hence status: :see_other.

Turbo submits forms with fetch, and a fetch cannot follow a redirect to Stripe's domain, which sends no CORS headers for it. Turn Turbo off for this one form, so the browser submits it as a normal page load and follows the redirect itself:

<%= button_to "Subscribe", checkout_path, form: { data: { turbo: false } } %>

The same goes for form_with: add data: { turbo: false } to it.

With the Pay gem

The Pay gem creates the Stripe customer for the signed-in user, and its payment_processor.checkout sends the options it does not handle itself on to Stripe. Put the visitor ID in metadata there, which leaves client_reference_id for your own IDs:

def create
  current_user.set_payment_processor :stripe
  options = {
    mode: "subscription",
    line_items: "price_...",
    success_url: "https://yourdomain.com/thanks",
    cancel_url: "https://yourdomain.com/pricing",
  }
  vid = cookies[:virling_vid]
  options[:metadata] = { virling_vid: vid } if vid.present?

  checkout_session = current_user.payment_processor.checkout(**options)
  redirect_to checkout_session.url, allow_other_host: true, status: :see_other
end

Pay always sets customer on the session, so a plan the same user buys later is matched to their first payment.

Subscriptions: the session, not subscription_data

Renewals need no code, because each one keeps the channel of the customer's first payment (renewals). What matters is where the first payment's ID goes. Metadata under subscription_data lands on the Stripe subscription, which Virling does not read, so set it at the top level of the session params:

session_params = {
  mode: "subscription",
  line_items: [{ price: "price_...", quantity: 1 }],
  success_url: "https://yourdomain.com/thanks",
  # Virling does not read the subscription's metadata
  subscription_data: { metadata: { plan: "pro" } },
}
vid = cookies[:virling_vid]
# Virling reads this one, on the session
session_params[:metadata] = { virling_vid: vid } if vid.present?

Virling looks at the charge, then its PaymentIntent, then the Checkout Session, as listed in the Stripe docs, which also cover PaymentIntents for Stripe Elements. The Stripe integration page shows what is imported.

Test it with the Rails log and console

In Virling, connect a restricted Stripe key starting with rk_test_; the app keeps its own test secret key in credentials and a price from test mode. Then make one tagged visit and one test card payment, as in test your setup. Log the session right after it is created and compare it with window.virling.vid() in the browser console:

Rails.logger.info "#{checkout_session.id} #{checkout_session.client_reference_id} #{checkout_session.metadata.to_h}"

To look at a session after the fact, run Stripe::Checkout::Session.retrieve("cs_test_...").client_reference_id in bin/rails console.

Rails blocks unknown hosts in development, so a tunnel or test subdomain has to be in config.hosts. With Pay, sign up as a fresh user for each run, since a second charge to one Stripe customer counts as a renewal. The SaaS page shows what the reports then give you per channel.

Common mistakes

When a test payment shows as Unattributed in Virling, open it: no Visitor under Details means the session went to Stripe without the ID.

What you seeCauseFix
vid is always nilcookies.signed or cookies.encrypted rejects a cookie Rails did not signRead cookies[:virling_vid]
cookies is undefined in an API controllerActionController::API leaves out cookie supportAdd include ActionController::Cookies, or create the session in a controller that inherits from ActionController::Base
ActionController::Redirecting::UnsafeRedirectErrorredirect_to refuses a URL on another host by defaultPass allow_other_host: true
Clicking Subscribe does nothing, with a CORS error for checkout.stripe.com in the consoleTurbo submitted the form with fetch and tried to follow the redirectAdd data: { turbo: false } to the form
No visitor ID, though the browser has the cookieThe session is created in an Active Job or a webhook controller, outside the buyer's requestRead the cookie in the controller the browser posts to and pass it to the job, for example CheckoutJob.perform_later(vid)
No virling_vid cookie on localhost:3000The script does nothing on localhost and 127.* without data-dev, and visits there are not kept for your siteAdd data-dev while you develop, and test on a subdomain of the domain in data-site
Several buyers land on the same Checkout SessionThe session URL was cached, for example with Rails.cache.fetch or a cached page that contains itCreate the session in the POST action, once per click
Stripe shows the ID on the subscription, but the payment is UnattributedIt is only in subscription_data[:metadata]Set it at the top level of the session, as in the subscription example

Page and fragment caching for ordinary pages is fine, because the cookie is set in the browser; only the checkout request has to reach Rails with its cookies (page caching and CDNs). Payments without a visitor ID still count as revenue, and the remaining causes are in Unattributed revenue.

Frequently asked questions

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

Pass the visitor ID instead. Read cookies[:virling_vid] in the action that creates the Checkout Session and set it as client_reference_id. Virling has the UTM tags of each visit stored under that ID, so the payment is joined to all of them.

Why is cookies.signed[:virling_vid] nil?

The signed and encrypted jars only accept cookies Rails wrote with secret_key_base. The Virling script writes virling_vid in the browser, so read it from the plain jar with cookies[:virling_vid].

How do I add the visitor ID with the Pay gem?

Pass it in the options of payment_processor.checkout, for example metadata: { virling_vid: cookies[:virling_vid] }. Pay sends the options it does not handle itself to Stripe when it creates the Checkout Session.

Why does the redirect to Stripe Checkout fail with Turbo?

Turbo Drive submits the form with fetch, and fetch cannot follow a redirect to checkout.stripe.com. Add data: { turbo: false } to the form, for example button_to "Subscribe", checkout_path, form: { data: { turbo: false } }, and redirect with allow_other_host: true and status: :see_other.

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