# 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.

> **Note:**
  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](/billing/overview#checkout-inside-your-app).

> **Note:**

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

## Quick example

```tsx
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.

| Returns                     | Description                                                                                                     |
| --------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `available`                 | `false` 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`:

```typescript
// 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

| Action              | Workspace                                                                            | A person's own plan                                            |
| ------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------- |
| Set up a card       | `POST /api/v1/public/workspaces/{workspaceId}/billing/payment-method/setup`          | `POST /api/v1/public/me/billing/payment-method/setup`          |
| Make it the default | `POST /api/v1/public/workspaces/{workspaceId}/billing/payment-method/default`        | `POST /api/v1/public/me/billing/payment-method/default`        |
| Pay an open invoice | `POST /api/v1/public/workspaces/{workspaceId}/subscription/invoices/{invoiceId}/pay` | `POST /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.

```json
{
  "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.

```bash
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..."}'
```

```json
{
  "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.

```json
{
  "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:

```json
{
  "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`.

| Code                             | Status | Route          | When                                                                                                          |
| -------------------------------- | ------ | -------------- | ------------------------------------------------------------------------------------------------------------- |
| `PAYMENT_METHOD_PAID_BY_ANOTHER` | `409`  | Setup, default | Another account pays for this plan, so its card is changed from that account's billing                        |
| `SETUP_INTENT_NOT_FOUND`         | `404`  | Default        | Not a card setup this subject started in the app, on another customer, or gone. Add the card again            |
| `SETUP_INTENT_NOT_SUCCEEDED`     | `409`  | Default        | The card was not confirmed (3-D Secure left half way, a decline). Carries `setupIntentStatus`                 |
| `INVOICE_NOT_FOUND`              | `404`  | Pay            | Not an invoice of this subject's own subscription, or the subject has none                                    |
| `INVOICE_NOT_OPEN`               | `409`  | Pay            | Voided or a draft: nothing to pay. Carries `invoiceStatus`                                                    |
| `PENDING_CHANGE_EXPIRED`         | `409`  | Pay            | The change this invoice pays for expired before it was paid. Start it again. Carries `pendingUpdateExpiresAt` |
| `PAYMENT_METHOD_NOT_FOUND`       | `404`  | Pay            | The `paymentMethodId` does not exist or is not on the invoice's customer                                      |
| `CARD_DECLINED`                  | `400`  | Pay            | The card was refused. Carries `paymentError: true` and Stripe's `declineCode` when there is one               |
| `STRIPE_NOT_CONNECTED`           | `409`  | All            | Your organization has no Stripe account connected                                                             |
| `IDEMPOTENCY_KEY_REUSED`         | `409`  | Setup, pay     | The `Idempotency-Key` was already used for a different request                                                |
| `STRIPE_PUBLISHABLE_KEY_MISSING` | `400`  | Setup          | No publishable key is saved with your payment credentials                                                     |
| `STRIPE_KEY_MODE_MISMATCH`       | `400`  | Setup          | The 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](/reference/error-codes).

## Next steps

- [Failed payments](/billing/failed-payments) - what happens when a renewal is declined
- [Managing subscriptions](/billing/managing-subscriptions) - plan changes and their previews
- [Billing overview](/billing/overview) - checkout, plan changes and the hooks
