# Commerce from your server

Read and change your app's items, orders, refunds, subscriptions, bookings and more from your backend with an org API key.

The server client's `commerce` calls are your app's own backend acting on
[selling](/billing/selling): list items for a seller, read an order before
serving what it bought, refund, cancel a subscription, ship, check a licence
key. They call `/api/v1/server/commerce/*` with an **org API key**, and see
every seller and buyer in your app.

> **Note:**
  Create an API role under **Settings > API roles** with the `marketplace_*`
  permissions you need (the table below), then an API key with that role
  under **Settings > API keys**. An app-server key is enough. Selling must be
  set up under **Billing > Selling**.

The `commerce` calls ship in `@buildbase/sdk` 1.2.0. This page lists them as of 1.5.0; on an older version a call may be missing.

## Quick example

```typescript title="lib/commerce.ts"
import { BuildBaseApiError, createServerClient } from '@buildbase/sdk/server';

const bb = createServerClient({
  serverUrl: 'https://api.console.buildbase.app',
  apiToken: process.env.BUILDBASE_API_TOKEN!, // <orgId>:<secret>
});

export async function refundOrder(orderId: string) {
  const order = await bb.commerce.orders.get(orderId);
  if (order.paymentStatus !== 'paid') return null;
  try {
    const { refund } = await bb.commerce.orders.refund(
      orderId,
      { reason: 'Requested by the buyer' }, // all that is left
      { idempotencyKey: `refund-${orderId}-1` }
    );
    return refund;
  } catch (err) {
    if (err instanceof BuildBaseApiError && err.code === 'REFUND_FAILED') {
      return null; // Stripe refused it; nothing was returned
    }
    throw err;
  }
}
```

Amounts are minor units: `4500` is $45.00.

## Retrying a write

Every write takes `{ idempotencyKey, signal, timeoutMs }` last. Left out,
the SDK makes a key per call; either way every error the call throws
carries it (`err.idempotencyKey`). To retry after a timeout or a network
error, send the same request with the same key: the platform answers with
the first request's result, so a refund is made once
([retrying a write safely](/billing/orders#retrying-a-write-safely)).

A write that moves money (a refund, a charged part, a cancel or change, a
bought label) waits `moneyTimeoutMs`, 60 seconds by default, instead of the
client's `timeoutMs`. One that gets no answer in time throws
`BuildBaseTimeoutError`: its outcome is unknown, so retry it with
`err.idempotencyKey` or read the order before trying again. Never retry it
under a new key.

## Method reference

| Namespace                   | Methods                                                                                                                                                                                         | Permission                                                                |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `commerce.items`            | `list`, `get`, `create`, `createMany` (up to 50, one result each), `update`, `publish`, `unlist`, `archive`, `approve`, `reject(id, reason)`, `delete`, `previewCalendarMove`, `moveToCalendar` | `marketplace_items`                                                       |
| `commerce.orders`           | `list`, `get`, `export`, `refund(id, input?)`, `fulfil(id, lineKey, input?)`, `chargePart(id, index)`, `stopParts(id, { revoke? })`                                                             | `marketplace_orders`; a refund also needs create on `marketplace_refunds` |
| `commerce.subscriptions`    | `list`, `get`, `cancel`, `resume`, `previewChange(id, variantId)`, `change(id, variantId)`                                                                                                      | `marketplace_orders`                                                      |
| `commerce.bookings`         | `list`, `get`, `cancel(id, input?)`, `reschedule(id, slotStart)`, `setAttendance(id, attendance)`                                                                                               | `marketplace_orders`                                                      |
| `commerce.calendars`        | `list`, `get`, `create`, `update`, `delete`                                                                                                                                                     | `marketplace_items`                                                       |
| `commerce.affiliates`       | `list`, `get`, `approve`, `pause`, `resume`, `ban`                                                                                                                                              | `marketplace_affiliate_programs`                                          |
| `commerce.commissions`      | `list`                                                                                                                                                                                          | `marketplace_affiliate_programs`                                          |
| `commerce.shipments`        | `list(orderId)`, `get`, `create`, `setStatus`, `label` (the label file, a `Blob`)                                                                                                               | `marketplace_orders`                                                      |
| `commerce.shippingRates`    | `list(sellerId)`, `get`, `create`, `update`, `delete`                                                                                                                                           | `marketplace_items`                                                       |
| `commerce.returns`          | `list(orderId)`, `get`, `approve`, `reject`, `refund`                                                                                                                                           | `marketplace_orders`; a refund also `marketplace_refunds`                 |
| `commerce.shippingSettings` | `get(sellerId)`, `save(sellerId, input)`                                                                                                                                                        | `marketplace_sellers`                                                     |
| `commerce.grants`           | `list`, `get`, `access({ userId, resourceType, resourceId })`, `revoke(id, reason)`, `deactivate(id, { unit, instance })`                                                                       | `marketplace_grants`                                                      |
| `commerce.licenses`         | `validate(key, instance?)`, `activate(key, instance)`, `deactivate(key, instance)`                                                                                                              | `marketplace_grants`                                                      |
| `commerce.files`            | `list(sellerId)`, `startUpload`, `completeUpload`, `get`, `delete`                                                                                                                              | `marketplace_releases`                                                    |
| `commerce.releases`         | `list(sellerId)`, `create`, `get`, `update`, `publish`, `delete`                                                                                                                                | `marketplace_releases`                                                    |

A read needs read on the permission, a write update (create for a refund).
Each call takes `{ signal, timeoutMs }` last, and each write the
`idempotencyKey` too. What each one does is on its feature's page:
[items](/billing/items), [orders](/billing/orders#your-server),
[bookings](/billing/bookings), [affiliates](/billing/affiliates),
[shipping](/billing/shipping).

## Before serving what was bought

Ask the platform, not your own copy, before you serve an object a buyer
paid for:

```typescript
const { hasAccess, until } = await bb.commerce.grants.access({
  userId,
  resourceType: 'course',
  resourceId: courseId,
});
```

Keep your own copy in step with the `order.*` and `grant.*` webhook events
([handling disputes on your server](/billing/orders#handling-disputes-on-your-server)
has a handler).

## Which credential each route takes

| Routes                       | Credential                                                                                                                                                                                                                                                      |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/api/v1/server/commerce/*`  | An org API key, app-server or admin, whose role holds the permission above. A session token gets `403` `API_KEY_REQUIRED`                                                                                                                                       |
| `/api/marketplace/*`         | The console's own routes: a console session, or an **admin key** (an API key issued as an admin key, with the owner or admin role, [key types](/reference/admin-api#key-types)). An app-server key and your app user's session get `403` `ADMIN_SCOPE_REQUIRED` |
| `/api/v1/public/*` (the SDK) | Your app user's session, as a buyer or a seller ([as the signed-in person](/billing/orders#as-the-signed-in-person))                                                                                                                                            |

So your backend uses this client and an app-server key; it does not need,
and should not hold, an admin key for selling.

## Errors

A refused call throws `BuildBaseApiError` with the HTTP `status` and the
server's `code` (`ORDER_NOT_FOUND`, `REFUND_NOT_ALLOWED`, `CHECKOUT_REFUSED`,
...); `err.body` holds `problems` when there are fields to fix. Every
commerce code is under [error codes](/reference/error-codes#commerce).

## Next steps

- [Checkout and orders](/billing/orders) - what an order holds and its events.
- [Send transactional email](/server-sdk/sending-email) - a receipt of your own on `order.paid`.
- [Error codes](/reference/error-codes#commerce) - every commerce code.
