Referrals
API endpoints for referral programs, codes, attributions, checkout resolution, credits, reports and import.
This page documents the v2 referral routes for projects that keep their own billing (external mode). The original by-external-id routes for projects where BillStack runs checkout and entitlements (billingOwnership: "billstack") are legacy and live in Legacy referrals. Read the integration guide first.
All referral endpoints are project scoped and require a private API key or an authenticated dashboard session with project access.
Referrals with your own billing (v2)
Prefix P = /api/billstack/v2/teams/{teamId}/projects/{projectId}. Authenticate with a private key (bs_test_ or bs_live_) as Authorization: Bearer <private-api-key>, or with a signed-in project session that holds the listed IAM action. Publishable keys are refused except where noted. The environment is the key's own; a session may pass ?mode=test or ?mode=live (the import route uses ?environment=, because mode is its import mode). Responses use the v2 envelope { "data": ..., "meta": { "apiVersion", "requestId" } }; errors are { "error": { "code", "message" }, "meta" }. List routes return data.items and data.nextCursor.
Routes
| Method and path | IAM action | Purpose |
|---|---|---|
GET P/referrals/program | referral:GetConfig | Read the program with day defaults applied. |
PUT P/referrals/program | referral:UpdateConfig | Merge settings and validate the result. Returns program and codesMarkedForSync. |
POST P/referrals/codes/self | referral:CreateCode | Get or create a customer's own code. Body { externalId }. |
GET P/referrals/codes | referral:ListCodes | List codes. Query owner, active, limit (max 200), cursor. |
POST P/referrals/codes | referral:CreateCode | Admin or partner code (exactly one of externalId or partner). 201. |
GET P/referrals/codes/{code} | referral:ListCodes | One code with syncState and syncError. |
PATCH P/referrals/codes/{code} | referral:CreateCode | isActive, maxRedemptions, expiresAt, plan overrides, externalRef. |
POST P/referrals/codes/{code}/deactivate | referral:CreateCode | Idempotent. |
GET P/referrals/codes/{code}/public | publishable key only | Share-page check: discount, project name, attributionTtlDays. 404 for an unusable code. |
POST P/referrals/attributions | referral:ApplyCode | Record who referred a referee. 201 when written, 200 otherwise. |
GET P/referrals/attributions?refereeExternalId= | referral:ListCodes | The referee's attribution (items, empty when none). |
POST P/referrals/checkout-resolution | referral:ApplyCode | Validate a code for a plan and return the promotion code. |
GET P/referrals/referrers/{externalId} | referral:ListCodes and referral:ListCredits | What a referrer sees. |
GET P/referrals/credits | referral:ListCredits | The credit ledger. |
GET P/referrals/credits/{id} | referral:ListCredits | One credit with transitions and reversals. |
POST P/referrals/credits/{id}/approve | referral:ReviewCredit | Approve a pending credit. |
POST P/referrals/credits/{id}/reject | referral:ReviewCredit | Reject with { reason }. |
POST P/referrals/credits/{id}/retry | referral:ReviewCredit | Retry a failed payout. |
POST P/referrals/credits/{id}/mark-applied | referral:ReviewCredit | Record a payout made outside BillStack. |
POST P/referrals/credits/bulk | referral:ReviewCredit | Approve or reject up to 100 credits. |
POST P/referrals/credits/manual | referral:CreateCredit | Manual or goodwill credit. |
GET P/referrals/credits/export.csv | referral:ListCredits | The ledger as CSV. |
GET P/referrals/reports/summary | referral:GetReport | Totals per status and currency. |
POST P/referrals/stripe-sync | referral:UpdateConfig | Re-queue every code for Stripe sync. 202. |
POST P/referrals/import?mode= | referral:UpdateConfig | Import an existing referral system. |
PUT P/customers/{externalId} | customer:UpdateCustomer | Register a customer with its Stripe customer id. |
GET/POST P/webhook-endpoints and related | billing:GetBilling / billing:UpdateBilling | Outbound webhooks. See Outbound webhooks. |
referral:* covers all referral actions. A new secret key (created since 2026-12-01) is an app-runtime key and already includes referral:*; an older full-access key without IAM attachments is admin-equivalent.
Program
PUT P/referrals/program accepts any of: enabled, billingOwnership (external or billstack), currency, eligibleSubscriptionStatuses, discountType (percent, fixed_amount), discountValue, discountDuration (once, repeating, forever), discountMonths, allowedPriceIds, allowedProductIds, allowedIntervals (day, week, month, year), rewardType (percent_of_paid, fixed, host_fulfilled; bonus_months for BillStack checkout), rewardPercentBps, rewardFixedAmount, rewardCapAmount, rewardScope (first_invoice, recurring_n, recurring_forever), rewardInvoiceLimit, rewardBasis (net_of_tax_after_discount, amount_paid), payoutMethod (stripe_balance, ledger_only), clawbackMode (ledger_debit, stripe_balance), approvalMode (manual, auto), holdDays, approvalWindowDays, attributionTtlDays, attributionExpiryDays, shareLandingUrl, selfReferralFreeMailDomains, rewardMonths, refundWindowDays, partnerPortalEnabled, minPayoutAmount (minor units or null). stripeCouponId is read-only. Validation errors are 400 INVALID_REQUEST with fieldErrors. The meaning of each setting is in the integration guide.
Codes
Create body (POST P/referrals/codes):
{
"partner": { "email": "partner@example.com", "name": "Example Partner" },
"code": "PARTNER1",
"maxRedemptions": 100,
"expiresAt": "2027-01-01T00:00:00.000Z",
"allowedPriceIds": ["price_..."],
"allowedIntervals": ["month"],
"externalRef": "partner-1"
}A code record carries ownerType (customer or partner), ownerExternalId, partner, isActive, maxRedemptions, redemptionCount, expiresAt, overrides, externalRef, syncState (pending, synced, error, disabled) and syncError. Errors: CODE_NOT_FOUND 404, CUSTOMER_NOT_FOUND 404, PROGRAM_DISABLED 409, CODE_TAKEN 409, CUSTOMER_ALREADY_HAS_CODE 409, EXTERNAL_REF_CONFLICT 409, CUSTOMER_NOT_ELIGIBLE 422, INVALID_CODE, INVALID_OVERRIDE, INVALID_LIMIT, INVALID_CURSOR 400.
Attributions
POST P/referrals/attributions:
{ "code": "ABCD1234", "referee": { "externalId": "org_456", "email": "new@example.com", "stripeCustomerId": "cus_..." }, "source": "link" }source is link or code (default code). stripeCustomerId is optional. Response data: { "ok": true, "attribution": { ... }, "created": true, "alreadyAttributed": false } or { "ok": false, "reason": "..." } with HTTP 200. The attribution has id, status (attributed, converted, reversed, expired), code, referrerExternalId, partner, refereeExternalId, source (link, code, import, checkout), attributedAt, expiresAt, convertedAt, flaggedReason, createdAt. A different Stripe customer for an already registered externalId is 409 EXTERNAL_ID_CONFLICT; a Stripe customer used by another externalId is 409 STRIPE_CUSTOMER_CONFLICT; a malformed id is 400 INVALID_STRIPE_CUSTOMER_ID.
Checkout resolution
POST P/referrals/checkout-resolution:
{ "code": "ABCD1234", "referee": { "externalId": "org_456", "email": "new@example.com", "stripeCustomerId": "cus_..." }, "priceId": "price_...", "interval": "month" }code is optional (the referee's existing attribution is used). Response data:
{
"ok": true,
"promotionCodeId": "promo_...",
"couponId": "...",
"referralId": "...",
"code": "ABCD1234",
"discount": { "type": "percent", "value": 20, "duration": "repeating", "months": 3 },
"alreadyAttributed": false
}or { "ok": false, "reason": "..." }. Reasons: disabled, not_found, inactive, expired, max_uses, plan_not_allowed, period_not_allowed, self_referral, not_first_time, not_synced. Pass discounts: [{ promotion_code: promotionCodeId }] to your Checkout Session and never allow_promotion_codes. The response is Cache-Control: private, no-store.
Referrers
GET P/referrals/referrers/{externalId} returns { program, code, referrals, credits }. code is { available: true, code, active, usable, shareLink, created } or { available: false, reason, message } (program_disabled, not_eligible, not_created). Referrals mask the referee (j***@example.com) and use the buckets signed_up, subscribed, expired, reversed. Credits are grouped as earned (applied only), pending and not earned with per-currency totals. At most 100 items per list (truncated). A customer outside the project or environment is 404 CUSTOMER_NOT_FOUND. The self code is created on first view only when the caller may also create codes and the customer is eligible.
Operate credits
GET P/referrals/credits filters: status (pending, approved, applying, applied, rejected, expired, reversed, failed), kind (referral, manual, goodwill, reversal), customerExternalId, limit (1 to 200), cursor. A credit has id, kind, status, customerExternalId, partner, referralId, code, sourceInvoiceId, basisAmount, percentBps, amount (minor units; negative for a reversal), currency, reviewRequired, reviewReason, eligibleAt, expiresAt, approvedBy, approvedAt, rejectedReason, stripeBalanceTransactionId, reversalOfId, attempts, lastError, createdAt, updatedAt.
| Action | Request | Notes |
|---|---|---|
| Approve | POST .../credits/{id}/approve | Moves pending only and overrides a review hold. 409 CREDIT_STATE_CONFLICT otherwise. |
| Reject | POST .../credits/{id}/reject { "reason": "..." } | reason 1-500 characters. Moves pending, approved or failed. |
| Retry | POST .../credits/{id}/retry | failed to approved with a fresh attempt budget. 200 { credit, enqueued }. |
| Mark applied | POST .../credits/{id}/mark-applied { "stripeBalanceTransactionId": "cbtxn_..." } | From failed, approved or applying. 422 BALANCE_TRANSACTION_NOT_FOUND, BALANCE_TRANSACTION_MISMATCH, CREDIT_NOT_PAYABLE. |
| Bulk | POST .../credits/bulk { "ids": [...], "action": "approve" or "reject", "reason"? } | 1 to 100 ids; one result per id. reason required to reject. |
| Manual credit | POST .../credits/manual { customerExternalId, amount, currency, kind: "manual" or "goodwill", reason, idempotencyKey, approve? } | 201 created, 200 repeat of the same key, 409 IDEMPOTENCY_CONFLICT. |
| Export | GET .../credits/export.csv?status&kind&from&to | Columns id, kind, status, referrer, code, invoice, amount, currency, created_at, approved_at. At most 50,000 rows. |
An id outside the project or environment is 404 CREDIT_NOT_FOUND. Admins can also use the dashboard (Referrals pages) and the authenticated MCP server at https://billing.w3dev.app/mcp: get_referral_summary, list_pending_referral_credits, approve_referral_credit, reject_referral_credit, create_referral_code and get_referrer_view. MCP callers need the same referral: IAM actions plus the mcp:read or mcp:write OAuth scope.
Reports
GET P/referrals/reports/summary returns credits (byStatus per status with count and per-currency amounts, total, reversals, paid, clawedBack, outstandingDebit, net), referrals (byStatus, total) and codes (active, total). Amounts are minor units.
Stripe sync and import
POST P/referrals/stripe-sync marks every code of the environment for sync and answers 202 { codesMarkedForSync, enqueued } (enqueued: false means the scheduled sweep will run it). POST P/referrals/import?mode=dry_run|apply|verify accepts the versioned JSON payload (up to 5 MB) described in Import an existing referral system; an apply that is blocked by errors is 409 with the report.
Customer registration
PUT P/customers/{externalId} with { "email": "owner@example.com", "name": "Example Org", "stripeCustomerId": "cus_..." } returns 201 or 200 with { customer, created }. It never calls Stripe. 409 STRIPE_CUSTOMER_CONFLICT and 409 EXTERNAL_ID_CONFLICT report identity conflicts.