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

Phoenix Elixir Stripe UTM tracking: controllers and LiveView

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

In Phoenix, the visitor ID arrives on the conn. Read virling_vid with get_cookies(conn) in the controller that creates the Stripe Checkout Session, send it as client_reference_id through stripity_stripe or a plain Req call, and redirect with external:. A LiveView has no cookies on its socket, so it either posts a form to that controller or gets the value from the conn before it mounts.

UTM tags in a landing URL never reach checkout.stripe.com, so the Virling script keeps them against that visitor ID, and Virling joins the payment to the visits behind it. Payment Links and metadata limits are in the general guide to Stripe Checkout UTM parameters. The code follows the Phoenix 1.8 and LiveView docs linked below. Other stacks: Rails, Django, Next.js and Symfony.

Start free trial

The script tag in root.html.heex

lib/my_app_web/components/layouts/root.html.heex wraps every page, LiveViews included, and is rendered once per HTTP request (Phoenix layouts). Put the tag before </head> there, not in Layouts.app, which sits inside each LiveView's own markup. A self-hosted server goes in place of app.virling.com.

<%!-- lib/my_app_web/components/layouts/root.html.heex --%>
<script defer src="https://app.virling.com/v.js"
  data-site="yourdomain.com"></script>

LiveView navigation changes the URL with history.pushState, which the script counts as a new page, so pages reached with <.link navigate> or patch show up too.

Reading the cookie from conn

get_cookies/1 returns the request cookies as a map of strings (Plug.Conn):

vid = get_cookies(conn)["virling_vid"]

It works once cookies are fetched, and the generated :browser pipeline already does that, because fetch_session fetches them first (Plug.Conn). The script writes a plain cookie, so leave out the :signed and :encrypted options of fetch_cookies/2. A visitor without one gives nil.

The Stripe key in config/runtime.exs

config/runtime.exs runs when the release boots, so the key comes from the server's environment and never from a compiled config file. With stripity_stripe (hex.pm), add {:stripity_stripe, "~> 3.2"} to mix.exs and set:

# config/runtime.exs
config :stripity_stripe, api_key: System.fetch_env!("STRIPE_SECRET_KEY")

System.fetch_env!/1 stops the boot with a clear error when the variable is missing, instead of failing on the first checkout.

A controller with stripity_stripe

Stripe.Checkout.Session.create/1 takes a map with atom keys and returns {:ok, session} or {:error, error} (Stripe.Checkout.Session). The redirect needs external:, since Phoenix refuses to: for another host (Phoenix controllers):

# lib/my_app_web/controllers/checkout_controller.ex
defmodule MyAppWeb.CheckoutController do
  use MyAppWeb, :controller

  def create(conn, _params) do
    params =
      put_visitor(
        %{
          line_items: [%{price: "price_...", quantity: 1}],
          mode: :payment,
          success_url: "https://yourdomain.com/thanks"
        },
        get_cookies(conn)["virling_vid"]
      )

    case Stripe.Checkout.Session.create(params) do
      {:ok, session} ->
        conn
        |> put_status(:see_other)
        |> redirect(external: session.url)

      {:error, _error} ->
        conn
        |> put_flash(:error, "Checkout is not available right now.")
        |> redirect(to: ~p"/")
    end
  end

  defp put_visitor(params, vid) when vid in [nil, ""], do: params
  defp put_visitor(params, vid), do: Map.put(params, :client_reference_id, vid)
end

Route it in the :browser scope of router.ex:

post "/checkout", CheckoutController, :create

The buy button is a <.form> with an action, which renders the CSRF token that protect_from_forgery checks (Phoenix.Component):

<.form for={%{}} action={~p"/checkout"}>
  <button type="submit">Buy</button>
</.form>

Or call the Stripe API with Req

stripity_stripe is a community library, and Stripe publishes no official one for Elixir. If you would rather not add it, the Checkout Session endpoint is one form-encoded POST (Stripe API reference). Req's :form option encodes a flat list of pairs, so nested fields use Stripe's bracket keys, and auth: {:bearer, key} sends the secret key (Req):

# config/runtime.exs
config :my_app, stripe_secret_key: System.fetch_env!("STRIPE_SECRET_KEY")

# in CheckoutController
def create(conn, _params) do
  vid = get_cookies(conn)["virling_vid"]

  form = [
    {"line_items[0][price]", "price_..."},
    {"line_items[0][quantity]", 1},
    {"mode", "payment"},
    {"success_url", "https://yourdomain.com/thanks"}
  ]

  form = if vid in [nil, ""], do: form, else: [{"client_reference_id", vid} | form]

  case Req.post("https://api.stripe.com/v1/checkout/sessions",
         auth: {:bearer, Application.fetch_env!(:my_app, :stripe_secret_key)},
         form: form
       ) do
    {:ok, %Req.Response{status: 200, body: %{"url" => url}}} ->
      conn |> put_status(:see_other) |> redirect(external: url)

    _ ->
      conn
      |> put_flash(:error, "Checkout is not available right now.")
      |> redirect(to: ~p"/")
  end
end

Req decodes the JSON reply into a map with string keys, so the URL is body["url"]. A Stripe error comes back as {:ok, response} with a 4xx status, which the catch-all clause handles.

When client_reference_id holds your user's ID

With phx.gen.auth in Phoenix 1.8, the signed-in user is in conn.assigns.current_scope. If you keep that user's ID in client_reference_id, move the visitor ID to the session's metadata, which Virling reads first (Stripe docs):

defp put_visitor(params, vid), do: Map.put(params, :metadata, %{"virling_vid" => vid})

# and in create/2
params = Map.put(params, :client_reference_id, to_string(conn.assigns.current_scope.user.id))

With Req, the same key is {"metadata[virling_vid]", vid}. Metadata given only under subscription_data ends up on the subscription, where Virling does not look.

Checkout from a LiveView page

A LiveView talks over a WebSocket, and cookies are not among the keys of get_connect_info/2 (Phoenix.LiveView). The cookie has to be read from the connection of an HTTP request, not from the socket.

Post a form to the controller

This is the simplest way. The form above works unchanged inside a LiveView: without phx-submit the browser submits it over HTTP, and the request carries the current cookie.

To run your own checks in the LiveView first, add phx-submit and phx-trigger-action. LiveView handles the event, then submits the form to the controller (LiveView form bindings):

# lib/my_app_web/live/pricing_live.ex
defmodule MyAppWeb.PricingLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, assign(socket, trigger_submit: false)}
  end

  def handle_event("buy", _params, socket) do
    {:noreply, assign(socket, trigger_submit: true)}
  end

  def render(assigns) do
    ~H"""
    <.form
      for={%{}}
      id="checkout"
      action={~p"/checkout"}
      phx-submit="buy"
      phx-trigger-action={@trigger_submit}
    >
      <button type="submit">Buy</button>
    </.form>
    """
  end
end

Or read the cookie before the LiveView mounts

If the LiveView must create the Checkout Session itself, pass the cookie in with the :session option of live_session. Phoenix calls the function with the conn of the page request and merges the map, which needs string keys, into the LiveView session (live_session):

# lib/my_app_web/visitor.ex
defmodule MyAppWeb.Visitor do
  def session(conn) do
    %{"virling_vid" => Plug.Conn.get_cookies(conn)["virling_vid"]}
  end
end

# lib/my_app_web/router.ex, in the scope that pipes through :browser
live_session :pricing, session: {MyAppWeb.Visitor, :session, []} do
  live "/pricing", PricingLive
end

In the LiveView, keep the value from the second argument of mount/3 and use it when you create the session, with the same put_visitor/2 as in the controller:

def mount(_params, session, socket) do
  {:ok, assign(socket, vid: session["virling_vid"])}
end

def handle_event("buy", _params, socket) do
  params =
    put_visitor(
      %{
        line_items: [%{price: "price_...", quantity: 1}],
        mode: :payment,
        success_url: "https://yourdomain.com/thanks"
      },
      socket.assigns.vid
    )

  case Stripe.Checkout.Session.create(params) do
    {:ok, session} ->
      {:noreply, redirect(socket, external: session.url)}

    {:error, _error} ->
      {:noreply, put_flash(socket, :error, "Checkout is not available right now.")}
  end
end

This value is as old as the page request. On a new visitor's first page the script has not set the cookie yet when the server reads it, and live navigation inside the same live_session makes no new HTTP request. A visitor who lands on the LiveView and buys there has no ID, so prefer the form when the page can be a landing page.

Subscriptions

Change mode: :payment to mode: :subscription and use a recurring price; put_visitor/2 stays as it is. Renewals need no code: each later charge keeps the channel of the customer's first payment, as described in renewals. If the user already has a Stripe customer, pass its ID as customer so a plan bought later is matched to that first payment.

Testing on a real host

Export a test secret key before mix phx.server, and connect a restricted key starting with rk_test_ in Virling. The script ignores localhost:4000 unless the tag has data-dev, and visits count only on your site's domain and its subdomains, so run the full path on a host such as staging.yourdomain.com. While testing, inspect the new session in the controller and compare the ID with window.virling.vid() in the browser console:

IO.inspect({session.id, session.client_reference_id, session.metadata})

Then follow test your setup with one tagged visit and a Stripe test card. When the session has the ID but only LiveView purchases come in without it, switch that page to the form.

A buyer without the cookie, because the script is blocked or the site runs cookieless, hits the nil clause of put_visitor/2: the session is created as usual and the revenue counts as Unattributed. Never put a Phoenix session token or user ID in place of the visitor ID, since no visits are recorded under it. 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 Phoenix?

Pass the visitor ID, not the tags. In the controller action that creates the Checkout Session, take get_cookies(conn)["virling_vid"] and send it as client_reference_id. Virling already has the UTM tags of each visit recorded under that ID.

Can a LiveView read the cookie from the socket?

No. Cookies are not among the connect info a socket offers. Post a normal form to a controller, or read the cookie from the conn in the session function of a live_session.

Do I need fetch_cookies in the router?

Not in the default browser pipeline. Its fetch_session plug also fetches cookies. In a pipeline without it, add plug :fetch_cookies, or get_cookies/1 raises an error.

Can I call Stripe with Req instead of stripity_stripe?

Yes. Stripe has no official Elixir library, and a Checkout Session is one POST to https://api.stripe.com/v1/checkout/sessions. Pass the fields to Req's :form option with bracket keys such as line_items[0][price], authenticate with auth: {:bearer, key}, and read the url from the decoded body.

Where does the visitor ID go when client_reference_id holds current_scope.user.id?

Put it in the session's metadata as %{"virling_vid" => vid}. Virling reads metadata.virling_vid before client_reference_id, so your own user ID can stay where it is.

What if get_cookies returns nil?

The visitor has no cookie, because the script was blocked or the site runs cookieless. put_visitor/2 then leaves the field 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