---
name: integrate-billstack-referrals
description: "v2 (provider-neutral). Add a referral program with referrer credits to an application that keeps its own Stripe account, Checkout sessions and subscriptions (bring your own billing, external mode) using BillStack at billing.w3dev.app: configure the program, register customers, capture and attribute share links, resolve the referee discount at checkout, receive signed outbound webhooks, show referrers their credits, and operate approvals and payouts."
---

# Integrate BillStack referrals (bring your own billing)

**Generation: v2** (provider-neutral, `/api/billstack/v2/...`, `BillStackV2Client`). This skill covers v2 only. If the project uses BillStack checkout with the legacy by-external-id referral routes (`/api/billstack/teams/.../referrals/...`), load [legacy-billstack-referrals](https://billing.w3dev.app/.well-known/agent-skills/legacy-billstack-referrals/SKILL.md) instead.

Use this skill when your product keeps its **own** Stripe account, creates its own Checkout Sessions and owns its subscriptions, and you want BillStack to run only the referral program and the referrer credit ledger. BillStack never creates your checkout sessions or subscriptions and never owns your entitlements in this mode.

Do not use it when BillStack should run checkout: load [integrate-billstack](https://billing.w3dev.app/.well-known/agent-skills/integrate-billstack/SKILL.md) instead (the legacy by-external-id referral routes belong to that mode and are documented in [legacy-billstack-referrals](https://billing.w3dev.app/.well-known/agent-skills/legacy-billstack-referrals/SKILL.md)). For approvals, recovery, reports and importing history load [operate-billstack-referrals](https://billing.w3dev.app/.well-known/agent-skills/operate-billstack-referrals/SKILL.md). Human-readable guide: https://docs.billing.w3dev.app/integration/referrals-external-billing

These instructions describe the source contracts. A deployment still needs the referral migration applied, background jobs registered and working signed Stripe webhook delivery. Reading this skill does not prove any of that.

## How it works

1. The referrer shares a link or code. The referee lands on **your** page with `?ref=CODE`.
2. Your page remembers the code in a first-party cookie.
3. At signup your server tells BillStack who referred whom (an attribution).
4. At checkout your server asks BillStack to resolve the discount and passes the returned Stripe promotion code to **your** Checkout Session.
5. When the referee's first paid invoice arrives in your Stripe account, BillStack sees `invoice.paid` through its own webhook endpoint, converts the referral and creates a pending credit for the referrer.
6. After a hold period the credit is approved (automatically or by a person) and paid as a Stripe customer-balance credit on the referrer's customer in your account. Refunds, credit notes and disputes reverse it.
7. BillStack calls your server with signed webhooks at every step.

## Prerequisites

1. A BillStack team and project, and a private server key (`bs_test_` for test, `bs_live_` for live) from the project's Settings > Keys page. Keep it on a trusted backend. A new key is an app-runtime key and already includes `referral:*`. Publishable `pk_` keys are refused everywhere below except the public code check. An older "Full access (legacy)" key without IAM attachments is admin-equivalent; operators may restrict it.
2. Connect the team's Stripe account in the team's Stripe integration settings. A restricted key is recommended. Grant: Coupons write, Promotion codes write, Customers write (customer balance transactions), Invoices read, Charges read, Disputes read, Credit notes read, Webhook endpoints write, plus read on whatever the Stripe mirror sync already needs. Confirm the permissions of a restricted key in the Stripe Dashboard: BillStack cannot see every write permission.
3. BillStack registers its own webhook endpoint in your Stripe account, separate from yours. After a BillStack release adds event types, an operator refreshes the subscribed events (`bun run stripe:refresh-webhook-events` in the BillStack repo). Needed events include `invoice.paid`, `charge.refunded`, `charge.dispute.created`, `charge.dispute.closed`, `credit_note.created`, `promotion_code.updated`, `coupon.deleted`, `customer.deleted`.
4. Do not enable external mode on a project that is also connected to Razorpay. Referral external mode is Stripe-only.
5. Start in the test environment. A test key only sees test data; use your Stripe test-mode account.

All v2 routes below use the prefix `P = https://billing.w3dev.app/api/billstack/v2/teams/{teamId}/projects/{projectId}`, `Authorization: Bearer <private-key>` and JSON. Success is `{ "data": ..., "meta": { "requestId" } }`; errors are `{ "error": { "code", "message" }, "meta" }`. URL-encode `externalId` and codes in paths. Log request IDs, not keys or customer bodies.

```ts
const prefix = `https://billing.w3dev.app/api/billstack/v2/teams/${teamId}/projects/${projectId}`;
const response = await fetch(`${prefix}/referrals/program`, {
  headers: { Authorization: `Bearer ${process.env.BILLSTACK_API_KEY}` },
  cache: "no-store",
});
const { data, error, meta } = await response.json(); // error is set when !response.ok
```

The HTTP routes below need no SDK. The SDK covers most of them: it needs `@billstack/sdk` 0.7.0 or later from the registry `https://npm.w3api.dev` (`@billstack:registry=https://npm.w3api.dev` in `.npmrc`; it is not on the default npm registry). Versions 0.3.0 and earlier contain none of the SDK imports in this skill (`BillStackV2Client`, `@billstack/sdk/browser`, `webhooks`, `createReferralEmbedUrl`), so check with `npm view @billstack/sdk versions --registry https://npm.w3api.dev` and use HTTP if 0.7.0 is not there. With it, `import { BillStackV2Client } from "@billstack/sdk/v2"` with `new BillStackV2Client({ baseUrl, apiKey, teamId, projectId })` exposes `client.referrals` and `client.credits`. Use the same client on the server only.

## Step 1: configure the program

`PUT P/referrals/program` merges the keys you send into the stored program and validates the result as a whole (omitted keys keep their value, `null` clears a nullable one). Read it with `GET P/referrals/program`. Needs `referral:UpdateConfig` (`referral:GetConfig` to read).

```json
{
  "enabled": true,
  "billingOwnership": "external",
  "currency": "usd",
  "discountType": "percent",
  "discountValue": 20,
  "discountDuration": "repeating",
  "discountMonths": 3,
  "allowedPriceIds": ["price_..."],
  "allowedIntervals": ["month", "year"],
  "rewardType": "percent_of_paid",
  "rewardPercentBps": 2000,
  "rewardCapAmount": 20000,
  "rewardScope": "first_invoice",
  "rewardBasis": "net_of_tax_after_discount",
  "payoutMethod": "stripe_balance",
  "clawbackMode": "ledger_debit",
  "approvalMode": "manual",
  "holdDays": 14,
  "approvalWindowDays": 60,
  "attributionTtlDays": 60,
  "attributionExpiryDays": 90,
  "shareLandingUrl": "https://app.example.com/signup"
}
```

Settings and valid values:

- `billingOwnership`: `external` for this skill (`billstack` is the legacy mode, see legacy-billstack-referrals). The default for an unconfigured project is `billstack`, so always send `external` explicitly. Only switch to `external` after your customers are registered (step 2).
- Referee discount: `discountType` `percent` (1-100) or `fixed_amount` (minor units in `currency`); `discountDuration` `once`, `repeating` (needs `discountMonths` 1-36) or `forever`; set all of type, value and duration or none. `percent` and `fixed_amount` discounts are created as one Stripe coupon per program and one promotion code per referral code, by BillStack.
- Plan limits: `allowedPriceIds` (`price_...`), `allowedProductIds` (`prod_...`), `allowedIntervals` (`day`, `week`, `month`, `year`); `null` means unrestricted. A referral code may narrow these per code.
- Reward: `rewardType` is `percent_of_paid` (needs `rewardPercentBps` 1-10000, optional `rewardCapAmount` per invoice), `fixed` (needs `rewardFixedAmount`, paid once per referral) or `host_fulfilled` (amount 0; you grant the benefit yourself, months come from `rewardMonths`). `bonus_months` is rejected in external mode. `rewardScope` is `first_invoice`, `recurring_n` (needs `rewardInvoiceLimit`) or `recurring_forever`. `rewardBasis` is `net_of_tax_after_discount` (invoice total without tax, never above cash collected) or `amount_paid`.
- Payout and risk: `payoutMethod` `stripe_balance` (credit the referrer's Stripe customer balance) or `ledger_only` (record only; export for manual payout). `clawbackMode` `ledger_debit` (offset against the referrer's future credits) or `stripe_balance` (debit their Stripe balance). `approvalMode` `manual` (default) or `auto` (after `holdDays`, except credits held for review).
- Timing: `holdDays` (default 14), `approvalWindowDays` (default 60, then pending credits expire), `attributionTtlDays` (default 60, the browser cookie lifetime), `attributionExpiryDays` (default 90, an attributed referee that never pays expires).
- `shareLandingUrl`: an absolute https URL of your signup page. It is also the **only origin allowed to frame the referrer embed** (step 7). `selfReferralFreeMailDomains` replaces the default free-mail list for the same-domain self-referral flag.
- `stripeCouponId` is read-only; BillStack's sync owns it. Saving a changed discount marks every active code for re-sync; the response reports `codesMarkedForSync`. Never create the coupon or promotion codes yourself.

`enabled` must be `true` before the first code can be created: both code routes (`POST P/referrals/codes/self` and `POST P/referrals/codes`) answer `409 PROGRAM_DISABLED` for a disabled program, and a disabled program has no live promotion codes. Enabling first is safe, because with no attributions there is nothing to convert, credit or pay. Keep `"enabled": false` only while you import existing history (step 9), then enable it. After enabling, create the first code (step 3) and wait for it to sync.

## Step 2: register customers

BillStack identifies referrers and referees as project customers by your `externalId`, with their Stripe customer in **your** account:

```bash
curl -X PUT "$P/customers/org_123" -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{ "email": "owner@example.com", "name": "Example Org", "stripeCustomerId": "cus_..." }'
```

Returns `201` (`created: true`) or `200` with `{ customer, created }`. It never calls Stripe. Errors: `409 STRIPE_CUSTOMER_CONFLICT` (that Stripe customer belongs to another `externalId`), `409 EXTERNAL_ID_CONFLICT` (this `externalId` already has a different Stripe customer), `400` for a malformed `cus_` id. Needs `customer:UpdateCustomer`. Call it whenever you create a Stripe customer, and backfill existing customers before you start capturing and attributing referrals. Do not use the legacy find-or-create endpoint in external mode: it creates Stripe customers.

A referee may be registered at signup without a Stripe customer (attribution creates the row); `PUT customers/{externalId}` adds the Stripe customer later on the same row.

Webhook events are matched to customers by `stripeCustomerId`. If one Stripe customer exists in two projects of the same team, BillStack routes the event by the program's `allowedPriceIds` or `allowedProductIds`; an event it still cannot place is skipped (see troubleshooting).

## Step 3: share links and capture

Referrers get a code with `POST P/referrals/codes/self` body `{ "externalId": "org_123" }` (or the SDK's `client.referrals.codes.getOrCreateSelf("org_123")`). The customer must exist and hold a subscription whose status is in `eligibleSubscriptionStatuses`; otherwise `422 CUSTOMER_NOT_ELIGIBLE`. A program that is not enabled is `409 PROGRAM_DISABLED`. A customer who already has a code gets it back. Admin and partner codes: `POST P/referrals/codes` with exactly one owner, `externalId` or `partner: { email, name }`, and optional `code` (4-20 letters or digits, stored uppercase; `SELF` is reserved), `maxRedemptions`, a future `expiresAt`, `allowedPriceIds`, `allowedIntervals`, `externalRef`.

Share link forms:

- Hosted: `https://billing.w3dev.app/r/{teamSlug}/{projectSlug}/{CODE}`. It validates the code and answers `302` to your `shareLandingUrl` with `?ref=CODE` (other landing query parameters are kept). An invalid code, an unknown team or project, or a program with no landing URL are the same bare `404`. It works for the **live** environment only; in test, link to your own landing page with `?ref=CODE`.
- Direct: your own `https://app.example.com/signup?ref=CODE`.

Code state: after create or change, `syncState` is `pending`, then `synced` once BillStack has created the Stripe promotion code; `error` carries `syncError`; `disabled` means not live. A code is only usable at checkout when `synced`. `POST P/referrals/stripe-sync` (needs `referral:UpdateConfig`) re-queues every code and answers `202 { codesMarkedForSync, enqueued }`.

Capture on your landing page with the browser entry (no dependencies, safe in server rendering):

```ts
import { captureReferral, getReferral, clearReferral } from "@billstack/sdk/browser";

captureReferral({ ttlDays: 60 }); // reads only ?ref= and writes the first-party bs_ref cookie
const referral = getReferral(); // { code, capturedAt } or null
```

- It reads only the configured query parameter (`param`, default `ref`) and an optional `pathPattern`; it **never reads `utm_*`**. Do not map UTM parameters to codes.
- Set `ttlDays` to the program's `attributionTtlDays` (`GET P/referrals/codes/{code}/public` with a publishable key returns it with the discount to show on your page; it needs a client built with a `pk_` key and returns `404` for a code that is not usable).
- First touch wins: a still-valid cookie is kept. Pass `domain: "example.com"` to share the cookie with subdomains.
- Codes are 4-20 letters or digits; anything else is ignored.

## Step 4: attribution at signup

After the referee has an account, from your **server**:

```ts
const result = await client.referrals.attribute({
  code: referral.code, // sent from the browser with the signup request
  referee: { externalId: org.id, email: org.email, stripeCustomerId: org.stripeCustomerId },
  source: "link", // "code" when the user typed it
});
```

HTTP: `POST P/referrals/attributions` with `{ code, referee: { externalId, email, stripeCustomerId? }, source? }` (`referral:ApplyCode`). `201` when a row was written, `200` otherwise.

- A rejected code is **HTTP 200 `{ ok: false, reason }`**, not an error. Branch on `ok`. Reasons: `disabled`, `not_found`, `inactive`, `expired`, `max_uses`, `plan_not_allowed`, `period_not_allowed`, `self_referral`, `not_first_time`, `not_synced`. Never block signup on a rejection; just continue without a referral.
- On `ok: true` you get `attribution`, `created` and `alreadyAttributed`. It is idempotent and first touch wins: attributing the same referee to a different code returns the original attribution with `alreadyAttributed: true`. An expired attribution may be replaced by a new code.
- Self-referral: same customer, `externalId` or Stripe customer is blocked (`self_referral`). A shared email domain outside the free-mail list, an identical email, or the same card fingerprint **flags** the credit for manual review (`flaggedReason`; the credit is created with `reviewRequired: true`).
- Clear the cookie after a successful attribution: `clearReferral()` in the browser, once your server answered.
- `GET P/referrals/attributions?refereeExternalId=org_123` returns `{ items }` (empty when none).

Skipping this step is safe: checkout resolution records the attribution too when the referee has none.

## Step 5: checkout

If BillStack runs your checkout through the v2 routed checkout (see integrate-billstack), skip this step's manual call: send `referral: { code }` (or `referral: {}` for the customer's existing attribution) on the v2 checkout request and BillStack resolves the discount on the price being sold, applies it and records the attribution. It needs the customer's email on record and `referral:ApplyCode` on the key, is available in Stripe regions only, and a rejected referral answers `422 REFERRAL_REJECTED` with the reason in `fieldErrors`. Use the two-step flow below when **you** create the Checkout Session.

Before creating **your** Checkout Session, from your server:

```ts
const resolved = await client.referrals.resolveForCheckout({
  referee: { externalId: org.id, email: org.email, stripeCustomerId: org.stripeCustomerId },
  code: referral?.code, // omit to use the referee's existing attribution
  priceId: "price_...",
  interval: "month", // day, week, month or year: the billing period of that price
});
const discounts = resolved.data.ok ? [{ promotion_code: resolved.data.promotionCodeId }] : [];
const session = await stripe.checkout.sessions.create({
  customer: org.stripeCustomerId,
  mode: "subscription",
  line_items: [{ price: "price_...", quantity: 1 }],
  ...(discounts.length ? { discounts } : { allow_promotion_codes: false }),
  success_url, cancel_url,
});
```

HTTP: `POST P/referrals/checkout-resolution` with `{ code?, referee, priceId, interval }`. It answers `200` with `{ ok: true, promotionCodeId, couponId, referralId, code, discount, alreadyAttributed }` or `{ ok: false, reason }` (same reasons as above). Authorization is the secret key; call it server-side only and never expose it to the browser. The response is never cacheable.

Rules:

- Pass `discounts: [{ promotion_code: promotionCodeId }]` and **never set `allow_promotion_codes` together with it**: Stripe rejects both, and the referee must not swap codes. Use `allow_promotion_codes: false` or omit it.
- A live attribution decides the code (first touch): presenting code B after code A resolves to A.
- The referee must be a first-time customer: any earlier paid invoice (amount above zero) is `not_first_time`. A $0 trial invoice does not count.
- `priceId` must be in the effective `allowedPriceIds` and `interval` in `allowedIntervals` when set; otherwise `plan_not_allowed` or `period_not_allowed`.
- Resolution registers the referee in BillStack when a code or Stripe customer is presented, and records an attribution if there is none.
- **Trials:** keep `discountDuration = repeating` with `discountMonths` long enough to cover the first paid invoice (trial length in months plus the months you want discounted). With `once`, Stripe spends the discount on the $0 trial invoice and the referee gets nothing. A $0 trial invoice neither converts the referral nor creates a credit; the first invoice with `amount_paid > 0` does.
- Create the Stripe customer first (step 2) so the referee's invoice is matched to the referral.

## Step 6: outbound webhooks

Create an endpoint (needs `billing:UpdateBilling`):

```ts
const { data } = await client.webhookEndpoints.create({
  url: "https://app.example.com/api/billstack-webhooks",
  enabledEvents: ["referral.converted", "referral.reward_applied", "referral.reward_reversed", "referral.reward_failed"], // or ["*"]
});
// data.secret (whsec_...) is shown once: store it in your secret manager.
```

HTTP: `POST P/webhook-endpoints` with `{ url, description?, enabledEvents? }` (default `["*"]`; an empty list is rejected). The URL must be `https` (test endpoints may use `http`), must not point to private or internal addresses, and redirects are not followed. `POST P/webhook-endpoints/{id}/test` sends a `webhook.test` event. `POST .../rotate-secret` issues a new secret and invalidates the old one at once.

Verify every request against the **raw body**:

```ts
import { webhooks } from "@billstack/sdk";

export async function POST(request: Request) {
  const payload = await request.text();
  let event;
  try {
    event = await webhooks.constructEvent(payload, request.headers.get("BillStack-Signature") ?? "", process.env.BILLSTACK_WEBHOOK_SECRET!);
  } catch {
    return new Response("invalid signature", { status: 400 });
  }
  if (await alreadyProcessed(event.id)) return new Response("ok");
  await handle(event); // then record event.id
  return new Response("ok");
}
```

- Header `BillStack-Signature: t=<unix>,v1=<hex>`, an HMAC-SHA256 of `"<t>.<raw body>"` with the endpoint secret. The default tolerance is 300 seconds. Also sent: `BillStack-Event-Id`, `BillStack-Event-Type`.
- Envelope: `{ id, type, created, projectId, environment, apiVersion, data }`.
- Return any `2xx` within 10 seconds. Failed deliveries are retried for about 68 hours (nine attempts), then marked `failed`; replay with `POST P/webhook-deliveries/{id}/replay`.
- Delivery is at least once and unordered: **dedupe on `event.id`**, and make handlers idempotent and order-tolerant.

Event catalogue (the live list is `GET P/webhook-event-types`):

| Event | `data` | What to do |
| --- | --- | --- |
| `referral.code_created`, `referral.code_updated` | `code`, `changed?` | Optional: refresh a cached share link or code state. |
| `referral.attributed` | `referral` | Optional: show "invited" in your UI. |
| `referral.converted` | `referral`, `invoiceId` | The referee made a first qualifying payment. Optional: notify the referrer. |
| `referral.expired` | `referral` | The referee never paid in time. Nothing to reverse. |
| `referral.reward_pending` | `credit` (and `hostFulfilled` for host-fulfilled rewards) | Reward is waiting for approval. Optional: show "pending". |
| `referral.reward_approved` | `credit` | Approved; the payout runs in the background. |
| `referral.reward_applied` | `credit`; `hostFulfilled: { type: "bonus_months", months }` for host-fulfilled rewards; `payout: { gross, offset, net }` when debits were offset | Paid. If `hostFulfilled` is present, **grant the benefit yourself** (for example add the months to the referrer's subscription) and do it idempotently by event id; BillStack wrote no Stripe balance credit. Otherwise the money is already on the referrer's Stripe balance. |
| `referral.reward_rejected`, `referral.reward_expired` | `credit` | No reward. If you granted anything early, take it back. |
| `referral.reward_reversed` | `credit`, `reversal { originalId, reversalId, amount, currency, reason, objectId, mode, full }` | Refund, credit note or dispute reduced or reversed the reward. For host-fulfilled rewards you must revoke the benefit yourself. |
| `referral.reward_failed` | `credit` | The payout failed repeatedly. Alert an operator; see recovery below. |
| `credit.created`, `credit.approved`, `credit.rejected`, `credit.expired`, `credit.applied`, `credit.reversed`, `credit.failed` | `credit` | The same lifecycle for manual, goodwill and reversal entries. |
| `webhook.test` | none | Connectivity check only. |

Endpoints on payload version `2026-10-26` or later also receive `entitlement.updated`, `subscription.*` and `purchase.*` events (see the [sync-billstack-entitlements skill](https://billing.w3dev.app/.well-known/agent-skills/sync-billstack-entitlements/SKILL.md)); an endpoint that only cares about referrals can list the referral, credit and payout types instead of `*`.

## Step 7: the referrer's view

Show referrers their code, link, referrals and credits. Server-side:

```ts
const { data } = await client.referrals.getReferrer("org_123"); // GET P/referrals/referrers/{externalId}
```

It returns `{ program, code, referrals, credits }`: referees are masked (`j***@example.com`), credits are grouped as earned (applied only), pending and not earned, with per-currency totals and an outstanding debit line when a clawback is owed. Admin free-text reasons and internal errors are never included. A customer of another project is `404 CUSTOMER_NOT_FOUND`.

Or embed the hosted page in an iframe. Mint the URL on your server with your secret key at each page render (the SDK default lifetime is one hour, the maximum seven days), never in the browser:

```ts
import { createReferralEmbedUrl } from "@billstack/sdk";

const { url } = await createReferralEmbedUrl({ baseUrl: "https://billing.w3dev.app", apiKey, teamId, projectId }, { externalId: "org_123" });
// <iframe src={url} />
```

- Pass exactly one of `customerId` or `externalId`. The URL is `https://billing.w3dev.app/embed/referrals/{token}`.
- BillStack allows framing only by the **origin of `shareLandingUrl`** (`Content-Security-Policy: frame-ancestors <that origin>`); anything else, or no landing URL, denies framing. Your host page must therefore be served from the same origin as `shareLandingUrl`. There is no allowlist of several origins.
- The page posts `{ type: "billstack:resize", height }` to the parent with `targetOrigin` set to that origin. In your host page check `event.origin === "https://billing.w3dev.app"` and the type before resizing the iframe.
- The partner portal and the embed URL above are the hosted referral surfaces in this mode; subscriptions, invoices and cards stay in your own billing. A legacy BillStack-hosted portal session (see [legacy-billstack-integration](https://billing.w3dev.app/.well-known/agent-skills/legacy-billstack-integration/SKILL.md)) shows the referrals view only for an external project.

### Optional: partner portal and payout requests

For partner codes or `ledger_only` programs where you pay referrers yourself, turn on the hosted partner portal: `PUT P/referrals/program` with `{ "partnerPortalEnabled": true, "minPayoutAmount": 5000 }` (minor units, `null` for no minimum). BillStack moves no money (no Stripe Connect): a referrer requests a payout, you approve it, pay them yourself and mark it paid with your reference. Human guide: https://docs.billing.w3dev.app/integration/partner-portal

- The portal is `https://billing.w3dev.app/partners/{teamSlug}/{projectSlug}` and serves the **live** environment only. Link partners to it; they sign in with an emailed magic link (15 minutes, single use, 7-day session).
- For a signed-in customer referrer, skip the email: `POST P/referrals/partner-portal/sessions` with `{ "customerExternalId": "org_123" }` (IAM `referral:CreatePartnerSession`, live key) returns `201 { data: { url, expiresAt } }`. The URL is single use and valid 15 minutes; mint it on click, redirect to it, never log or store it. SDK: `client.partnerPortal.createSession("org_123")`. Errors: `404 CUSTOMER_NOT_FOUND`, `404 PORTAL_DISABLED`, `409 LIVE_ONLY`.
- Until a referrer has `earned > 0` the portal shows a locked screen with no amounts.
- New webhook events: `payout.requested`, `payout.approved`, `payout.rejected`, `payout.paid`, `payout.cancelled`, `payout.credit_reversed` (payload `{ payout }`). Subscribe to `payout.requested` to start your payment run.

## Step 8: admin operations (summary)

Approvals, recovery, reports and imports are in [operate-billstack-referrals](https://billing.w3dev.app/.well-known/agent-skills/operate-billstack-referrals/SKILL.md). In short: the dashboard has Referrals pages (overview, approvals, codes, settings, webhooks); `GET P/referrals/credits`, `POST P/referrals/credits/{id}/approve|reject|retry|mark-applied`, `GET P/referrals/reports/summary`; and authenticated MCP tools at `https://billing.w3dev.app/mcp` (`get_referral_summary`, `list_pending_referral_credits`, `approve_referral_credit`, `reject_referral_credit`, `create_referral_code`, `get_referrer_view`).

## Step 9: migrating an existing referral system

If you already run codes, Stripe promotion codes, referrals and credits, do not recreate them. Use the importer, which adopts your existing Stripe coupon, promotion codes and balance transactions without changing Stripe: https://docs.billing.w3dev.app/migration/referrals-import. Order: register the program in external mode and leave it **disabled**, dry run, apply, verify, enable the program, then `POST P/referrals/stripe-sync`. Importing `approved` credits into an enabled program makes BillStack pay them again, so import disabled.

## Step 10: test before live

1. Use a `bs_test_` key and your Stripe test-mode account. The hosted `/r/...` link does not resolve in test; send test traffic to your landing page with `?ref=CODE`.
2. Create a program (`enabled: true`), a self code for a registered test customer with a subscription in an eligible status, and wait for `syncState: "synced"` (`GET P/referrals/codes/{code}`).
3. As a new referee: capture, attribute, `resolveForCheckout`, pay a test Checkout Session with the promotion code, and confirm the discount.
4. Confirm `referral.converted`, then `referral.reward_pending` at your endpoint (verified and deduplicated). Approve it (`manual` mode) or wait out `holdDays`, then confirm `referral.reward_applied` and a customer balance credit on the referrer in Stripe.
5. Refund the invoice in test mode and confirm `referral.reward_reversed` (or `referral.reward_rejected` if the reward was not paid yet).
6. Repeat the same checks with a live key only after test passes. Do not use live payments as a substitute for test coverage.

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| `{ ok: false, reason: "not_synced" }` | The Stripe promotion code does not exist yet or the program has no discount. Check `syncState`/`syncError` on the code; fix the Stripe key permissions (Coupons and Promotion codes write) and `POST P/referrals/stripe-sync`. Do not create the promotion code by hand. |
| `period_not_allowed` / `plan_not_allowed` | The checkout `interval` or `priceId` is outside `allowedIntervals` / `allowedPriceIds` (program or code override). Fix the program or do not offer the discount for that plan. |
| `not_first_time` | The referee already has a paid invoice, or its attribution is already converted. Expected; check out without a discount. |
| `self_referral` | Same customer, `externalId` or Stripe customer. Expected. |
| Referral converts but no credit, or no reward appears | The invoice was `$0`, or its price or interval is not allowed, or the reward scope is used up. These are skipped and logged, not errors. Check `allowedPriceIds`/`allowedIntervals`, `rewardScope` and the invoice amount. |
| Webhook events seem ignored for a customer (`ambiguous_customer`) | The same Stripe customer id exists in two projects of one team and no `allowedPriceIds`/`allowedProductIds` identify the project. The event is skipped (a warning is logged) and the webhook is still marked processed. Fix the routing lists or register the Stripe customer in one project only. Events skipped before the fix are not replayed automatically. |
| Credit stuck as `pending` with `reviewRequired: true` | Held for review (self-referral flag such as `same_email_domain`, `same_email`, `same_card`). A human approves or rejects it. Auto mode never approves a held credit. |
| Credit `failed` (`referral.reward_failed`) | The Stripe balance credit failed after five attempts (missing Customers write permission, deleted Stripe customer, no `stripeCustomerId` on the referrer). Fix the cause, then `POST P/referrals/credits/{id}/retry` (fresh attempts), or pay it yourself and `POST .../mark-applied` with the `cbtxn_...` id. |
| Pending credit disappeared as `expired` | It was not approved within `approvalWindowDays`. A manual credit (`POST P/referrals/credits/manual`) can give it back. |
| `409 CREDIT_STATE_CONFLICT` | The credit already moved (someone else approved it, or it is no longer pending). Re-read it. |
| Embed iframe is blank | `shareLandingUrl` missing or on a different origin than the page that frames it, or an expired token. Mint a fresh URL per page render. |
| `401`/`403` on a referral route | The key is publishable, belongs to another environment, or lacks the `referral:*` action. Use a private key of the right environment. |
| Signature verification fails | You parsed the body before verifying, used the wrong endpoint secret (rotate-secret invalidates the old one), or your clock is more than 300 seconds off. |

Never log or commit private keys, webhook secrets, portal or embed URLs, or customer data.
