Anh Tran dev notes

Production bugs from mobile and backend work, written up with the fix and how it was checked.

Note 01 / Subscriptions / Supabase / RevenueCat

A RevenueCat webhook handler for Supabase that does not lose a paid purchase

Failing closed on a missing secret, logging every event before acting on it, handling TRANSFER and refunds, and why a 200 for a rejected gem pack is a bug. Notes from a production Edge Function.

By
Trần Thế Anh, Software Engineer
Published
Work done
October 2026, Yuuki (React Native app, Supabase backend)
Stack
Supabase Edge Functions (Deno), Postgres RPC, RevenueCat webhooks and REST API
Reading
8 min, 1,663 words

A RevenueCat webhook looks like the easy part of subscriptions. The SDK handles the purchase, RevenueCat tells your server, and your server flips a flag. The handler for the Yuuki app is about 600 lines, and a good share of the comments in it explain something that went wrong without any visible error. This note walks through the parts that earned their lines: authentication that fails closed, an append-only event log, the TRANSFER event, refunds, and one status-code decision that decides whether a paying user gets their purchase.

Fail closed when the secret is missing

RevenueCat sends whatever string you configure in the webhook’s Authorization field. The handler compares it with a function secret, REVENUECAT_WEBHOOK_AUTH. The first version of that check read, in spirit, if (expected && provided !== expected) reject. When the variable was empty, the whole check was skipped, and anyone who found the function URL could post a forged event and grant themselves Pro or a pile of in-app currency.

The current version refuses everything when the secret is not set, and it answers with 500 rather than 401:

const expected = (Deno.env.get("REVENUECAT_WEBHOOK_AUTH") ?? "").trim();
if (!expected) {
  console.error("webhook secret not configured, rejecting every request");
  return json({ ok: false, error: "misconfigured" }, 500);
}
const provided = (req.headers.get("Authorization") ?? "")
  .trim()
  .replace(/^Bearer\s+/i, "");
if (!(await sameSecret(provided, expected))) {
  return json({ ok: false, error: "unauthorized" }, 401);
}

The 500 is deliberate. The mistake is on your side, so you want RevenueCat to keep retrying and to show the failure on its dashboard. When you set the variable, the backlog drains by itself. A 401 would read as “the sender is wrong” and hide the real cause.

Two smaller details came from reading the first version again. It used !==, which stops at the first wrong character and returns early on different lengths, so a patient caller can measure how much of the secret they have right. The fix hashes both sides with SHA-256 and compares the digests without early exit:

async function sameSecret(a: string, b: string): Promise<boolean> {
  const enc = new TextEncoder();
  const [ha, hb] = await Promise.all([
    crypto.subtle.digest("SHA-256", enc.encode(a)),
    crypto.subtle.digest("SHA-256", enc.encode(b)),
  ]);
  const x = new Uint8Array(ha);
  const y = new Uint8Array(hb);
  let diff = 0;
  for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
  return diff === 0;
}

The old 401 response also echoed the first five characters of the expected secret and its length, meant as a debugging aid. It is gone. When the secret does not match, you read the function log, not the response body.

Write the event down before you do anything with it

The table that holds subscription state is keyed by user, so each new event overwrites the previous one. That is fine for answering “is this user Pro right now?” and useless for “how many people renewed last month, and why did cancellations spike?” Those questions need history.

So the handler’s first real action, before any branching, is to append the raw event to a separate subscription_events table with the event id as a unique key:

await db.from("subscription_events").upsert(
  { event_id: ev.id, type: ev.type, rc_app_user_id: ev.app_user_id, payload: body },
  { onConflict: "event_id", ignoreDuplicates: true },
);

Retries from RevenueCat then collapse into one row. The write happens even when the event cannot be mapped to a user. An event for an anonymous RevenueCat id is still a real purchase, and keeping it means you can reconcile against RevenueCat later. Dropping it means the money is in the store and nowhere in your database.

TRANSFER has no app_user_id

Most events carry app_user_id, and the natural first line of a handler is “find the user for this id”. TRANSFER events do not carry one. They carry transferred_from and transferred_to. A handler that resolves the user first and branches afterwards never reaches its transfer code, because the lookup comes back empty and the event is skipped as “no user”.

The fix is ordering. Branch on the type first, then reconcile both sides against RevenueCat’s current state:

if (type === "TRANSFER") {
  for (const uid of uuidsFrom(ev.transferred_from)) {
    const snap = (await snapshotFromRC(uid)) ?? emptySnapshot();
    await writeState(uid, snap, type, body);
  }
  for (const uid of uuidsFrom(ev.transferred_to)) {
    // If the API call fails, the payload still lists the entitlements.
    const snap = (await snapshotFromRC(uid)) ?? snapshotFromEvent(ev);
    await writeState(uid, snap, type, body);
  }
  return json({ ok: true, type });
}

Two choices in there matter. The losing side falls back to an empty snapshot, because if you cannot verify, the safe answer for the account that lost the plan is “nothing”. The receiving side falls back to the event payload, because skipping it would leave a user who just received a plan with no row at all. The asymmetry is on purpose.

Whether TRANSFER appears at all depends on the restore behaviour set in the RevenueCat dashboard, which is its own decision and has its own note in this series on binding a subscription to one account.

Refunds must not wait for the expiry date

When the fallback path builds state from the event payload (RevenueCat’s API was unreachable), a plan’s end is normally taken from expiration_at_ms. For a refund that is wrong. A CANCELLATION event whose cancel_reason is CUSTOMER_SUPPORT means the store refunded the current period, so access should end now. An ordinary cancellation, where the user turned off auto-renew, keeps access until the paid period ends.

const refunded = type === "CANCELLATION" && ev.cancel_reason === "CUSTOMER_SUPPORT";
const revoking = type === "EXPIRATION" || type === "SUBSCRIPTION_PAUSED" || refunded;
const isActive = !revoking && (expMs == null || expMs > Date.now());

Without the refunded branch, the happy path was right (the API said “no entitlement”) but the fallback kept a refunded user on Pro until the period they had been refunded for would have ended. It only showed up when the API call failed, which is exactly the situation nobody tests.

The status code that decides whether a paying user gets paid

Consumable packs, such as bundles of in-app currency, arrive as NON_RENEWING_PURCHASE. The handler maps the store product to an amount from a config table and calls a Postgres function, keyed by the store transaction id so a replay cannot add the amount twice.

That function does not raise an exception when it refuses. It returns { ok: false, reason }, with reasons such as no_product, no_amount and no_user. The first version of the handler checked only the RPC’s error field. A refusal is not an error in that sense, so the handler fell through to return json({ ok: true }). RevenueCat saw a 200, marked the event delivered and stopped retrying. The user had paid real money and received nothing, and no alert fired.

It happened once. App Store events carry the store product id in product_id. The code that maps a product to its store id called RevenueCat’s v2 products endpoint, which expects RevenueCat’s own product id and not the store id. It got nothing back and passed a null product to the RPC. The RPC answered no_product, the handler answered 200, and the pack was never added. The mapping now falls back to the product id carried in the event, and the handler reads the result:

const { data, error } = await db.rpc("grant_gem_pack", {
  p_user: userId, p_product: storeProductId, p_txn: transactionId,
});
if (error) return json({ ok: false, error: error.message }, 500);
if ((data as { ok?: boolean } | null)?.ok !== true) {
  console.error("gem pack not granted", { userId, storeProductId, transactionId });
  return json({ ok: false, reason: (data as any)?.reason ?? "unknown" }, 500);
}

A 500 here keeps the event in RevenueCat’s failed list and keeps retrying. Once someone fixes the config, the next retry grants the pack. That is safe to repeat only because the function is idempotent on the transaction id; the two decisions depend on each other. A refund of a pack (CANCELLATION) goes through a matching revoke_gem_pack function with the same property, so a retried refund cannot subtract twice.

Sandbox purchases still grant, on purpose

The handler does not filter out sandbox events. App Review testers buy with sandbox accounts, and if the purchase does nothing they reject the build. The cost is known: anyone with a public TestFlight link can buy with a sandbox account and receive currency on production. The comment in the code names this and says that if it needs closing, the right tool is an allow-list of tester user ids, not a ban on the whole environment. The comment records the decision (7 October 2026): review risk outweighed a small, bounded exposure. I would not copy that choice into an app with real-money payouts.

How it was checked

Each rule above has a repeatable check:

  1. With the secret unset, curl -X POST the function with any body. Expected: HTTP 500 misconfigured. With it set and a wrong value: 401 with no hint in the body.
  2. Send the same event id twice. Expected: one row in subscription_events.
  3. Replay a TRANSFER payload that has no app_user_id. Expected: rows written for both the old and the new user.
  4. Call the pack RPC with a product that has no config row. Expected: the handler returns 500, not 200.

These are the checks I would run against a staging function. I have not re-run them while writing this note; the behaviour described comes from reading the current handler code and the comments in it. The GirlX app has a separate webhook handler that I did not use as a source here, so nothing in this note should be read as describing it.

The pattern across all of it: a webhook consumer is a place where “nothing happened” and “something failed” look alike unless you choose the status code carefully, and where the only record of a purchase may be the event you almost did not store.