Skip to main content

Client Billing (Stripe Connect)

Audience: Engineering / Support · Where in app: agency Settings → Payments / Signup Page (owner only), Packages → Edit → Client Price, client detail → Client Payments; client portal Packages & Billing → Your Plan; public /signup/:token · Since: backend af2e8f65f (2026-09-25), refined through c0748c695

Agencies collect from their own clients on their own Stripe account (Standard account, OAuth scope: read_write). Charges are direct charges on the agency's account — the agency is merchant of record (refunds, disputes, payouts); our cut is the application_fee. Two rails never mix: client → agency goes through Connect and is mirrored in agency_client_billings; agency → us stays on the platform customer.

There is no per-agency super-admin gate — every owner sees the tabs. The only prerequisite is the platform env STRIPE_CONNECT_CLIENT_ID (empty → configured: false → "Online client payments aren't available yet … contact support"). Super-admin knobs shape it: fee override, default markup, trial seats/days/conversion add-on, opening-transfer minimum.

Config​

app/configs/stripe.js: STRIPE_CONNECT_CLIENT_ID, STRIPE_CONNECT_REDIRECT_URI (default <portal_url>/agency/settings/payments), STRIPE_CONNECT_WEBHOOK_SECRET, STRIPE_CONNECT_APPLICATION_FEE_PERCENT (default 0). PROD sets the client id, webhook secret and fee in flux-deployments/Apps/PROD/backend/secret.sops.yaml (backend only — not the schedular).

agencies.stripe_connect (AgencyModel): account_id (sparse index), livemode, charges_enabled, payouts_enabled, details_submitted, default_currency, country, business_name, email, connected_at, disconnected_at, oauth_state / oauth_state_expires_at (select:false, 15 min), application_fee_percent (null = env default), wallet_markup_multiplier (agency default, super-admin only), portal_configuration_id.

Connection​

AgencyStripeConnectController + lib/stripeConnect.js, routes app/routes/agencyStripeConnectRoutes.js (mounted before agencyRoutes, else GET /agencies/:id swallows them). Stripe calls in StripeService (connect*).

  • GET /agencies/stripe-connect — status for any agency user (configured, connected, flags, resolved fee, is_owner).
  • POST /agencies/stripe-connect/{authorize,callback,refresh,disconnect} — owner only (user_type === 'agency', else 403). authorize 503s when unconfigured. Stripe redirects to the frontend with code&state; the frontend POSTs them to callback (timing-safe, single-use state). One Stripe account per agency (409 "already connected to another agency").
  • Disconnect deauthorizes (failure logged, continues) and clears the account fields. Package prices are not cleared but become unsellable (client_billing.stripe_account_id ≠ current account) until re-saved. Existing client subscriptions keep billing on the agency's Stripe; we just stop receiving their events.
  • UI: views/agency/settings/Payments.vue (route agency-settings-payments, ownerOnly): "Connect with Stripe", account card ("Accepting payments" / "Setup incomplete", "Test mode"), checks, "Stripe dashboard", "Refresh status", "Disconnect", "How clients pay you", "Client payments" list.

Package prices​

PUT /agencies/stripe-connect/packages/:id/price {amount, currency, interval} ({amount: null} removes) — needs agency.manage_packages. Amount ≥ 0.50 (non-zero-decimal) and ≤ 1,000,000; 3-letter currency; month/year. Same account → reuses the product, mints a new price, archives the old; unchanged price is a no-op. Existing subscribers keep their price.

PackageModel: client_billing {amount, currency, interval, stripe_account_id, stripe_product_id, stripe_price_id}, signup_visible (separate from visibility, which stays private), archived_at (archive also clears signup_visible). Trial reuses free_trial / trial_limit, written from body.trial_days capped by maxTrialDays (TRIAL_DAYS_OVER_LIMIT).

UI views/agency/packages/Edit.vue: Client Price ("Charge for this package", Amount, Currency limited to the account default + saved one, "Billed every" Month/Year, "Free trial (days)"), Availability → "Show on signup page". Price saves in a second call after the package save ("Package saved, but the client price was not: …").

Client side​

/client-billing* (same routes file):

  • GET /client-billing (any company user): enabled, agency_name, can_manage (web_owner), can_pay (enabled && priced && no live subscription), wallet_via_agency (bool only — never the percentage), package {…, trial_days, priced}, billing summary (live, price_mismatch).
  • Owner only: POST /client-billing/checkout (hosted Checkout — unused by the frontend), GET/POST /client-billing/cards, POST …/cards/setup-intent, DELETE …/cards/:payment_method_id (can't delete the only card a live plan bills), POST /client-billing/subscribe (payment_behavior: default_incomplete, fee + trial; returns client_secret for 3-D Secure, confirmed with Stripe.js {stripeAccount}), POST /client-billing/wallet/top-up, POST /client-billing/portal (Billing Portal on the connected account; config created once, invoices + payment-method update on, cancel off; returns to /packages/agency-billing).
  • Cards live on a customer on the agency's account, separate from platform /cards; a new card becomes default and moves any live subscription onto it. A stored customer id missing from the agency's connected account ("No such customer" — e.g. after a reconnect) is replaced on the fly across card endpoints, payment links and top-ups (5a2276695).
  • With wallet_via_agency, the client's platform cards are hidden in settings/billing/CardManagement.vue (shown again once the plan expired), and POST /client-billing/wallet/top-up without a Connect card returns {card_required: true} → AddOns.vue routes to Plan payment card (1bfdfbaf, 51810c41, ad7f179bc). The agency's ClientPaymentsCard warns that the client must re-add a card.
  • Pay lock (agency_payment_due = agency_payment_required && package billable through Connect && no live Connect subscription, SubscriptionController): after onboarding, and not while impersonating, the router (store/app.js mustPayAgencyPlan) confines owners and members to packages-agency-billing, inform-agency, sdk-docs. Members on InformAgency see "Almost ready / Your account owner needs to add a card…".
  • UI views/packages/AgencyBilling.vue (route packages-agency-billing, tab Your Plan in PackagesTabs.vue, agency sub-accounts only; cards in components/packages/AgencyPlanCards.vue): "Start free trial" / "Pay {amount} and start", "Your last payment didn't go through" + "Update card", "Invoices & receipts", status badges from common/helpers/clientBilling.js; unpriced → "Online payment isn't set up for your plan. Contact {agency} about billing."

Per-client card (agency)​

components/agency/ClientPaymentsCard.vue on views/agency/companies/Detail.vue; hidden unless connected; endpoints need agency.subscription_payments:

  • GET /agencies/stripe-connect/clients, GET …/clients/:company_id
  • POST …/clients/:company_id/payment-link — hosted Checkout on the agency account, 24 h, success/cancel → /packages/agency-billing?checkout=… on the agency's live white-label domain.
  • POST …/clients/:company_id/cancel ("Stop billing", cancel at period end) / …/resume ("Keep billing"); 409 when the subscription belongs to a previously connected account.
  • PUT …/clients/:company_id/wallet-markup — per-client multiplier (needs Connect + charges_enabled).

Webhook​

POST /stripe/connect/webhook (public, signature-verified; 503 without the secret). Agency found by event.account; unknown/disconnected accounts ignored.

  • account.updated mirrors status; account.application.deauthorized marks disconnected.
  • payment_intent.succeeded with metadata.kk_purpose === 'wallet_topup' → AgencyWalletTopUpHelper.creditFromPayment.
  • checkout.session.completed (subscription) and customer.subscription.* → #syncSubscription (re-reads with latest_invoice, mirrors onto agency_client_billings, sets trial_used_at) → #applyToClientSubscription on the local subscriptions row: trialing → active until trial end (credits/flags granted once); active → expiry extended only when latest_invoice is paid; canceled / incomplete_expired → canceled, expiry clamped, unconverted trial seat released; past_due / unpaid left alone (the paid period simply runs out, then the router locks). resource_missing → row marked canceled.
  • invoice.paid → sync + last_payment_*; #grantPaidPeriod once per invoice id (creates an invoices row, resets remaining_ai_credits to the package, expiry = line period.end, flags, audit); amount_paid > 0 → #convertTrialSeat.
  • invoice.payment_failed → last_payment_failed_at / last_payment_error; no suspension.

Platform fee: resolveFeePercent = agency override else env; ≤ 0 = none; capped at 99. Applied as application_fee_percent on subscriptions, so a change affects only subscriptions created afterwards. Override PUT /agencies/stripe-connect/admin/:agency_id/fee {application_fee_percent?, wallet_markup_multiplier?} (admin only).

Wallet markup​

lib/agencyWalletMargin.js. Multiplier m (1–10, normalizeMultiplier): a top-up credits the full amount paid, but every wallet debit costs m× — at 2× a $10 top-up buys $5 of usage. On a top-up we keep round(amount / m) (the application fee) and the agency keeps the rest (splitWalletTopUp).

walletMarkupMultiplier(agency, company): 1 unless the agency has account_id && charges_enabled (Connect-only) and the company isn't a playground; then companies.wallet_markup_multiplier wins over stripe_connect.wallet_markup_multiplier. Applied in TelephonyWalletController (on top of the global telephony markup), AgentKWalletService, AITokensCreditJob (wallet part only), lib/aiSpendGuard.js, WalletActivityController, AgencyWalletTopUpHelper, BalanceAutoRechargeJob. A change applies immediately, including to balance already bought.

sellsWalletThroughAgencyStripe (effective m > 1) → the client tops up via POST /client-billing/wallet/top-up ({addon_id}): our balance add-on's price charged once on the agency account with the client's default card there, application_fee_amount = round(amount / m), credited once keyed wallet_topup:<pi> (3-D Secure → credited by the webhook). Platform buyAddon refuses these clients with 409 agency_wallet_topup. Top-ups take only the markup split, never the platform fee %, and are priced in our add-on's currency.

Admin: views/admin/agencies/Detail.vue "Client Payments" (Revenue share (%), "Default wallet markup for their clients (×)", per-client "Wallet markup" column); views/admin/wallet-margins/WalletMargins.vue "Agency resale" section (GET /settings/agency-margins, read-only).

Public signup page​

AgencySignupController, routes app/routes/agencySignupRoutes.js (also mounted before agencyRoutes).

  • Owner: GET/PUT /agencies/signup-page {enabled, auto_buy_seats, headline} (first enable mints a 24-hex token), POST /agencies/signup-page/rotate. Stored in agencies.public_signup {enabled, token, auto_buy_seats, headline ≤ 200, created_at}. Link: https://<white-label domain or portal_url>/signup/<token>.
  • Public: GET /public/agency-signup/:token offers packages that are signup_visible, active, not archived and priced on the current account. Trial = package trial capped by maxTrialDays, only while client_trials.available > 0. A plan is hidden unless the agency wallet covers the opening-transfer minimum and (trial plan → a trial seat is free; pay-now → a spare paid seat or auto_buy_seats).
  • POST /public/agency-signup/:token/register {email, first_name, company_name, package_id}: rate-limited 5/IP/h and 50/agency/day; reserves a trial seat atomically; creates a passwordless web_owner, a company with agency_id + registered_package_id and the default chatbot, a subscription from clientSubscriptionSeed (inactive, agency_payment_required: true, agency_trial_seat, pinned agency_trial_days, agency_seat_claimed: false), moves the opening wallet (signup_opening_credits); returns a JWT → onboarding → pay lock on Your Plan.
  • SignupOpeningRefundJob (hourly): signups still agency_payment_required 3 days after signup_opening_at get the unspent opening balance (up to the opening amount) returned to the agency.
  • UI: views/agency/settings/SignupPage.vue (route agency-settings-signup-page, ownerOnly: "Public signup", "Your signup link", "Generate a new link", "When you run out of seats" → "Keep accepting and buy me a seat" / "Pause signups until I add seats", "Plans on the page"); public views/auth/AgencySignupView.vue (route agency-signup, /signup/:token, ?pkg= preselects).

Trial seats​

agencies.client_trials {seats, available, days (default 14 = the agency max), conversion_addon_id} — super-admin via AgencyController.update (client_trial_seats, client_trial_days, client_trial_conversion_addon_id; admin agency Edit "Trial Client Seats").

SubscriptionModel billing fields: agency_payment_required, agency_seat_claimed (false for signups), signup_opening_credits / _at / _refunded_at, agency_trial_seat, agency_trial_days, agency_trial_converted_at, agency_trial_released_at, agency_paid_seat_at (the last two only feed the archive/delete refund — see Managing Companies), agency_trial_conversion_charge {status none|charged|pending|seat_used, attempts, last_attempt_at, last_error, addon_id}, agency_billing_active.

lib/agencyClientBilling.js: billsClientThroughAgencyStripe, trialDaysFor (≤ 730), maxTrialDays, capTrialDays, clientSubscriptionSeed — priced + agency-created → active now, expiry = now + trial days (trial seat) else agency expiry + 30 min, agency_payment_required: true, agency_trial_days: 0, 0 credits; priced + public signup → inactive, no expiry; unpriced → legacy (active until agency expiry, package credits).

Add Client (views/agency/companies/Edit.vue): "Package" select when connected ("Custom limits for this client (no charge)" or priced packages), "Start them on a free trial" + "Free trial days"; createCompany reserves a trial seat and requires the agency to stake the opening wallet. NoSubAccountsModal.vue "Or add them as a free-trial client".

Conversion (#convertTrialSeat, first invoice.paid with amount > 0): seat returned to the pool, agency_trial_converted_at set; the agency then pays us for a regular seat — a spare available_sub_accounts seat (seat_used), else the conversion_addon_id via AgencySeatHelper.purchaseSeat (charged); a failed charge → pending + agency.payment_issue: true, retried by AgencyTrialConversionChargeJob (hourly, ≤ 50 rows, < 10 attempts, ≥ 24 h apart, atomic claim). No add-on configured → none (seat free). Non-trial signups on a paid seat buy an add-on only when auto_buy_seats. A trial cancelled before converting releases its seat.

agency_client_billings​

AgencyClientBillingModel: agency_id + company_id (unique), package_id, stripe_account_id (required), stripe_customer_id, stripe_subscription_id (sparse), stripe_price_id, status (Stripe status or none), amount (major units), currency, interval, current_period_end, cancel_at_period_end, canceled_at, trial_used_at (one trial per client, ever), last_payment_at, last_payment_amount, last_invoice_url (audit-ignored), last_payment_failed_at, last_payment_error. Counts as "in use" for package deletion (lib/packageUsage.js).

Gotchas / known gaps​

  • "Stop billing" copy is wrong: the dialog says access doesn't change, but when the Stripe subscription ends #applyToClientSubscription cancels the local subscription and clamps the expiry.
  • Package trials don't apply to hand-created clients on a non-trial seat: clientSubscriptionSeed pins agency_trial_days: 0, so the Add Client hint "N days free, then charged" overstates it. Only trial-seat clients and public signups get free days.
  • Trial seat on an unpriced package takes the legacy branch: the seat is used, no trial expiry, and it can never convert through Stripe.
  • Deleting / cancelling a client never cancels its Connect subscription (CompanyController.destroy, cancelCompanySubscription don't call connectCancelSubscription) — Stripe keeps billing it on the agency account. Deleting a package doesn't archive its Stripe price.
  • headline has no field in SignupPage.vue; the page also doesn't explain that an under-funded agency wallet hides every plan.
  • Fee: admin API accepts up to 99.99 %, resolveFeePercent caps at 99.
  • Connect secrets are only in the backend secret; schedular jobs that charge on the agency account (BalanceAutoRechargeJob via AgencyWalletTopUpHelper) use the platform secret key with stripeAccount, which is present there.
  • Realtime: client-billing routes run notifyCompanyChanged, and Connect subscription updates ping company-settings-updated — see Wallet → Realtime refresh.