Skip to main content

How to connect Stripe payments to your content

Pass one id from your page to Stripe, receive it in a webhook, and join it to the post that sent the buyer. Working code and a test you can run today.

Written by
The Totems team
Published
Updated
Reading time
6 minutes

Short answer

How do I link Stripe sales to a post or channel?

Save a random visitor id when someone lands from your post. When they pay, send that id to Stripe as client_reference_id, and copy it into the payment's metadata. Listen for checkout.session.completed, look up the id, and you know the post. If the id is missing, match by email, or mark it Unknown.

Who this is for. People who sell with Stripe and can edit a page or a server. You need a little code, or someone who writes it.

On this page

Stripe is good at money and knows nothing about your posts. That is fine. You only need it to hold one small note for you and give it back.

What has to happen

There are four moves: save an id, send it, get it back, look it up.

  1. Page

    Save a random id

    v_51Xa

  2. Server

    Make a Checkout Session

    client_reference_id

  3. Stripe

    Takes the payment

    cs_test_…

  4. Webhook

    Sends it back to you

    v_51Xa

  5. Your list

    Find the clicks

    /price, 18 Nov

Figure 1One id goes out with the buyer and comes back with the payment.Made-up example

Send the id

When your server makes the Checkout Session, set the id in two places. The first goes on the session. The second goes on the payment itself.

Your server
const session = await stripe.checkout.sessions.create({
  mode: "payment",
  line_items: [{ price: "price_123", quantity: 1 }],
  success_url: "https://studio.example/thanks",
  client_reference_id: visitorId,
  metadata: { visitor_id: visitorId },
  payment_intent_data: { metadata: { visitor_id: visitorId } },
});

For a subscription, use subscription_data.metadata instead. Stripe then also shows it on each invoice.

Get it back

Check the signature first, then read the id. Use the payment id as the key, so one payment is one sale.

Your webhook
const event = stripe.webhooks.constructEvent(rawBody, signature, secret);
if (event.type === "checkout.session.completed") {
  const s = event.data.object;
  if (s.payment_status === "paid") {
    await saveSale({
      key: s.payment_intent,           // one payment, one sale
      visitorId: s.client_reference_id, // may be null
      email: s.customer_details?.email, // the fallback
      cents: s.amount_total,
      currency: s.currency,
    });
  }
}

Join it to a post

Now the easy part. Look for proof in this order and stop at the first hit.

OrderProofTrust it?
1The visitor id on the paymentYes. It came from the same browser
2A Stripe customer you knowYes. They have paid before
3The same emailYes, if the form used it too
4NothingMark it Unknown

Here is a made-up day with four payments. Only one needs a guess, and we don't make one.

LineVideoEmail postUnknown
Alex, by visitor id$2,000$0$0
Priya, by email$0$490$0
Sam, no proof$0$0$490
Jo, by visitor id$490$0$0
Net sales$2,490$490$490
Figure 2Four payments on one day. The unmatched one still counts, in its own column.Made-up example

If you don't know, write Unknown. A wrong match costs more than a missing one.

Test it in fifteen minutes

  1. Use Stripe test mode and a test card.
  2. Click your own tagged link in a private window.
  3. Pay with the test card.
  4. Open the event in Stripe and find your id.
  5. Pay again without clicking a link. It must land in Unknown.

The fifth step matters most. A setup that never says Unknown is guessing.

A worked example with every field

A made-up studio sells a $490 course with a Payment Link and a $2,000 programme with Checkout. One buyer, Alex, does this.

DayWhat Alex doesWhat you save
1Clicks a video linkClick, with link /price
1Says yes to trackingVisitor v_51Xa
3Sends the formEmail, joined to v_51Xa
9Opens Checkoutclient_reference_id: v_51Xa
9Pays $2,000Payment, with the id
30Gets $500 backRefund on the same payment

On day 9 the webhook brings the id. You look up v_51Xa, find one click on day 1, and the video gets the sale. On day 30 the refund arrives with the payment's id. You find the sale and lower it. The video now shows $1,500.

Sale pi_3Kq

Paid
$2,000.00
Refunded
−$500.00
Net
$1,500.00
Visitor id
v_51Xa
First click
/price, day 1
Matched by
visitor id
Events seen
evt_1, evt_2
Figure 3The row you keep for Alex's sale. Every line can be traced to a click or a Stripe event.Made-up example

Notice the last line. You keep the event ids so a repeat does nothing.

Subscriptions need one more thing

A subscription pays again each month, with no visit and no browser. If you only save the id on the first session, month two looks like a new Unknown sale.

Set the id in subscription_data.metadata. Stripe's metadata page says a subscription's metadata is copied to its invoices as a snapshot. So each renewal carries the id.

Subscription
await stripe.checkout.sessions.create({
  mode: "subscription",
  line_items: [{ price: "price_monthly", quantity: 1 }],
  success_url: "https://studio.example/thanks",
  client_reference_id: visitorId,
  subscription_data: { metadata: { visitor_id: visitorId } },
});

Then decide what a renewal means for credit. Two fair choices:

  • All payments to the first source. Good for asking what a video is worth over time.
  • Only the first payment. Good for asking what brought new people this month.

Pick one and write it down. Changing halfway makes months impossible to compare.

Edge cases worth a test

CaseWhat happensWhat to do
Buyer pays twiceTwo payments, one idTwo sales, same source
Couple shares a laptopSecond buyer carries the first one's idIf the email belongs to someone else, flag it
Free trialSession completes with no moneyDon't count until an invoice is paid
100% couponAmount is zeroCount the customer, not money
Other currencyAmount is in another unitSave both, with that day's rate
You send an invoice by handNo session at allMatch by customer or email
Dispute opensMoney leaves your balanceTake it out until it is decided

The shared laptop is the sneaky one. The browser says Alex. The payment says Jo. The payment knows who paid, so Jo is the buyer. Don't give Jo's sale to Alex's clicks without other proof.

A daily check that takes a minute

  1. Count yesterday's paid Stripe payments.
  2. Count yesterday's sales in your list.
  3. If they differ, find the missing payment id.
  4. Look at the share with no id. If it doubles, a page or button changed.

Do this for two weeks after you launch. Most mistakes show in the first three days.

If you have no server

You can still do half of it. Use Payment Links with the id in the address. Once a week, export payments from Stripe and put them in a sheet. Add a second tab with your visitor ids and first clicks. Join them with a lookup. Payments without a match go in an Unknown tab, where you can see them. Don't delete that tab. It is the most honest part of the sheet.

What can go wrong

  • You count two events as two sales. Use the payment id, not the event id, as the key for the sale.
  • You count money that has not arrived. Bank debits and vouchers can take 2 to 14 days to confirm. Wait for paid.
  • The field is taken. If another tool uses client_reference_id, leave it and use metadata only.
  • The id is personal. Never put an email in it. Stripe warns that links with parameters can turn up in unexpected places.

When not to use Totems

If you have a developer and one checkout, the code above may be all you need. If your buyers pay inside a platform that hides its checkout, no script can add an id. And if you take fewer than ten payments a month, ask each buyer how they found you and write it down.

Totems does these steps for you, with a proof card on each sale. Its Stripe connection is written and passes our own tests. It is not yet tested with a live account.

Sources

  1. Stripe: The Checkout Session objectChecked
  2. Stripe: MetadataChecked
  3. Stripe: Receive events with webhooksChecked
  4. Stripe: Track a payment linkChecked
Read as MarkdownFound a mistake? Tell us: First version, with code and the Stripe pages we checked.
Questions

More questions.

Can't find it? Ask us.

Can I see the source of old Stripe payments?

Only if you saved it at the time. Stripe can't tell you which post a past buyer clicked. You can still bring the payments in and mark them Unknown.

Should I put the video name in Stripe instead of an id?

You can, but it only holds one post. An id lets you look up every click that person made, so you can change the credit rule later.

Which event should I listen for?

Use checkout.session.completed for Checkout and Payment Links. Some payment methods, such as bank debits, confirm days later, so check payment_status before you count the money.

Can one sale arrive twice?

The same event can be sent again, because Stripe retries when your server does not answer. Save the event id and the payment id, and skip any you have seen.

Next note

No. 04

Stripe client_reference_id: a plain guide

What to put in client_reference_id, what Stripe drops without telling you, where it comes back, and copy-ready examples for links and Checkout.

Payments and StripeNo. 11

Why Stripe and Google Analytics don't match

7 minute read

YouTube moneyNo. 01

How to track which YouTube video made a sale

8 minute read

Put one link in your next post and follow it. 7 days free.

Start free trialView demo