Skip to content
BuildBase

Card payment in your app

Save a card, make it the default and pay an open invoice without leaving your app, with the routes, answers and error codes.

A customer can add a card, make it the card their plan is charged on, and pay an invoice that is waiting, all inside your app. Stripe's Payment Element takes the card, and 3-D Secure finishes in the page. Without it, the billing portal and Stripe's hosted invoice page stay the way to do these.

Before you start

Save your Stripe publishable key with your payment credentials in the console, from the same mode as the secret key, and pass loadStripe to SaaSOSProvider as in Checkout inside your app.

Note

useInAppPayment and the WorkspaceApi methods below: Requires @buildbase/sdk 1.0.0 or later.

Quick example

import { useInAppPayment } from '@buildbase/sdk/react';

function PaymentMethodCard({ workspaceId }: { workspaceId: string }) {
  const { available, addCard, element } = useInAppPayment(workspaceId);

  // Without loadStripe, keep the billing portal for card changes.
  if (!available) return null;

  return (
    <>
      <button
        onClick={async () => {
          const saved = await addCard();
          if (saved?.card)
            console.log(
              `Now paying with ${saved.card.brand} ${saved.card.last4}`
            );
        }}
      >
        Change card
      </button>
      {element}
    </>
  );
}

useInAppPayment(subject) takes a workspace id, or { user: true } for the signed-in person's own plan. Render element once in the screen: it is the card dialog.

ReturnsDescription
availablefalse without loadStripe on the provider; every action then answers unavailable
addCard()Opens the card dialog, confirms the card with Stripe and makes it the default. null when the person closes it
authenticate(action)Finishes 3-D Secure for a paymentAction the server answered: succeeded, failed or unavailable
payWithNewCard(invoiceId)Adds a card and pays the open invoice with it: succeeded, failed, unavailable or cancelled

How it works

Three calls, each the billing manager's:

  1. Set up a card. The server makes a Stripe SetupIntent on the subject's customer, card only, for later off-session charges, and answers its client secret and your publishable key.
  2. Confirm it with Stripe.js in the browser (stripe.confirmSetup). The SDK's dialog does this.
  3. Make it the default. Send the SetupIntent's id back. The card becomes the subscription's card, the Stripe customer's default when nothing else is billed on that customer, and the automatic credit top-up's card.

If the tab closes between steps 2 and 3, Stripe's setup_intent.succeeded event applies the card anyway.

To pay an invoice that is waiting (after a decline, or to settle a failed renewal), call the pay route, optionally with a card the subject saved.

On your own screen, the same calls are on WorkspaceApi:

// api: a WorkspaceApi. Pass a workspace id, or { user: true }
const setup = await api.createCardSetup(workspaceId);
// ...confirm setup.clientSecret with Stripe.js on setup.publishableKey...
const outcome = await api.setDefaultCard(workspaceId, setup.setupIntentId);

const paid = await api.payInvoice(workspaceId, invoiceId, { paymentMethodId });

createCardSetup and payInvoice take an optional idempotencyKey in their options.

Routes

ActionWorkspaceA person's own plan
Set up a cardPOST /api/v1/public/workspaces/{workspaceId}/billing/payment-method/setupPOST /api/v1/public/me/billing/payment-method/setup
Make it the defaultPOST /api/v1/public/workspaces/{workspaceId}/billing/payment-method/defaultPOST /api/v1/public/me/billing/payment-method/default
Pay an open invoicePOST /api/v1/public/workspaces/{workspaceId}/subscription/invoices/{invoiceId}/payPOST /api/v1/public/me/subscription/invoices/{invoiceId}/pay

Each takes the person's session. The workspace routes need permission to manage the workspace's billing (403 without it); the /me routes act on the signed-in person's own subscription. All six share a limit of 10 requests a minute (429 past it).

Set up a card

Body: {} (any field is refused with 400). Takes an optional Idempotency-Key header: a retried click with the same key gets the same SetupIntent.

{
  "success": true,
  "setupIntentId": "seti_1Q...",
  "clientSecret": "seti_1Q..._secret_...",
  "publishableKey": "pk_live_..."
}

The client secret is answered to the caller only, and never logged or stored. When the subject has no Stripe customer yet, one is created.

Make it the default

Body: { "setupIntentId": "seti_..." }, required.

curl -X POST "https://api.console.buildbase.app/api/v1/public/workspaces/$WORKSPACE_ID/billing/payment-method/default" \
  -H "x-session-id: $SESSION_ID" \
  -H "Content-Type: application/json" \
  -d '{"setupIntentId": "seti_1Q..."}'
{
  "success": true,
  "superseded": false,
  "paymentMethod": {
    "brand": "visa",
    "last4": "4242",
    "expMonth": 12,
    "expYear": 2030
  },
  "appliedTo": { "subscription": true, "customer": true, "autoTopUp": false }
}
  • superseded: true: a card saved more recently (in another tab, say) is already the default, so this one was not applied, and appliedTo is all false. The newest card always wins.
  • appliedTo.customer is false when another workspace or person is billed on the same Stripe customer: only this subject's subscription changes.
  • appliedTo.autoTopUp is true when an automatic credit top-up now charges this card.

The SetupIntent must be one this route's setup call made, for this organization and subject, on its customer, and confirmed.

Pay an open invoice

Body: { "paymentMethodId": "pm_..." }, optional; without it, Stripe charges the subscription's default card. Takes an optional Idempotency-Key header.

{
  "success": true,
  "paid": true,
  "invoice": { "id": "in_1Q...", "status": "paid", "amount_due": 1250 }
}

amount_due is in the currency's minor unit. An invoice already paid answers paid: true too, so a retry after the payment landed is not an error. When the card asks for 3-D Secure, the answer is paid: false with paymentAction, which authenticate finishes in the page:

{
  "success": true,
  "paid": false,
  "invoice": { "id": "in_1Q...", "status": "open", "amount_due": 1250 },
  "paymentAction": {
    "invoiceId": "in_1Q...",
    "clientSecret": "pi_..._secret_...",
    "publishableKey": "pk_live_...",
    "status": "requires_action"
  }
}

paymentAction also carries declineCode when the last attempt failed. The invoice must belong to the subject's own subscription; an id that does not start with in_ is 404 with no code.

Errors

Refusals carry success: false, a code and a message.

CodeStatusRouteWhen
PAYMENT_METHOD_PAID_BY_ANOTHER409Setup, defaultAnother account pays for this plan, so its card is changed from that account's billing
SETUP_INTENT_NOT_FOUND404DefaultNot a card setup this subject started in the app, on another customer, or gone. Add the card again
SETUP_INTENT_NOT_SUCCEEDED409DefaultThe card was not confirmed (3-D Secure left half way, a decline). Carries setupIntentStatus
INVOICE_NOT_FOUND404PayNot an invoice of this subject's own subscription, or the subject has none
INVOICE_NOT_OPEN409PayVoided or a draft: nothing to pay. Carries invoiceStatus
PENDING_CHANGE_EXPIRED409PayThe change this invoice pays for expired before it was paid. Start it again. Carries pendingUpdateExpiresAt
PAYMENT_METHOD_NOT_FOUND404PayThe paymentMethodId does not exist or is not on the invoice's customer
CARD_DECLINED400PayThe card was refused. Carries paymentError: true and Stripe's declineCode when there is one
STRIPE_NOT_CONNECTED409AllYour organization has no Stripe account connected
IDEMPOTENCY_KEY_REUSED409Setup, payThe Idempotency-Key was already used for a different request
STRIPE_PUBLISHABLE_KEY_MISSING400SetupNo publishable key is saved with your payment credentials
STRIPE_KEY_MODE_MISMATCH400SetupThe publishable key is from the other mode (live or test) than the secret key

In the SDK, IN_APP_PAYMENT_CODE holds the first eight, and isCardFormUnavailable(err) is true when the card form cannot be used here (an older server that answers 404, or Stripe keys that cannot open Stripe.js), so your screen can fall back to the billing portal. For handling refusals in general, see Error codes.

Next steps