---
name: operate-billstack-referrals
description: "v2 (provider-neutral). Operate a BillStack referral program for a project that keeps its own Stripe billing: review and approve referrer credits, recover failed payouts, issue manual credits, reconcile Stripe promotion codes, read reports and CSV exports, manage partner codes, and import an existing referral system, using the v2 referral APIs, the dashboard, or authenticated MCP tools."
---

# Operate BillStack referrals

**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 for day-to-day administration of a referral program in external billing mode. To build the integration first, load [integrate-billstack-referrals](https://billing.w3dev.app/.well-known/agent-skills/integrate-billstack-referrals/SKILL.md). Human-readable guide: https://docs.billing.w3dev.app/integration/referrals-external-billing

Prefix `P = https://billing.w3dev.app/api/billstack/v2/teams/{teamId}/projects/{projectId}`. Use a private key (`bs_test_` or `bs_live_`) on a trusted backend, or a signed-in project session. The key's environment decides whether you touch test or live data; sessions pass `?mode=test|live`. Publishable keys never authenticate. Success is `{ data, meta }`, errors `{ error: { code, message }, meta }`. IAM actions: `referral:ListCredits`, `referral:ReviewCredit`, `referral:CreateCredit`, `referral:GetReport`, `referral:ListCodes`, `referral:CreateCode`, `referral:UpdateConfig`; `referral:*` covers all.

## Credit lifecycle

Statuses: `pending`, `approved`, `applying`, `applied`, `rejected`, `expired`, `reversed`, `failed`. Kinds: `referral`, `manual`, `goodwill`, `reversal`.

- A referral credit is created `pending` on the referee's first paid invoice (and later ones with `recurring_n` or `recurring_forever`), with `eligibleAt = now + holdDays` and, for referral rewards, `expiresAt = now + approvalWindowDays`.
- `approvalMode: "auto"` approves a pending credit after the hold unless it is held for review (`reviewRequired: true`, with `reviewReason` such as `same_email_domain`, `same_email`, `same_card` or `imported`). Held credits need a human. In `manual` mode every credit needs approval.
- `pending` becomes `approved`, then a background job moves it to `applying` and `applied` by creating a Stripe customer-balance credit on the referrer's customer (`payoutMethod: stripe_balance`). Partner credits (no customer), `ledger_only` programs and amount-0 `host_fulfilled` rewards are marked applied without a Stripe call; partner and ledger-only credits are paid by you from the CSV export.
- A refund, credit note or dispute reverses the reward: unpaid credits are reduced or rejected, applied ones get a `reversal` entry (an outstanding debit offset against the referrer's next payouts, or a Stripe balance debit when `clawbackMode: stripe_balance`). A won dispute does not restore the reward; give it back with a manual credit.
- Every state change is in the credit's history (`GET P/referrals/credits/{id}` returns `transitions` and `reversals`).

## Review and approve

```bash
curl "$P/referrals/credits?status=pending&limit=50" -H "Authorization: Bearer $KEY"
curl -X POST "$P/referrals/credits/{id}/approve" -H "Authorization: Bearer $KEY"
curl -X POST "$P/referrals/credits/{id}/reject" -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{ "reason": "duplicate account" }'
```

- List filters: `status`, `kind`, `customerExternalId`, `limit` (max 200), `cursor` (pass `nextCursor` back). Newest first.
- Approve moves `pending` only and also overrides a review hold, so read `reviewReason` first. Reject takes a required `reason` (1-500 characters), moves `pending`, `approved` or `failed`, and is final; the reason is never shown to the referrer.
- `POST P/referrals/credits/bulk` with `{ ids: [...up to 100], action: "approve" | "reject", reason? }` returns one result per id; a failing id does not fail the call. Reject needs a reason.
- `409 CREDIT_STATE_CONFLICT` means the credit already moved: re-read it. `404 CREDIT_NOT_FOUND` also covers another project's id.
- The same actions exist in the dashboard (Referrals > Approvals) and as MCP tools at `https://billing.w3dev.app/mcp`: `list_pending_referral_credits`, `approve_referral_credit`, `reject_referral_credit` (reason required). MCP callers need the matching `referral:` IAM actions and the `mcp:read` or `mcp:write` OAuth scope.

## Recover from failures

- **`failed` credit** (the payout failed five times): fix the cause (Stripe key lacks Customers write, referrer has no `stripeCustomerId`, Stripe customer deleted), then `POST P/referrals/credits/{id}/retry` (failed to approved with a fresh attempt budget; returns `{ credit, enqueued }`; `enqueued: false` means the 15-minute job will pick it up; `409` when it is not failed). Or reject it.
- **Paid outside BillStack:** `POST P/referrals/credits/{id}/mark-applied` with `{ "stripeBalanceTransactionId": "cbtxn_..." }` for a `failed`, `approved` or `applying` credit. BillStack retrieves the transaction on the referrer's Stripe customer and requires the amount to equal `-credit.amount` in the same currency, no tag for another credit, and no other credit already recording it (`422 BALANCE_TRANSACTION_NOT_FOUND`, `BALANCE_TRANSACTION_MISMATCH`, `CREDIT_NOT_PAYABLE`).
- **Stuck `applying`:** nothing to do. A lease expires after 10 minutes and a 15-minute job adopts an existing Stripe credit or returns the credit to `approved`. Do not pay it by hand without checking the referrer's Stripe balance transactions for a `billstack_credit_id` tag first.
- **Reversal waiting on a payout:** a refund event for a credit in `applying` is retried by BillStack's own sweep after the payout settles.
- **Promotion code problems:** `GET P/referrals/codes/{code}` shows `syncState` (`pending`, `synced`, `error`, `disabled`) and `syncError`. `POST P/referrals/stripe-sync` re-queues every code and answers `202 { codesMarkedForSync, enqueued }`. A promotion code switched off in Stripe deactivates the BillStack code; turn it back on with `PATCH P/referrals/codes/{code}` `{ "isActive": true }`.
- **Failed outbound webhook deliveries:** `GET P/webhook-deliveries?status=failed`, then `POST P/webhook-deliveries/{id}/replay` (a `pending` delivery is a 409).
- **Disabling the program** pauses automation (no auto-approval, expiry, lease reclaim or payout enqueue) and deactivates promotion codes; admins can still approve, retry, reject and mark applied by hand.

## Manual and goodwill credits

`POST P/referrals/credits/manual` with `{ customerExternalId, amount, currency, kind: "manual" | "goodwill", reason, idempotencyKey, approve? }`. `amount` is a positive integer in minor units; the customer must be registered. Repeating the same `idempotencyKey` returns the same credit (`201` created, `200` repeat; `409 IDEMPOTENCY_CONFLICT` when the key is reused with different values). Manual credits never expire. With `approve: true` it is paid right away.

## Codes and partners

- `GET P/referrals/codes?owner=&active=&limit=&cursor=`; `GET|PATCH P/referrals/codes/{code}` (`isActive`, `maxRedemptions` not below `redemptionCount`, `expiresAt`, per-code `allowedPriceIds` / `allowedIntervals` that must be subsets of the program's lists, `externalRef`); `POST P/referrals/codes/{code}/deactivate` (idempotent). The code string never changes.
- Create an admin or partner code with `POST P/referrals/codes` (exactly one of `externalId` or `partner: { email, name }`), or the MCP tool `create_referral_code`. Partner credits have no customer, use the `ledger_only` path and appear in the CSV export.
- Errors: `CODE_TAKEN` and `EXTERNAL_REF_CONFLICT` (409), `CUSTOMER_ALREADY_HAS_CODE` (409), `PROGRAM_DISABLED` (409), `CUSTOMER_NOT_FOUND` (404), `CUSTOMER_NOT_ELIGIBLE` (422).

## Payout requests (partner portal)

When the program has `partnerPortalEnabled`, referrers request payouts at `https://billing.w3dev.app/partners/{teamSlug}/{projectSlug}` once they have earned something. A request reserves their payable credits of one currency. **BillStack moves no money**: you pay the referrer yourself, then record it. Human guide: https://docs.billing.w3dev.app/integration/partner-portal. IAM: `referral:ListPayouts` (list, get, export), `referral:ReviewPayout` (approve, reject, mark paid), `referral:CreatePartnerSession` (mint sign-in URLs).

Statuses: `requested`, `approved`, `paid`, `rejected`, `cancelled`. Review order:

```bash
curl "$P/referrals/payouts?status=requested&limit=50" -H "Authorization: Bearer $KEY"
curl "$P/referrals/payouts/{id}" -H "Authorization: Bearer $KEY"          # { request, transitions }
curl -X POST "$P/referrals/payouts/{id}/approve" -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{ "note": "ok" }'
# pay the referrer outside BillStack, then:
curl -X POST "$P/referrals/payouts/{id}/mark-paid" -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{ "externalReference": "wire-2026-10-21-001" }'
curl -X POST "$P/referrals/payouts/{id}/reject" -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{ "note": "Payout details incomplete" }'
```

- Filters: `status`, `currency`, `limit` (max 100), `cursor`. `amount` is integer minor units. `payoutDetails` is what the referrer typed (bank or PayPal details): personal data, keep it out of logs.
- Reject needs a `note` the referrer sees and releases the credits so they can ask again. Mark paid needs `externalReference` (max 255 characters). Approve takes an optional `note`.
- `409 PAYOUT_CREDIT_REVERSED` on approve: a reserved credit was reversed by a refund or dispute; reject the request instead. `409 PAYOUT_INVALID_TRANSITION`: it already moved, re-read it. `404 PAYOUT_NOT_FOUND` also covers another project's id.
- A paid request with `reversedAfterPaid: true` means a credit behind it was reversed after you paid. BillStack does not claw it back; settle it with the referrer in a later payout.
- `GET $P/referrals/payouts/export.csv` is the payment-run export (payout details omitted).
- The dashboard has Referrals > Payouts. MCP tools: `list_payout_requests`, `get_payout_request`, `approve_payout_request`, `reject_payout_request` (note required), `mark_payout_paid` (externalReference required) and `set_partner_portal_settings` (`partnerPortalEnabled`, `minPayoutAmount`). Webhooks: `payout.requested|approved|rejected|paid|cancelled|credit_reversed`.
- SDK: `client.referrals.payouts.{list,get,approve,reject,markPaid}`.

## Reports and exports

- `GET P/referrals/reports/summary` (or MCP `get_referral_summary`): credit counts and amounts per status and currency (minor units, reversals reported separately), `paid`, `clawedBack`, `outstandingDebit` and `net`, referral counts per status, and active/total codes.
- `GET P/referrals/credits/export.csv?status=&kind=&from=&to=` (CRLF CSV, at most 50,000 rows, `from` inclusive, `to` exclusive on creation time). Columns: `id, kind, status, referrer, code, invoice, amount, currency, created_at, approved_at`; `amount` is integer minor units. Use it to pay partner and ledger-only credits manually: once approved, BillStack marks them applied without moving money, so the export is your payout record.
- `GET P/referrals/referrers/{externalId}` (or MCP `get_referrer_view`) shows exactly what one referrer sees, with referees masked.

## Import an existing system

Load your history with the importer: https://docs.billing.w3dev.app/migration/referrals-import. The same plan runs in three modes through `POST P/referrals/import?mode=dry_run|apply|verify` (needs `referral:UpdateConfig`; body up to 5 MB; `skipConflicts=true`, `emitEvents=true`), or the CLI `bun run referrals:import --project-id <id> --environment live --file payload.json --team-id <teamId>` (dry run by default, `--apply`, `--verify`).

Procedure, in this order:

1. Register the program in external mode and keep it **disabled**.
2. Dry run until no error remains; read every warning (`approved_credits_will_be_paid`, `promotion_code_will_rotate`).
3. `apply` (it writes nothing while any error exists), then `verify`.
4. Enable the program, then immediately `POST P/referrals/stripe-sync`.

`approved` credits in an enabled program are paid again, and old payouts carry no BillStack metadata to recognise them, so import with the program disabled. A credit that already carries a balance transaction id must be imported as `applied` or `reversed`.

## Safety rules

- Never approve a credit just to clear a queue: check `reviewReason` and the referral first.
- Pay partner and ledger-only credits only from the export or an approved payout request, and keep the record with the payment. Never mark a payout paid before you have paid it, and never put a payout reference you did not issue.
- Do not edit Stripe coupons or promotion codes BillStack manages; change the program instead.
- Never log or commit private keys, webhook secrets or customer data.
