> ## Documentation Index
> Fetch the complete documentation index at: https://docs.scrip.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Start with https://docs.scrip.dev/agents.md and https://docs.scrip.dev/which-endpoints-you-need.md. Your application only needs a few API calls as users earn and spend (`POST /v1/events`, balance/history reads, and redemptions); program setup happens in the dashboard or setup scripts.
> Use `https://api-sandbox.scrip.dev` with `sk_test_` keys for testing, and `https://api.scrip.dev` with `sk_live_` keys for production. Keep API keys on your server.
> Pass your own user ID as `external_id` on events and prefix it with `ext:` in participant URL paths (e.g., `GET /v1/participants/ext:user_123/balances`). By default (`on_unknown_participant: CREATE`), the first event for a new `external_id` creates and enrolls the participant automatically.
> Events process asynchronously: `POST /v1/events` returns `202 Accepted` when queued, and rules evaluate in the background. Pass an `idempotency_key` (such as an order ID) on every event, and wait for the `event.completed` webhook or poll `GET /v1/events/{event_id}` before reading updated balances.
> Connect the hosted MCP server at https://mcp.scrip.dev/mcp (OAuth, defaults to Sandbox) to inspect programs, validate and simulate rules, and trace events. Append `.md` to any docs URL for Markdown, or fetch https://docs.scrip.dev/openapi.json for full endpoint schemas.

# Pay with points at checkout with Stripe

> Let a shopper pay part of a Stripe order with points. Scrip holds the points until your server reports the Stripe payment result.

Let shoppers pay part of a Stripe order with points and the rest by card. On a \$100 cart, a shopper can apply \$20 in points while Stripe charges \$80.

When a shopper applies points, Scrip places a temporary hold on them so they cannot be spent elsewhere. When the Stripe payment succeeds, your server completes the [pending redemption](https://docs.scrip.dev/guides/redemption-lifecycle.md) and Scrip spends the held points. If the payment is cancelled or the hold expires, Scrip releases the points back to the shopper's balance.

Your server makes every Stripe API call. Scrip never holds your Stripe keys and never calls Stripe directly. `@scrip-systems/checkout-sdk` gives your server methods that manage Scrip holds and return updated parameters for your Stripe calls. `@scrip-systems/checkout-widget` provides an optional UI control for your checkout page.

## Choose a path

Start by picking the Stripe integration your checkout uses:

| Stripe integration | How points apply | Where to go |
| - | - | - |
| **PaymentIntents** (you host the checkout form) | Scrip lowers the PaymentIntent `amount` directly | [Quickstart](#quickstart) below |
| **Checkout Sessions** (Stripe hosts the checkout page) | Scrip builds a one-time Stripe coupon for the session | [Checkout Sessions](https://docs.scrip.dev/guides/pay-with-points-with-stripe-checkout-sessions.md) |

Jump directly to a specific task:

| What you want | Where to go |
| - | - |
| Show a points control on your checkout page | [Add the widget](https://docs.scrip.dev/guides/checkout-points-widget.md#add-the-widget) |
| Build your own points UI | [Build your own control](https://docs.scrip.dev/guides/checkout-points-widget.md#build-your-own-control) |
| Handle an order paid in full with points | [Orders that points pay in full](#orders-that-points-pay-in-full) |
| Return points after a partial refund | [Return points after a partial refund](#return-points-after-a-partial-refund) |
| Use points alongside promotion codes on Checkout Sessions | [Promotion codes on Checkout Sessions](https://docs.scrip.dev/guides/pay-with-points-with-stripe-checkout-sessions.md#promotion-codes-on-checkout-sessions) |
| Debug a failed or unexpected payment | [If something goes wrong](#if-something-goes-wrong) |

## Set up

Set `value_per_unit` on your points asset so Scrip knows what one point is worth in your Stripe checkout currency. For example, if 100 points equal \$1.00, set one point to `0.01` USD:

```bash theme={null}
PATCH /v1/assets/a3bb189e-8bf9-4c8b-9be0-6b5d2f4e7a02
```

```json theme={null}
{
  "value_per_unit": {
    "amount": "0.01",
    "currency": "USD"
  }
}
```

Once `value_per_unit` is set, participant balances include their money value in `available_value`, and redemptions accept a `face_value` in money. See [Value per unit](https://docs.scrip.dev/guides/asset-configuration.md#value-per-unit) and [Redeem a price in money](https://docs.scrip.dev/guides/redemptions.md#redeem-a-price-in-money). Make sure the asset is linked to your program and the participant has a balance.

## Quickstart

Finish [Set up](#set-up) first. Integrating PaymentIntents takes three steps.

**1. Install the packages**

```bash theme={null}
npm install @scrip-systems/checkout-sdk stripe
```

**2. Hold the points and lower the PaymentIntent amount**

Call `scrip.stripe.applyPoints` before creating the PaymentIntent. It holds the points in Scrip and returns updated PaymentIntent parameters with a lower `amount` and the hold IDs stored in `metadata`.

```ts theme={null}
import Stripe from "stripe";
import { Scrip } from "@scrip-systems/checkout-sdk";

const scrip = new Scrip({
  apiKey: process.env.SCRIP_API_KEY,
  baseUrl: process.env.SCRIP_BASE_URL,
});
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function createPaymentIntent(cart: { id: string; shopperId: string; totalMinor: number }) {
  // What the card pays when no points are applied
  const fullPrice: Stripe.PaymentIntentCreateParams = {
    amount: cart.totalMinor,
    currency: "usd",
    allowed_payment_method_types: ["card"],
    metadata: { cart_id: cart.id },
  };

  // Hold $20.00 of points and lower the Stripe charge
  const result = await scrip.stripe.applyPoints({
    participantId: `ext:${cart.shopperId}`,
    programId: "8f14e45f-ceea-4e70-9df8-2a7d1b3c9f01",
    assetId: "a3bb189e-8bf9-4c8b-9be0-6b5d2f4e7a02",
    cartId: cart.id,
    faceValue: { amount_minor: 2000, currency: "usd" },
    paymentIntent: fullPrice,
  });

  // Handle other statuses (including fully_covered, which already placed a hold)
  if (result.status !== "applied") return result;

  const intent = await stripe.paymentIntents.create(result.params, {
    idempotencyKey: `pi-${cart.id}-${result.redemptionIds.join("-")}`,
  });
  return {
    status: "applied",
    clientSecret: intent.client_secret,
    redemptionIds: result.redemptionIds,
  };
}
```

In this request, `participantId` identifies the shopper in Scrip (`ext:` followed by your shopper ID, or the Scrip participant UUID), `programId` and `assetId` specify the program and points asset, and `faceValue` is the discount in minor currency units (`2000` is \$20.00 in USD cents).

For a \$100.00 cart, `result.params.amount` is `8000`. Save `result.redemptionIds` on your cart record so you can pass them back if the shopper changes their cart, and block edits once the order is paid. See [Refuse changes to a paid cart](#refuse-changes-to-a-paid-cart).

**3. Forward Stripe webhooks to handleEvent**

After verifying the Stripe webhook signature, pass the event to `scrip.stripe.handleEvent`. Subscribe your Stripe webhook endpoint to `payment_intent.succeeded` and `payment_intent.canceled`.

```ts theme={null}
export async function stripeWebhook(rawBody: string | Buffer, signature: string): Promise<void> {
  const event = stripe.webhooks.constructEvent(rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET!);

  // Completes the hold on success, or releases points on cancel.
  // Throws on retryable failures so Stripe delivers the event again.
  await scrip.stripe.handleEvent(event);

  // Run your existing order fulfillment logic here
}
```

## Use one environment

Scrip production and sandbox have separate API addresses, keys, and data. See [Environments](https://docs.scrip.dev/environments.md). Match your Scrip and Stripe credentials to the same environment:

| Setting | Sandbox | Production |
| - | - | - |
| Scrip `baseUrl` | `https://api-sandbox.scrip.dev` | `https://api.scrip.dev` |
| Scrip API key | Starts with `sk_test_` | Starts with `sk_live_` |
| Stripe secret key | Test-mode key | Live-mode key |
| Stripe webhook secret | Test-mode endpoint secret | Live-mode endpoint secret |

Always pass `baseUrl` explicitly and fail on startup if it is missing. Omitting `baseUrl` defaults to production.

The checkout widget holds no API URL or keys. It renders whatever your server passes to it, so it needs no environment configuration.

## Hold points and lower the charge

`scrip.stripe.applyPoints` takes the `PaymentIntentCreateParams` you would send without points, places a hold on the requested points, and returns updated parameters with the lowered charge:

| Option | Description |
| - | - |
| `participantId` | The shopper's Scrip participant UUID, or `ext:` followed by your own ID for the shopper. Use the same format consistently. |
| `programId`, `assetId` | The program and points asset to redeem from. |
| `cartId` | Your unique ID for this order. Never reuse a `cartId` across orders. |
| `faceValue` | The money value of the points to apply, in minor units (such as cents for USD). |
| `paymentIntent` | The `Stripe.PaymentIntentCreateParams` you would send with no points applied. `amount` is the full order total. |
| `expectedAmount` | Optional. The point count you showed the shopper. If the asset's `value_per_unit` changed since then, Scrip holds nothing and returns `price_changed`. |
| `ttlSeconds` | Optional. How long the hold lasts, from `60` to `31536000` (365 days). Defaults to `3600` (1 hour). |
| `description` | Optional. Label recorded on the redemption and ledger entries. Defaults to `Order <cartId>`. |
| `replaces` | Optional. The `redemptionIds` you saved earlier for this cart. Always pass them on updates so unchanged requests reuse the existing hold and changed amounts swap it cleanly. See [Cart changes and page refreshes](#cart-changes-and-page-refreshes). |

To combine points from multiple assets on one order, pass `points` (an array of `{ assetId, faceValue }`) instead of `assetId` and `faceValue`. Scrip places one hold per asset.

When `applyPoints` succeeds, `result.params` preserves all of your original PaymentIntent fields and updates two of them:

* `amount` becomes the order total minus the applied points.
* `metadata.scrip_redemption_ids` records the held redemption IDs.

Pass `result.params` directly to `stripe.paymentIntents.create`. When updating an existing PaymentIntent with `stripe.paymentIntents.update`, pass only `{ amount: result.params.amount, metadata: result.params.metadata }`, because Stripe's update endpoint does not accept create-only fields.

Always pass an `idempotencyKey` to `stripe.paymentIntents.create` so retries or double-clicks do not create duplicate PaymentIntents. If a PaymentIntent is cancelled and you create a new one for the same cart, increment a counter on the cart (`cart.cancelledIntents`) and include it in the key (for example, `pi-${cart.id}-${cart.cancelledIntents}-${cart.redemptionIds.join("-") || "full"}`), because Stripe returns the cancelled PaymentIntent if you reuse its idempotency key.

A hold can end earlier than `ttlSeconds` if your program sets a shorter `pending_redemption_ttl`, or if the held points expire sooner. Read `result.expiresAt` from the response rather than calculating the deadline yourself. Holds cannot be extended. See [Use the returned deadline](https://docs.scrip.dev/guides/redemption-lifecycle.md#use-the-returned-deadline).

Bank debits and other async payment methods can stay `processing` longer than a 1-hour hold, so start by restricting points checkouts to cards (`allowed_payment_method_types: ["card"]`, or `payment_method_types` on older Stripe API versions). If you support slower payment methods, set a longer `ttlSeconds` (up to 365 days).

### Read the result

`applyPoints` returns a `status` field for every expected checkout outcome instead of throwing:

| Status | Points held | What your checkout flow does |
| - | - | - |
| `applied` | Yes | Save `redemptionIds` on your cart and charge `params.amount` on Stripe. |
| `fully_covered` | Yes | Points cover the full order, so skip Stripe. See [Orders that points pay in full](#orders-that-points-pay-in-full). |
| `price_changed` | No new hold | Refresh the points price with `priceFaceValue`, ask the shopper to confirm, and retry with the new `expectedAmount`. If `existingRedemptionIds` is returned, keep passing those IDs in `replaces`. |
| `insufficient_points` | No | Prompt for a smaller amount, or hide the points control if the shopper has no balance. `availablePoints` reports the current balance when available. |
| `below_minimum_charge` | No | The remaining card charge would fall under Stripe's minimum. `maxFaceValueMinor` gives the largest discount (in minor units) that keeps the card charge valid. Offer that amount or cover the full order with points. |
| `already_completed` | No new hold | Show the order as paid. Returned if this cart's hold already completed, if an ID in `replaces` already completed (`reason: "replaced"`), or if you reused a `cartId`. |
| `hold_conflict` | No new hold | The cart already has a hold created with a different `ttlSeconds` or `description`. Pass your saved IDs in `replaces` and keep both options consistent for a given cart. |

To calculate the exact point count for a money amount before calling `applyPoints`, use `priceFaceValue`. It matches the API's rounding rules:

```ts theme={null}
import { priceFaceValue } from "@scrip-systems/checkout-sdk";

const asset = await scrip.assets.get({ path: { asset_id: "a3bb189e-8bf9-4c8b-9be0-6b5d2f4e7a02" } });
const points = priceFaceValue({ faceValue: { amount_minor: 2000, currency: "usd" }, asset }); // "2000"
```

Compare point values as numbers rather than strings. Invalid inputs (such as mismatched currencies or a `replaces` ID belonging to another participant) throw `TypeError` or `RangeError` before any hold is placed. Unexpected API failures throw `ScripError`. See [Errors](https://docs.scrip.dev/errors.md).

The SDK checks remaining card charges against a built-in table of Stripe currency minimums (for example, `50` cents for USD). To override those minimums, create custom helpers with `createStripeHelpers`:

```ts theme={null}
import { createStripeHelpers } from "@scrip-systems/checkout-sdk";

const stripeHelpers = createStripeHelpers(scrip, { minimumCharges: { usd: 100 } });
// Pass {} to disable the minimum-charge check
```

## Complete or release the points

`scrip.stripe.handleEvent` reads `metadata.scrip_redemption_ids` from the PaymentIntent or Checkout Session inside the Stripe webhook event. If the event has no `scrip_redemption_ids` or is an event type Scrip does not act on, `handleEvent` returns `{ handled: false }`.

| Stripe event | What `handleEvent` does |
| - | - |
| `payment_intent.succeeded` | Completes each held redemption, recording `provider: "stripe"` and the PaymentIntent ID as `order_id`. |
| `payment_intent.canceled` | Releases the held points back to the shopper's balance. |
| `payment_intent.payment_failed`, `payment_intent.processing` | Does nothing (`{ handled: false }`). The hold stays active so the shopper can retry payment. |

For Checkout Session webhook events, see [Pay with points with Stripe Checkout Sessions](https://docs.scrip.dev/guides/pay-with-points-with-stripe-checkout-sessions.md#hold-points-and-start-a-session). If both a PaymentIntent event and a Checkout Session event arrive for the same payment, the second delivery is a safe no-op.

Stripe delivers webhook events in your account's configured API version, which can differ from the version your SDK requests use. `handleEvent` handles both shapes.

### Act on what `handleEvent` returns

When a payment succeeds, `handleEvent` completes each redemption. Even if the original hold expired or was released during a cart edit, Scrip attempts to redeem the same points again so the shopper cannot receive a discounted order for free.

`handleEvent` returns a per-redemption `outcome` for every hold in `results`. **Two outcomes require your store to take recovery action:**

| Outcome | Points spent | What your store does |
| - | - | - |
| `points_unavailable` | No. The hold ended and the points could not be redeemed again (`reason` holds the error code, such as `insufficient_funds`, and `requestId` identifies the request for support). | Record the shortfall and decide how to resolve it: collect the missing balance, issue a partial refund, or absorb the difference. The result includes `participantId`, `assetId`, `points`, `faceValue`, `holdStatus`, and `failureReason`. |
| `completed_by_other_payment` | Yes, by a different Stripe payment (`otherOrderId`). | Refund one of the two payments. |

All other outcomes represent normal completion, cancellation, or safe duplicate deliveries:

| Outcome | Points spent | What your store does |
| - | - | - |
| `completed` | Yes, by this call | Fulfill the order. |
| `already_completed` | Yes, earlier, for this same payment | No action needed. |
| `retaken` | Yes, by this call. The original hold had ended, so Scrip redeemed the points under a new redemption (`newRedemptionId`). | Fulfill the order. If a cart edit created a newer PaymentIntent, cancel that newer PaymentIntent. |
| `cancelled` | No. The held points were released. | Clear the saved hold IDs from the cart. |
| `already_released` | No. The hold had already ended. | No action needed. |
| `kept_completed` | Yes, earlier. A cancel event arrived after the redemption already completed. | No action needed; the redemption stays completed. |
| `unknown_redemption` | No. The ID in metadata does not match a redemption (`reason` is `not_found` or `malformed_id`). | Check what wrote `scrip_redemption_ids` into Stripe metadata. |

Because retrying cannot change any of these outcomes, `handleEvent` returns them instead of throwing. Your webhook endpoint returns `200`, so handle `points_unavailable` and `completed_by_other_payment` explicitly:

```ts theme={null}
export async function stripeWebhook(rawBody: string | Buffer, signature: string): Promise<void> {
  const event = stripe.webhooks.constructEvent(rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET!);
  const outcome = await scrip.stripe.handleEvent(event);

  if (outcome.handled) {
    for (const r of outcome.results) {
      if (r.outcome === "points_unavailable" || r.outcome === "completed_by_other_payment") {
        await recordShortfall(event, r); // Your own alert or ops queue
      }
    }
  }

  if (event.type === "payment_intent.succeeded") {
    const intent = event.data.object as Stripe.PaymentIntent;
    await fulfillOrder(intent.id); // Your own idempotent fulfillment step
    const paidCart = await loadCart(intent.metadata?.cart_id ?? "");
    if (paidCart) paidCart.paid = true;
  }

  if (event.type === "payment_intent.canceled") {
    const intent = event.data.object as Stripe.PaymentIntent;
    const cart = await loadCart(intent.metadata?.cart_id ?? "");
    if (cart && cart.intentId === intent.id) {
      cart.intentId = undefined;
      cart.clientSecret = undefined;
      cart.cancelledIntents += 1; // Forces a fresh Stripe idempotency key on the next create
      cart.redemptionIds = [];
      cart.card = fullPrice(cart);
    }
  }
}
```

When a payment is cancelled, clear `intentId` and `redemptionIds` on your cart record so a subsequent checkout attempt starts clean.

`handleEvent` throws on errors that should be retried: network failures, timeouts, `StripeDeadlineError`, `5xx` or `429` responses, and `401`/`403` responses (so you can fix a rotated or misconfigured key without losing events). Let those errors propagate so your webhook returns a `5xx` and Stripe retries delivery.

### Make your order step safe to run twice

Stripe can deliver the same webhook event more than once, out of order, or concurrently. Two concurrent deliveries can both return `completed`, while Scrip spends the points only once. Make your `fulfillOrder` step idempotent by keying it on the PaymentIntent ID or Stripe event ID and skipping work you already completed.

These SDK calls are safe to retry: `applyPoints` with the same cart and amount, `handleEvent` with the same event, `completeWithoutPayment`, `removePoints`, and `scrip.redemptions.reverse` with the same `idempotencyKey`.

### Timeouts

`handleEvent` enforces built-in timeouts so webhook handlers do not hang:

| Option | Default | Behavior |
| - | - | - |
| `eventDeadlineMs` | `8000` (8s) | Total budget for `handleEvent`. Exceeding it throws `StripeDeadlineError`. |
| `eventCallTimeoutMs` | `5000` (5s) | Timeout per Scrip API request (with one retry). |
| `insufficientFundsWaitMs` | `1000` (1s) | Maximum time to wait for another expiring hold to release points before returning `points_unavailable`. |

Run `handleEvent` inline if your webhook handler can wait up to 8 seconds. Otherwise, verify and enqueue the event, return `200` immediately, and call `handleEvent` from a background worker. To customize timeouts, pass them to `createStripeHelpers`:

```ts theme={null}
import { createStripeHelpers } from "@scrip-systems/checkout-sdk";

const stripeHelpers = createStripeHelpers(scrip, { eventDeadlineMs: 4000 });
```

## Cart changes and page refreshes

Store cart state on your server rather than trusting totals or hold IDs from the browser. The examples below assume a server-side `Cart` record and two small app helpers:

```ts theme={null}
interface Cart {
  id: string;
  shopperId: string;
  participantId: string; // "ext:" followed by your shopper ID
  currency: string; // Lowercase ISO 4217 code for Stripe, such as "usd"
  totalMinor: number; // Full order total in minor units (cents for USD)
  redemptionIds: string[]; // Hold IDs from the latest applyPoints call
  card: Stripe.PaymentIntentCreateParams; // Current PaymentIntent parameters for the card portion
  intentId?: string;
  clientSecret?: string;
  cancelledIntents: number;
  paid: boolean;
}

const fullPrice = (cart: Cart): Stripe.PaymentIntentCreateParams => ({
  amount: cart.totalMinor,
  currency: cart.currency,
  allowed_payment_method_types: ["card"],
  metadata: { cart_id: cart.id },
});

async function syncIntent(cart: Cart) {
  if (!cart.intentId) return;
  await stripe.paymentIntents.update(cart.intentId, {
    amount: cart.card.amount,
    metadata: {
      ...cart.card.metadata,
      // Empty string removes the metadata key on Stripe when no points are held
      scrip_redemption_ids: cart.card.metadata?.scrip_redemption_ids ?? "",
    },
  });
}
```

Always pass your saved `cart.redemptionIds` in `replaces` when calling `applyPoints`:

* **Unchanged request (page refresh, double-click, or timeout retry):** Scrip returns the existing holds without placing a second hold or releasing anything.
* **Changed points amount:** Scrip releases the saved holds and places a new hold for the updated amount.
* **Changed cart total with the same points amount:** Scrip keeps the existing holds and updates `result.params.amount` to match the new total.

Save `result.redemptionIds` after every successful call, even when the same holds are returned. On a page refresh, reuse the cart's existing PaymentIntent instead of creating a new one.

When the shopper changes their points amount, call `applyPoints` with `replaces` and update the existing PaymentIntent:

```ts theme={null}
await requireOpen(cart); // Defined in "Refuse changes to a paid cart" below

const result = await scrip.stripe.applyPoints({
  participantId: cart.participantId,
  programId: "8f14e45f-ceea-4e70-9df8-2a7d1b3c9f01",
  assetId: "a3bb189e-8bf9-4c8b-9be0-6b5d2f4e7a02",
  cartId: cart.id,
  faceValue: { amount_minor: 1000, currency: cart.currency }, // Shopper changed $20 to $10
  replaces: cart.redemptionIds, // Always read from your server, never the browser
  paymentIntent: fullPrice(cart),
});

if (result.status === "applied") {
  cart.redemptionIds = result.redemptionIds;
  cart.card = result.params;
  await syncIntent(cart);
}
```

Always source `replaces` from your server's cart record, never from client input. The SDK verifies that each ID belongs to the same participant and program, throwing `TypeError` otherwise. Process one cart update at a time per cart (for example, with a per-cart lock) so concurrent clicks cannot race.

Do not reuse hold IDs across a cancelled PaymentIntent: its `payment_intent.canceled` webhook releases any holds listed in its metadata. Keep a one-to-one mapping between an active hold and its PaymentIntent.

### Refuse changes to a paid cart

Once a cart's card payment succeeds or points cover the order in full, treat the cart as locked. Check that the cart is still open at the top of every mutating route (creating or updating the PaymentIntent, applying or removing points, changing items, or placing a points-only order). Blocking updates early also prevents Stripe's `400 payment_intent_unexpected_state` error when updating a PaymentIntent that has already succeeded.

Because the shopper's browser can return from Stripe before your webhook arrives, check Stripe directly when `cart.paid` is still `false`:

```ts theme={null}
async function isPaid(cart: Cart): Promise<boolean> {
  if (!cart.paid && cart.intentId) {
    const intent = await stripe.paymentIntents.retrieve(cart.intentId);
    if (intent.status === "succeeded") cart.paid = true;
  }
  return cart.paid;
}

async function requireOpen(cart: Cart): Promise<void> {
  if (await isPaid(cart)) {
    throw new OrderPaidError(); // Return 409 from your route and show the order confirmation
  }
}
```

This guard only protects the cart from edits; your webhook still completes the redemption and fulfills the order. Include `paid` in the cart payload sent to your checkout page so the UI renders the confirmation screen with no points control or **Pay** button.

## Remove points

When a shopper removes points from their cart, call `scrip.stripe.removePoints`. It cancels each held redemption, releases the points back to the shopper's balance, and returns `result.params` with the full card amount and `metadata.scrip_redemption_ids` set to `""` (which instructs Stripe to delete that metadata key while keeping your other metadata).

```ts theme={null}
await requireOpen(cart);
if (!cart.redemptionIds.length) return { status: "removed" }; // Nothing is held, and removePoints requires at least one ID

const result = await scrip.stripe.removePoints({
  redemptionIds: cart.redemptionIds,
  paymentIntent: fullPrice(cart),
});

if (result.status === "already_completed") {
  return { status: "error", message: "These points are already used for a paid order." };
}

cart.redemptionIds = [];
cart.card = result.params;
await syncIntent(cart);
```

Always clear `scrip_redemption_ids` on the PaymentIntent when releasing a hold. If a PaymentIntent still references a released hold when it succeeds, `handleEvent` will redeem those points again.

Conversely, if you need to cancel a PaymentIntent while keeping its hold (for example, when points now cover the full order), clear `scrip_redemption_ids` on the PaymentIntent before cancelling it so the `payment_intent.canceled` webhook does not release the hold.

Calling `removePoints` on an already-released hold is a safe no-op, so retries are safe. If a hold has already completed, `removePoints` releases nothing and returns `{ status: "already_completed" }` with no `params`. To return points after completion, reverse the redemption instead.

## Orders that points pay in full

When points cover the entire cart total, `applyPoints` places the hold and returns `status: "fully_covered"`. No Stripe payment or webhook occurs. When the shopper places the order, call `scrip.stripe.completeWithoutPayment` to spend the held points.

If the cart already had a PaymentIntent referencing that hold, clear `scrip_redemption_ids` on the PaymentIntent before cancelling it (as shown in [Add the widget](https://docs.scrip.dev/guides/checkout-points-widget.md#add-the-widget)), or the `payment_intent.canceled` webhook will release the hold you are about to complete.

```ts theme={null}
await requireOpen(cart);

const { results } = await scrip.stripe.completeWithoutPayment({
  redemptionIds: cart.redemptionIds,
});

const ok = results.every(
  (r) => r.outcome === "completed" || r.outcome === "already_completed" || r.outcome === "retaken",
);
if (!ok) {
  throw new Error(`Points could not be redeemed: ${results.map((r) => r.outcome).join(", ")}`);
}

await fulfillOrder(`cart_${cart.id}`);
cart.paid = true;
```

Because no Stripe payment occurred, `completeWithoutPayment` does not set `provider` or `order_id` by default. To record your own order reference on the redemption, pass `orderId` and `provider` together.

If the hold expired before the shopper clicked **Place order**, `completeWithoutPayment` redeems the points again (`retaken`), the same way as a card payment. A duplicate call returns `already_completed`, and `requireOpen` blocks duplicate order submissions once `cart.paid` is `true`.

## Return points after a partial refund

To refund part of a split-payment order, issue the card refund in Stripe, then call `scrip.redemptions.reverse` with the points' share as `face_value`. Your store decides how to split refunds and taxes between card and points; Scrip converts `face_value` back to points using the exact rate locked in when the points were held. See [Reversals](https://docs.scrip.dev/guides/redemptions.md#reversals).

For example, suppose a \$100.00 order was paid with \$80.00 by card and \$20.00 in points (2,000 points at \$0.01/point). On a \$30.00 proportional refund, \$24.00 goes back to the card and \$6.00 (600 points) goes back to Scrip:

```ts theme={null}
// Issue the card refund in Stripe
const refund = await stripe.refunds.create({
  payment_intent: intentId,
  amount: 2400,
});

// Return the points share (600 points) in Scrip.
// Scrip uses uppercase ISO 4217 currency codes ("USD").
await scrip.redemptions.reverse(
  {
    path: { redemption_id: redemptionId },
    body: {
      reason: `Stripe refund ${refund.id}`,
      face_value: { amount_minor: 600, currency: "USD" },
    },
  },
  { idempotencyKey: `refund-${refund.id}` },
);
```

Reversals apply only to `COMPLETED` or `PARTIALLY_REVERSED` redemptions. Before a payment succeeds, points are only held and are returned by cancelling the PaymentIntent or calling `removePoints`. The checkout SDK does not issue Stripe refunds or calculate refund splits and tax.

## If something goes wrong

To inspect a redemption or debug a balance mismatch, call `scrip.redemptions.get`, `scrip.redemptions.listForParticipant`, or `scrip.participants.listBalances` (which returns `available`, `held`, and `available_value`).

| What happened | What the SDK does | What your store does |
| - | - | - |
| Shopper returned from Stripe before the webhook arrived, or reloaded after paying | Does nothing; the webhook still completes the redemption on arrival. | Block cart edits and show the order confirmation. See [Refuse changes to a paid cart](#refuse-changes-to-a-paid-cart). |
| Card was declined | `payment_intent.payment_failed` returns `{ handled: false }`. The hold and discount remain active. | Let the shopper try another card on the same PaymentIntent. |
| Payment succeeded after the hold expired, and points are still available | `handleEvent` redeems and completes the points under a new redemption (`retaken`). | Fulfill the order. |
| Payment succeeded after the hold expired, and points are no longer available | `handleEvent` returns `points_unavailable` and spends no points. | Resolve the shortfall: collect the difference, refund part of the payment, or absorb the loss. |
| Two Stripe payments succeeded for one order | `handleEvent` returns `completed_by_other_payment` with `otherOrderId`. | Refund one of the two payments. |
| Scrip is unreachable or times out during `handleEvent` | Throws `ScripError`, `ScripNetworkError`, or `StripeDeadlineError`. | Let the error propagate so your webhook returns `5xx` and Stripe retries. |

> [card] [Add the checkout points widget](https://docs.scrip.dev/guides/checkout-points-widget.md)
>
> Mount a points control on your checkout page or wire up your own UI.

> [card] [Use Stripe Checkout Sessions](https://docs.scrip.dev/guides/pay-with-points-with-stripe-checkout-sessions.md)
>
> Apply points as a one-time coupon on Stripe-hosted Checkout pages.

> [card] [Pending redemptions](https://docs.scrip.dev/guides/redemption-lifecycle.md)
>
> Hold deadlines, states, and ledger entries underneath checkout.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.