Skip to content

Import an Existing Referral System

Move referral codes, Stripe promotion codes, attributions and credit history into a BillStack project that keeps its own billing.

Use this migration when your product keeps its own Stripe account, Checkout sessions and subscriptions (external billing mode) and already runs a referral program of its own: referral codes backed by Stripe promotion codes, referrals, and a credit ledger with Stripe customer balance transactions.

For projects where BillStack owns checkout, use Migrate an Affiliate System instead.

The importer reads a versioned JSON file, checks it against your project and (read-only) your Stripe account, and writes it idempotently. It never creates or changes anything in Stripe: it adopts the coupon, promotion codes and balance transactions you already have.

Procedure

Always in this order. Each step is safe to repeat.

Prepare the project

Register the program in external mode and leave it disabled until the import is verified. The import file can carry the settings (program), or you set them first with PUT .../referrals/program. Connect the Stripe account of the team.

Export your data to the JSON format below

See Export recipe. Large systems can be split into several files; entities may refer to each other across files because references are resolved against the database (customers by externalId, codes by externalRef).

Dry run

bun run referrals:import --project-id <id> --environment live --file payload.json --team-id <teamId>

Validates everything, reads Stripe, writes nothing, and prints a report: counts per entity (create, update, skip, conflict) and issues with a severity. Fix every error, read every warning, then run it again until no error is left.

Apply

bun run referrals:import ... --apply

Refuses to write while any error exists (--skip-conflicts writes the rows without conflicts and reports the rest; errors about the program or the coupon always block). Re-running --apply is a no-op for everything already imported.

Verify

bun run referrals:import ... --verify

Re-reads the database and compares it with the file: rows that are missing, values that differ, and the credit totals per currency (payload against ledger). It does not call Stripe.

Enable the program, then let BillStack reconcile Stripe

Enable the program, then immediately run POST .../referrals/stripe-sync (or Resync with Stripe on the referrals settings page). The sync stamps your coupon and promotion codes as managed by BillStack and handles every code the importer left without a state. Do not run the sync while the program is disabled: a disabled program has no live promotion codes, so the sync would deactivate yours. Check the codes page for synced.

The same three modes are available over HTTP:

curl -X POST \
  "https://billing.w3dev.app/api/billstack/v2/teams/{teamId}/projects/{projectId}/referrals/import?mode=dry_run" \
  -H "Authorization: Bearer bs_..." \
  -H "Content-Type: application/json" \
  --data @payload.json

mode is dry_run (default), apply or verify. The key must be a secret key (or a signed-in user) with referral:UpdateConfig. The environment is the key's own; a signed-in user passes ?environment=test|live. The body is limited to 5 MB (413 PAYLOAD_TOO_LARGE); split larger exports. The response is the report; an apply that refused to write is a 409 with the report. Optional query flags: skipConflicts=true, emitEvents=true.

Format (version 1)

{
  "version": 1,
  "program": { "billingOwnership": "external", "rewardType": "percent_of_paid", "rewardPercentBps": 1000,
               "discountType": "percent", "discountValue": 20, "discountDuration": "repeating", "discountMonths": 3 },
  "coupon": { "stripeCouponId": "co_abc123" },
  "customers": [
    { "externalId": "org_1", "email": "owner@example.com", "name": "Acme", "stripeCustomerId": "cus_123" }
  ],
  "codes": [
    { "externalRef": "ref_code_17", "code": "ACME20",
      "owner": { "externalId": "org_1" },
      "stripePromotionCodeId": "promo_123", "maxRedemptions": 50, "redemptionCount": 12,
      "expiresAt": "2027-01-01T00:00:00Z", "active": true,
      "allowedIntervals": ["month", "year"], "createdAt": "2026-03-01T10:00:00Z" },
    { "externalRef": "ref_code_18", "code": "AGENCY25",
      "owner": { "partnerEmail": "sales@agency.example", "partnerName": "Agency" }, "active": true }
  ],
  "attributions": [
    { "externalRef": "ref_17", "codeExternalRef": "ref_code_17", "referee": { "externalId": "org_2" },
      "status": "converted", "attributedAt": "2026-04-01T09:00:00Z", "convertedAt": "2026-04-03T09:00:00Z",
      "firstInvoiceId": "in_123", "paidInvoiceCount": 1 }
  ],
  "credits": [
    { "externalRef": "txn_901", "referrer": { "externalId": "org_1" }, "kind": "referral",
      "sourceInvoiceId": "in_123", "amount": 900, "currency": "usd", "status": "applied",
      "stripeBalanceTransactionId": "cbtxn_123", "createdAt": "2026-04-03T09:00:00Z",
      "approvedAt": "2026-04-17T09:00:00Z", "appliedAt": "2026-04-18T09:00:00Z",
      "attributionExternalRef": "ref_17" }
  ]
}

The schema is exported as referralImportSchema from @repo/billstack/referrals/import (zod). Rules in short:

FieldRule
versionMust be 1. Unknown keys are rejected so a typo cannot silently drop data.
programAny subset of the program settings (same shape and validation as PUT .../referrals/program). The resulting program must be billingOwnership: "external". enabled is honoured but should stay false until verified.
coupon.stripeCouponIdThe host's coupon behind the referee discount. If the program has no discount and Stripe is checked, the discount is taken from the coupon.
externalRefYour own id for the row. Required on codes, attributions and credits; the key that makes a re-run a no-op. Up to 200 characters.
customers[]externalId, email, optional name and stripeCustomerId (cus_...). Same identity rules as PUT .../customers/{externalId}. Customers already in the project are not re-created. Codes, attributions and credits may also refer to customers that are only in the database.
codes[].codeAt most 20 characters (A-Z a-z 0-9 - _); stored upper-case. Unique per project and environment ignoring case, and across projects.
codes[].owner{ "externalId" } (customer code, one per customer) or { "partnerEmail", "partnerName"? } (partner code, no customer).
codes[].redemptionCountUses so far. Defaults to the number of attributions in the file for that code.
attributions[]codeExternalRef (preferred) or code, never both. status: attributed, converted, expired, reversed.
credits[].referrer{ "externalId" } for a customer, { "codeExternalRef" } for a partner credit (no customer, settled outside BillStack).
credits[].kindreferral, manual or goodwill.
credits[].amountPositive integer, minor units. Reversals are not imported as entries.
credits[].attributionExternalRefOptional link to the attribution that earned a referral credit.

Status mapping

Credits are imported directly in their final state, with one transition row (actor_type system, actor_id import, reason imported, the source dates and status in its metadata). BillStack never imports an in-between state.

Source credit statusImported asNotes
pendingpendingFlagged for manual review (reason imported); no hold, no expiry, never auto-approved. Approving it in the dashboard overrides the flag.
approvedapprovedWill be paid by BillStack once the program is enabled (see caveats).
applyingapprovedThe source payout was mid-flight. A note in the transition says so. With a balance transaction id the dry run refuses it: a paid credit must be sent as applied.
appliedappliedKeeps stripeBalanceTransactionId, verified in Stripe when a client is available.
rejectedrejectedreason becomes the rejection reason.
expiredexpired
reversedreversedHistory only: no reversal entry is written.
Source attribution statusImported as
attributedattributed, expires after the program's attributionExpiryDays from attributedAt (an old one is expired by the next credits tick).
convertedconverted, paidInvoiceCount defaults to 1 so the first invoice is not rewarded again.
expired, reversedthe same status.

Attributions are stored with source = import and provider_event_id = import:<externalRef> (the table has no external reference column); the referee's unique index keeps it to one per referee. An existing attribution of a referee is never overwritten: the same code is kept, a different code is a conflict.

Adoption of Stripe objects

The importer only reads Stripe (coupons.retrieve, promotionCodes.retrieve and .list, customers.retrieveBalanceTransaction), through the team's own key given by --team-id (or the route's team). It never creates a coupon, promotion code or balance transaction.

SituationResult
Coupon exists and matches the program discountStored as the program's coupon. The first sync stamps it as managed by BillStack instead of replacing it.
Coupon is missing, invalid, or its discount differs from the programError.
Promotion code exists on the program coupon, with matching code, limit and expiryCode stored with sync_state = synced.
Promotion code exists but is not first-time-only, or its limits or active state differAdopted and left pending (no state while the program is disabled) with a warning; the sync replaces it (the old one is deactivated first).
Promotion code is missing, on another coupon, or has a different code stringError (conflict).
No promotion code id in the file, an active one with that code exists on the program couponFound by its code string and adopted.
No promotion code id and none in Stripepending; the sync creates it once the program is enabled.
Balance transaction exists on the referrer's Stripe customer with amount -amountKept on the applied credit. Missing or different is an error.
No Stripe client (no --team-id)Ids are stored unverified, codes are pending (no state while the program is disabled), a warning says so. The sync verifies and adopts them later.

Export recipe

A generic export from a Postgres referral system. Adapt names to your schema; the importer only needs the JSON.

-- codes: one row per code
SELECT json_build_object(
  'externalRef', rc.id::text,
  'code', rc.code,
  'owner', json_build_object('externalId', rc.owner_org_id::text),
  'stripePromotionCodeId', rc.stripe_promotion_code_id,
  'maxRedemptions', rc.max_uses,
  'redemptionCount', rc.times_used,
  'expiresAt', rc.expires_at,
  'active', rc.is_active,
  'createdAt', rc.created_at)
FROM referral_codes rc;

-- credits: one row per credit transaction
SELECT json_build_object(
  'externalRef', t.id::text,
  'referrer', json_build_object('externalId', t.referrer_org_id::text),
  'kind', 'referral',
  'sourceInvoiceId', t.stripe_invoice_id,
  'amount', t.amount_cents,
  'currency', lower(t.currency),
  'status', t.status,                        -- pending / approved / applying / applied / rejected / expired
  'stripeBalanceTransactionId', t.stripe_balance_transaction_id,
  'createdAt', t.created_at,
  'approvedAt', t.approved_at,
  'appliedAt', t.applied_at,
  'reason', t.note)
FROM referral_credit_transactions t;

Assemble the arrays into one document (for example with jq -s). Referrals (referee, code, status, dates) and the owners and referees as customers follow the same pattern. Dates must be ISO 8601 with an offset.

Caveats

  • A disabled program is never synced. While the program is disabled the importer stores codes without a sync state, because a pending code would make the 10-minute sweep deactivate the promotion code you already have in Stripe. Do not change the discount settings of the disabled program after the import for the same reason; enable it first.
  • Approved credits get paid. BillStack's apply job pays every approved credit of an enabled external program through the referrer's Stripe customer balance. Import with the program disabled, verify, and check that none of your approved or applying credits was already paid in Stripe before you enable it. A credit that was paid must be imported as applied with its balance transaction id.
  • No events. Imported history publishes no outbound webhook events, so your endpoints are not flooded with old news. Pass --emit-events (or emitEvents=true) to publish referral.code_created for created codes and the status event of created credits; attributions never emit.
  • Re-running does not update. Rows that already exist are left as they are (admins and payouts may have changed them since). The only update is adopting a promotion code id on a code that had none, and filling in a missing Stripe customer id or email on a customer. A credit with the same externalRef but a different amount, currency, kind or referrer is a conflict.
  • One credit per invoice and kind. A referral credit whose sourceInvoiceId already has a credit in BillStack (for example one earned live after cutover) is a conflict; this is what prevents a double reward.
  • Codes over 20 characters or with other characters cannot be imported. Codes that are not 4-20 letters or digits are imported (with a warning) but the public code check, the hosted /r/ link and the browser SDK do not accept them.
  • Reversed credits are history. No reversal entry is written, so the report's clawed-back and net totals do not include them.
  • Test environment. Run the whole procedure against --environment test first.