Skip to content

Referrals with your own billing

Run a referral program with referee discounts and referrer credits when your product keeps its own Stripe account, Checkout sessions and subscriptions.

Use this guide when your product creates its own Stripe Checkout sessions and owns its subscriptions (external billing mode) and you want BillStack to run only the referral program and the referrer credit ledger. If BillStack should run checkout, use Referrals instead. Agents can load the integrate referrals skill.

BillStack never creates your checkout sessions or subscriptions and never owns your entitlements in this mode. It watches your Stripe account through its own webhook endpoint, creates the discount objects it needs there, and pays referrers as Stripe customer-balance credits.

What BillStack does and what you do

BillStackYour product
Stores the program, codes and credit ledgerRegisters customers by your own id and Stripe customer id
Creates one Stripe coupon per program and one promotion code per referral codeShows share links, captures ?ref=CODE, and sends signup and checkout calls from your server
Validates a code for a plan and returns the promotion codePasses that promotion code to your own Checkout Session
Converts a referral on the referee's first paid invoice and creates a pending creditReceives signed webhooks and, for host-fulfilled rewards, grants the benefit
Holds, approves, pays and reverses credits; runs all schedulingShows the referrer their code and credits (API or embed)

Flow

sequenceDiagram
  participant R as Referrer
  participant E as Referee
  participant App as Your product
  participant BS as BillStack
  participant S as Your Stripe account
  R->>E: share link (billing.w3dev.app/r/team/project/CODE or your own ?ref=CODE)
  E->>App: lands on shareLandingUrl?ref=CODE
  App->>App: captureReferral() stores the bs_ref cookie
  E->>App: signs up
  App->>BS: POST attributions (code, referee)
  App->>App: clearReferral()
  E->>App: starts checkout
  App->>BS: POST checkout-resolution (priceId, interval)
  BS-->>App: ok, promotionCodeId
  App->>S: create Checkout Session with discounts[promotion_code]
  E->>S: pays
  S->>BS: invoice.paid (BillStack webhook endpoint)
  BS->>BS: referral converted, credit pending
  BS-->>App: signed webhook referral.converted, referral.reward_pending
  BS->>BS: hold period, then approval (auto or manual)
  BS->>S: customer balance credit for the referrer
  BS-->>App: signed webhook referral.reward_applied

Set up

Connect Stripe with a restricted key

Connect the team's Stripe account in the team's Stripe integration settings. A restricted key is recommended with: Coupons write, Promotion codes write, Customers write (balance transactions), Invoices read, Charges read, Disputes read, Credit notes read, Webhook endpoints write, plus read access for the Stripe mirror sync. The Stripe status endpoint (GET /api/billstack/teams/{teamId}/stripe/status) returns permission warnings. Write permissions on a restricted key can only be confirmed in the Stripe Dashboard.

BillStack registers its own webhook endpoint in your Stripe account. A BillStack operator refreshes the subscribed events after releases that add event types.

Register customers

PUT /api/billstack/v2/teams/{teamId}/projects/{projectId}/customers/{externalId} with { email, name?, stripeCustomerId, metadata? }. It never calls Stripe. A Stripe customer already used by another externalId is 409 STRIPE_CUSTOMER_CONFLICT; an externalId that already has a different Stripe customer is 409 EXTERNAL_ID_CONFLICT.

Configure the program

PUT .../referrals/program with billingOwnership: "external", the referee discount, plan limits, reward model and approval settings. Set enabled: true in this step: the code routes answer 409 PROGRAM_DISABLED while the program is disabled, so the first code cannot be created (or synced) before it. With no attributions yet, enabling is safe. Keep it disabled only while you import existing history. See Program settings.

Share, attribute and resolve

Capture the code with @billstack/sdk/browser, attribute at signup, resolve before checkout. See Capture, attribute and check out.

Receive webhooks and show referrers their credits

Create an outbound webhook endpoint and show the referrer view.

All v2 routes use a private key (bs_test_ or bs_live_) as a Bearer token, or a signed-in project session. Publishable keys are refused, except on the public code check. Test and live data never mix; see Test and live environments. The full route list is in the referrals API reference.

Program settings

GET and PUT .../referrals/program. A PUT merges the keys you send into the stored program and validates the result as a whole; null clears a nullable setting.

SettingValuesMeaning
enabledbooleanTurns the program on. Must be true to create codes (409 PROGRAM_DISABLED otherwise). A disabled program has no live promotion codes and no automation.
billingOwnershipexternal, billstackUse external here. The default of an unconfigured project is billstack.
currency3-letter codeCurrency of fixed amounts.
discountType, discountValuepercent (1-100), fixed_amount (minor units)The referee's discount.
discountDuration, discountMonthsonce, repeating (1-36 months), foreverHow long it applies.
allowedPriceIds, allowedProductIds, allowedIntervalslists or nullPlans and billing periods the program accepts. A code can narrow them.
rewardTypepercent_of_paid, fixed, host_fulfilledThe referrer's reward. bonus_months is only for BillStack checkout.
rewardPercentBps, rewardCapAmount, rewardFixedAmountintegersBasis points (1-10000), per-invoice cap, fixed amount (minor units).
rewardScope, rewardInvoiceLimitfirst_invoice, recurring_n, recurring_foreverWhich invoices of the referee earn a reward.
rewardBasisnet_of_tax_after_discount, amount_paidWhat the percentage applies to.
payoutMethodstripe_balance, ledger_onlyCredit the referrer's Stripe balance, or only record it.
clawbackModeledger_debit, stripe_balanceHow a reversal is taken back from an already paid reward.
approvalMode, holdDays, approvalWindowDaysmanual/auto, days (defaults 14 and 60)Approval and hold timing.
attributionTtlDays, attributionExpiryDaysdays (defaults 60 and 90)Browser cookie lifetime and how long an attributed referee has to pay.
shareLandingUrlhttps URLWhere share links send visitors. Its origin is the only origin allowed to frame the referrer embed.
selfReferralFreeMailDomainslistReplaces the default free-mail list used by the shared-domain check.
partnerPortalEnabledbooleanTurns on the hosted partner portal: referrer sign-in and payout requests. Default off.
minPayoutAmountinteger (minor units) or nullSmallest payout a referrer may request per currency.

The Stripe coupon is created and rotated by BillStack. Changing the discount creates a new coupon and replaces active promotion codes; coupons are immutable in Stripe, and existing subscriptions keep the discount they already have. Do not create coupons or promotion codes yourself.

A referrer's own code: POST .../referrals/codes/self with { externalId }. The customer must exist and hold a subscription whose status is in the program's eligibleSubscriptionStatuses; otherwise 422 CUSTOMER_NOT_ELIGIBLE. Admin and partner codes: POST .../referrals/codes with exactly one of externalId or partner: { email, name }, plus optional code (4-20 letters or digits), maxRedemptions, expiresAt, plan overrides and externalRef.

LinkBehaviour
https://billing.w3dev.app/r/{teamSlug}/{projectSlug}/{CODE}Validates the code and redirects (302) to shareLandingUrl?ref=CODE. Live environment only. An invalid code, unknown project or missing landing URL is the same bare 404. No click is recorded.
https://your-app.example.com/signup?ref=CODEYour own page. Use this in test.

Each code has a syncState: pending (waiting for the Stripe promotion code), synced (live), error (see syncError) or disabled. A code is usable at checkout only when it is synced. A promotion code switched off in Stripe deactivates the BillStack code; other drift is repaired by BillStack.

Capture, attribute and check out

Capture on the landing page

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

captureReferral({ ttlDays: 60 });
const referral = getReferral(); // { code, capturedAt } or null

It reads only the configured query parameter (default ref) and an optional path pattern, never utm_*, and writes a first-party bs_ref cookie. Use the program's attributionTtlDays as ttlDays. A still-valid cookie is kept (first touch).

Attribute at signup

From your server: POST .../referrals/attributions with { code, referee: { externalId, email, stripeCustomerId? }, source? }. A code that cannot be used is HTTP 200 { ok: false, reason }; never block signup on it. Then call clearReferral().

Resolve at checkout

From your server, before creating your Checkout Session: POST .../referrals/checkout-resolution with { code?, referee, priceId, interval }. On ok: true pass discounts: [{ promotion_code: promotionCodeId }] and do not set allow_promotion_codes.

Rejection reasons (ok: false): disabled, not_found, inactive, expired, max_uses, plan_not_allowed, period_not_allowed, self_referral, not_first_time, not_synced.

  • The first attribution wins. A referee who already has a live attribution keeps it; presenting a different code returns the original with alreadyAttributed: true.
  • A referee with an earlier paid invoice (amount above zero) is not_first_time. A $0 trial invoice does not count.
  • Checkout resolution records an attribution when there is none, so a host that skips the signup call still credits the referrer.
  • Trials: use discountDuration: "repeating" with enough discountMonths to cover the first paid invoice. With once, Stripe applies the discount to the $0 trial invoice and the referee gets nothing.

Attribution states

stateDiagram-v2
  [*] --> attributed: signup attribution or checkout resolution
  attributed --> converted: first invoice.paid with amount_paid above 0
  attributed --> expired: not converted within attributionExpiryDays
  expired --> attributed: referee attributed again with a code
  converted --> reversed: the converting invoice is fully refunded, credited or disputed

A $0 trial invoice never converts a referral. A converted or reversed attribution is never replaced. A reversed referral earns no further rewards.

Self-referral rules: the same customer, externalId or Stripe customer is always blocked (self_referral). A shared email domain outside the free-mail list, an identical email address, or the same card fingerprint as the referrer does not block the signup, but the credit is created held for manual review (reviewRequired).

Rewards and credits

On invoice.paid for an external project, BillStack looks up the referee's attribution and creates a ledger entry unless the invoice is skipped: $0 invoices, a price or billing period outside the allowed lists, a deactivated attribution, or a reward scope already used up. A skipped invoice creates nothing and is logged.

Formulas

For percent_of_paid:

  1. Basis with rewardBasis: net_of_tax_after_discount: the invoice total without tax, never more than the cash actually collected (amount_paid). With amount_paid, the basis is the amount paid including tax.
  2. reward = floor(basis × rewardPercentBps ÷ 10000), then at most rewardCapAmount per invoice.

For fixed: rewardFixedAmount, once per referral (the first rewarded invoice). For host_fulfilled: amount 0; the months in rewardMonths are reported to you and you grant the benefit. Percent entries use the invoice currency; a fixed entry uses the program currency; a mismatch is recorded, never converted.

rewardScope: first_invoice rewards only the referee's first paid invoice, recurring_n the first rewardInvoiceLimit invoices, recurring_forever all of them. A duplicate Stripe event never creates a second credit.

Credit states

stateDiagram-v2
  [*] --> pending: reward earned
  pending --> approved: auto after holdDays, or approved by a person
  pending --> rejected: rejected
  pending --> expired: approvalWindowDays elapsed
  approved --> applying: payout job claims it
  approved --> applied: marked applied by an admin
  approved --> rejected: rejected
  approved --> expired: approvalWindowDays elapsed
  applying --> applied: Stripe balance credit created
  applying --> approved: error, retried
  applying --> failed: attempts spent
  failed --> approved: admin retry
  failed --> applied: marked applied by an admin
  failed --> rejected: rejected
  applied --> reversed: refund, credit note or dispute

A credit is never stuck: the payout job holds a 10-minute lease, calls Stripe with an idempotency key and a billstack_credit_id marker, rolls back to approved on any error, and a 15-minute job reclaims expired leases and adopts a Stripe credit that already succeeded before retrying.

Approval and payout

  • approvalMode: auto approves a pending credit after holdDays unless it is held for review. manual leaves every credit for a person (dashboard, API or MCP tools).
  • Pending and approved credits that are not paid within approvalWindowDays expire. Manual and goodwill credits never expire.
  • payoutMethod: stripe_balance creates a customer-balance credit on the referrer's Stripe customer. A partner code (no customer), ledger_only programs and host_fulfilled rewards are marked applied without moving money; use the CSV export to pay partners.

Clawbacks

A refund, credit note or dispute reverses the reward in proportion:

Reward stateResult
pending, approved, failedFully reversed: rejected. Partly reversed: the amount is reduced.
applyingThe event is retried after the payout settles.
appliedA reversal entry (negative amount) is created.
rejected, expired, reversedNothing.

clawbackMode: ledger_debit keeps the reversal as a debit that is offset against the referrer's next payouts (a payout that is fully offset moves no money). stripe_balance approves the reversal and debits the referrer's Stripe balance. A won dispute does not restore the reward; give it back with a manual credit. Reversal events are referral.reward_reversed (or referral.reward_rejected for an unpaid reward).

Scheduling is done by BillStack

You do not run any cron job. BillStack's background jobs auto-approve after the hold, expire stale credits and attributions, reclaim stuck payouts, enqueue approved credits (every 15 minutes), sweep Stripe promotion code sync (every 10 minutes) and retry webhook deliveries (every 5 minutes). Disabling the program, or leaving external mode, pauses this automation.

Webhooks

Subscribe to the events you need and verify the signature with webhooks.constructEvent from @billstack/sdk. Deduplicate on the event id. The full catalogue, payloads, retries and replay are on Outbound webhooks.

EventTypical action
referral.convertedNotify the referrer.
referral.reward_appliedIf data.hostFulfilled is present ({ type: "bonus_months", months }), grant the benefit yourself.
referral.reward_reversedFor host-fulfilled rewards, revoke the benefit.
referral.reward_failedAlert an operator; retry from the credit.
payout.requestedA referrer asked to be paid: review it, pay them, then mark it paid.
payout.paid, payout.rejected, payout.cancelledUpdate your own payment records.

Pay partners with payout requests

For partner codes and ledger_only programs, BillStack never pays the referrer. Instead of paying from the CSV export, you can turn on the partner portal: referrers sign in (emailed magic link, or a URL your server mints), see earned, pending and available balances, and request a payout once they have earned something. You review requests in Referrals > Payouts (or through the API, SDK and MCP), pay the referrer yourself, and mark the request paid with your payment reference. A request reserves the referrer's payable credits so nothing is paid twice; a rejected or cancelled request releases them. BillStack moves no money and there is no Stripe Connect.

The payout.requested, payout.approved, payout.rejected, payout.paid, payout.cancelled and payout.credit_reversed events let you automate your own payment run.

Show referrers their credits

  • API: GET .../referrals/referrers/{externalId} returns the code, share link, referrals with masked referees, and credits grouped as earned (applied only), pending and not earned with per-currency totals. SDK: client.referrals.getReferrer(externalId).
  • Embed: mint a URL on your server with createReferralEmbedUrl(config, { externalId }) from @billstack/sdk and put it in an iframe. The URL is https://billing.w3dev.app/embed/referrals/{token}; the session lasts one hour by default (seven days at most). BillStack allows framing only from the origin of shareLandingUrl, so the host page must be served from that origin. The page posts { type: "billstack:resize", height } to its parent.
  • Partner portal: a hosted page at /partners/{teamSlug}/{projectSlug} with balances, credit history and payout requests: Partner portal and payout requests.
  • Portal: a portal session for an externally billed customer shows the referrals view only; subscriptions, invoices and cards stay in your own billing.

Test mode

Use bs_test_ keys and your Stripe test-mode account. Hosted /r/... links only work in live; in test send visitors to your own landing page with ?ref=CODE. Run a full cycle: sync a code, capture, attribute, resolve, pay a test Checkout Session, confirm the webhooks, approve, confirm the Stripe balance credit, refund, confirm the reversal.

Already have a referral system?

Import it instead of recreating it: Import an existing referral system. The importer adopts your existing coupon, promotion codes and balance transactions.

Troubleshooting

SymptomCause
not_syncedThe promotion code is not created yet or the program has no discount. Check the code's syncState and syncError, fix the Stripe key permissions, then POST .../referrals/stripe-sync.
period_not_allowed, plan_not_allowedThe checkout interval or price is outside the program's or the code's limits.
Webhook events ignored for a customerThe same Stripe customer exists in two projects of one team and allowedPriceIds or allowedProductIds cannot tell them apart (ambiguous_customer). The event is skipped and a warning is logged.
Credit held as pendingreviewRequired is true (self-referral flag or imported). A person must approve or reject it.
Credit failedThe Stripe balance credit failed repeatedly. Fix the cause (key permissions, missing or deleted Stripe customer), then retry it.
PAYOUTS_LOCKED or PORTAL_DISABLED in the partner portalThe referrer has not earned anything yet, or partnerPortalEnabled is off.
Embed iframe blankshareLandingUrl is missing, is on another origin than the framing page, or the token expired.