Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Stripe retries webhooks: avoid double Meta and GA4 purchases with the event id

Disclosure: I'm on the FloorSync team. We sell a paid tool for this, but the pattern below needs nothing from us. You send Stripe sales to Meta and GA4 from your webhook. It works. Then one day your Meta purchases are h

Disclosure: I'm on the FloorSync team. We sell a paid tool for this, but the pattern below needs nothing from us.

You send Stripe sales to Meta and GA4 from your webhook. It works. Then one day your Meta purchases are higher than your Stripe payments. Or GA4 shows two purchases for one invoice.

Most often the cause is not a bug in your handler. It's that Stripe sends the same event more than once, and your code sent each copy on.

Why the same event arrives twice

Stripe expects a 2xx answer from your endpoint. If your server is slow, crashes, or answers an error, Stripe tries again later. So one invoice.paid can reach you two or three times. Even when you answer 200 every time, you should assume duplicates can happen: handle each event so that running it twice changes nothing.

There is a second source of doubles. If the browser pixel fired on your thank-you page and your webhook sent a Purchase for the same sale, Meta sees two events unless they share an id.

The fix: one stable id per payment

Use the Stripe id of the payment, not a random one, so a retry produces the same id as the first try:

  • First sale: the Checkout session id, cs_...
  • Renewal: the invoice id, in_...

In Meta's Conversions API that goes in event_id. Meta merges events that carry the same event_id (and the same event name). In GA4's Measurement Protocol it goes in transaction_id.

function paymentId(event) {
  const obj = event.data.object;
  if (event.type === 'checkout.session.completed') return obj.id; // cs_...
  if (event.type === 'invoice.paid') return obj.id;               // in_...
  return null;
}

If you also fire the browser pixel on the thank-you page, give it the same eventID as the server uses. The session id is in the success URL if you set success_url to include {CHECKOUT_SESSION_ID}:

// browser, thank-you page
fbq('track', 'Purchase', { value: 29, currency: 'USD' }, { eventID: sessionIdFromUrl });

Don't rely only on the platform: dedupe yourself too

Meta merging by event_id is a safety net, not a plan. GA4 will not always save you either. Keep your own record of what you already sent, and skip it on a retry.

// Postgres: a table with the payment id as the primary key
// CREATE TABLE sent_events (payment_id text PRIMARY KEY, sent_at timestamptz DEFAULT now());

app.post('/stripe/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(req.body, req.headers['stripe-signature'], WEBHOOK_SECRET);
  } catch {
    return res.sendStatus(400);
  }

  const id = paymentId(event);
  if (!id) return res.sendStatus(200);

  // claim the id first: a retry that arrives now inserts nothing and stops here
  const claimed = await db.query(
    'INSERT INTO sent_events (payment_id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING payment_id',
    [id]
  );
  if (claimed.rowCount === 0) return res.sendStatus(200);

  try {
    await sendToMetaAndGa4(event, id); // event_id = id, transaction_id = id
  } catch (err) {
    // release the claim so Stripe's retry can try again
    await db.query('DELETE FROM sent_events WHERE payment_id = $1', [id]);
    return res.sendStatus(500);
  }
  res.sendStatus(200);
});

Two details that matter:

  1. Claim before you send. If you send first and record after, two retries arriving at the same moment both see "not sent yet".
  2. Answer 500 on a real failure, after releasing the claim. That tells Stripe to try again, and the same id keeps the retry from doubling.

Test it

  • Replay an event with the Stripe CLI (stripe events resend evt_...) and check that your log shows one send and one skip.
  • In Meta Events Manager, open Test events and send with the test_event_code. Send the same event_id twice and look at how Meta shows it.
  • For GA4, /mp/collect answers 204 whatever you send. Post the same body to /debug/mp/collect first: it returns validationMessages.

One more choice: do renewals count as new Purchases?

Not about doubles, but you'll hit it right after. Tracking Consulting warns that sending each renewal as a new Purchase can inflate numbers, since no new ad click is behind month five. The other view is that campaigns that bring people who stay should get credit, and Meta's optimisation learns from buyers who keep paying. The experts disagree. If you send renewals, you can mark them system_generated and keep them apart from new money. If you don't want them in Meta, skip invoice.paid events where billing_reason is subscription_cycle. Decide on purpose. I wrote about this more in the renewals post.

A public example of why the webhook path matters at all: a small shop's only real buyer paid with Cash App Pay, the pixel never loaded on the success page, and the sale was fixed by sending the Purchase from the Stripe webhook (GitHub issue).

Build it, or use a tool

If Meta is your only ad platform and you can maintain this, build it. It's a few hundred lines.

FloorSync does these steps for $29 a month, with 7 free days: your webhook passes each verified Stripe event on, it sends it to Meta and GA4 with the Stripe id as the event id, and it keeps every send and its answer in a log. Add ?dry_run=1 and nothing is sent: you get the payloads back.

See what Meta and GA4 would get, free, no sign-up: run the dry run. A free key needs only an email: get one.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.