Stripe Checkout
View as MarkdownCredit Stripe Checkout Sessions created on your server to the visit that led to them, with Next.js, Express or any backend language.
On this page
When your server creates Stripe Checkout Sessions, add the Reveata visitor and session ids to the session. Reveata reads them when Stripe reports the payment and credits it to the right visit. First connect Stripe with a restricted key or Connect with Stripe.
Reveata reads the ids from any of these places on the session:
| Where | Keys |
|---|---|
metadata |
reveata_visitor_id, reveata_session_id, and optionally reveata_user_id (the userId you pass to identify) |
client_reference_id |
dt_<visitorId>_<sessionId>, the format the script writes on Payment Links |
The ids from the session are applied to the payment it creates: the PaymentIntent in payment mode, or the first invoice and the subscription in subscription mode. Later invoices of that subscription are renewals and keep the first payment's source, so you only need the ids once.
Get the ids
The tracking script keeps the ids in two first-party cookies on your domain, and also exposes them in the browser. Use whichever is easier.
From the browser, send them with the request that starts checkout:
await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ priceId, ...window.reveata.metadata() }),
});window.reveata.metadata() returns { reveata_visitor_id, reveata_session_id }, or {} when the script has no ids (cookieless mode, or a blocked script).
From the cookies on your server, when checkout starts from a plain form or link and your server runs on the same domain (or a subdomain) as your site:
| Cookie | Value | Lifetime |
|---|---|---|
_dt_v |
<visitorId>.<visit number> |
400 days |
_dt_s |
<sessionId>.<last activity time> |
30 minutes, renewed on every event |
The id is the part before the first dot: lowercase letters and digits. The session cookie can be missing after 30 idle minutes; the visitor id alone is enough to match the payment.
Next.js
With @reveata/next (npm packages), readTrackerIds reads both cookies for you in a route handler or server action:
// app/api/checkout/route.ts
import { cookies } from 'next/headers';
import Stripe from 'stripe';
import { readTrackerIds } from '@reveata/next/server';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(request: Request) {
const { priceId } = await request.json();
const ids = readTrackerIds(await cookies());
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [{ price: priceId, quantity: 1 }],
success_url: 'https://example.com/thanks',
cancel_url: 'https://example.com/pricing',
metadata: {
...(ids.visitorId ? { reveata_visitor_id: ids.visitorId } : {}),
...(ids.sessionId ? { reveata_session_id: ids.sessionId } : {}),
},
});
return Response.json({ url: session.url });
}clientReference(ids) from the same import returns the dt_<visitorId>_<sessionId> string if you would rather use client_reference_id.
Express
const express = require('express');
const Stripe = require('stripe');
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const app = express();
// "<id>.<rest>" → id, or undefined when the cookie is missing or malformed.
function trackerId(cookieHeader, name) {
const m = new RegExp('(?:^|; )' + name + '=([a-z0-9]{8,64})\\.').exec(cookieHeader || '');
return m ? m[1] : undefined;
}
app.post('/api/checkout', express.json(), async (req, res) => {
const visitorId = req.body.reveata_visitor_id || trackerId(req.headers.cookie, '_dt_v');
const sessionId = req.body.reveata_session_id || trackerId(req.headers.cookie, '_dt_s');
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items: [{ price: req.body.priceId, quantity: 1 }],
success_url: 'https://example.com/thanks',
metadata: {
...(visitorId && { reveata_visitor_id: visitorId }),
...(sessionId && { reveata_session_id: sessionId }),
},
});
res.json({ url: session.url });
});Any other backend
Read the two cookies and keep the part before the first dot. Then put the values in metadata as above.
<?php
function reveata_id(string $cookie): ?string {
$id = explode('.', $_COOKIE[$cookie] ?? '')[0];
return preg_match('/^[a-z0-9]{8,64}$/', $id) ? $id : null;
}
$metadata = array_filter([
'reveata_visitor_id' => reveata_id('_dt_v'),
'reveata_session_id' => reveata_id('_dt_s'),
]);import re
def reveata_id(cookies, name):
value = cookies.get(name, "").split(".")[0]
return value if re.fullmatch(r"[a-z0-9]{8,64}", value) else None
# Flask: request.cookies · Django: request.COOKIES
metadata = {k: v for k, v in {
"reveata_visitor_id": reveata_id(request.cookies, "_dt_v"),
"reveata_session_id": reveata_id(request.cookies, "_dt_s"),
}.items() if v}def reveata_id(cookies, name)
id = cookies[name].to_s.split('.').first.to_s
id.match?(/\A[a-z0-9]{8,64}\z/) ? id : nil
end
# Rails controller
metadata = {
reveata_visitor_id: reveata_id(cookies, '_dt_v'),
reveata_session_id: reveata_id(cookies, '_dt_s'),
}.compactvar trackerID = regexp.MustCompile(`^[a-z0-9]{8,64}$`)
func reveataID(r *http.Request, name string) string {
c, err := r.Cookie(name)
if err != nil {
return ""
}
id := strings.SplitN(c.Value, ".", 2)[0]
if !trackerID.MatchString(id) {
return ""
}
return id
}When there are no ids
In cookieless mode, or when a blocker stopped the script, there are no ids to send. The payment is still recorded, and Reveata then matches it by the buyer's email for visitors you identify. Unmatched payments are tried again every hour for 90 days, so an identify call that happens after the purchase still links it.
Check it works
- Open your site in a private window from a link ending in
?ref=test. - Buy something with a Stripe test key on a test website, or make a small real purchase and refund it afterwards. A free, fully discounted checkout is not a payment, so it does not show up.
- In Stripe, open the Checkout Session: its metadata shows
reveata_visitor_id. - In Reveata, the payment appears under Revenue with the source
test. In Settings → Payments, the recent payments list shows the matched visitor.
A replayed webhook or a later import of the same session never adds the payment again: payments are keyed on their Stripe ids.