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

# Checkout points widget

> Add a points control to a Stripe checkout page with the Scrip checkout widget, or build the control yourself.

Add a "use your points" control to your Stripe checkout page with `@scrip-systems/checkout-widget`, or build your own UI on top of the same server routes.

This guide builds on the PaymentIntents setup (`scrip`, `stripe`, `Cart`, `fullPrice`, `syncIntent`, and `requireOpen`) in [Pay with points at checkout with Stripe](https://docs.scrip.dev/guides/pay-with-points-at-checkout-with-stripe.md).

## Add the widget

The widget lets shoppers enter a dollar amount, click **Apply**, and pay the remaining balance by card. It never calls Scrip or Stripe directly: it calls callbacks you provide, and your server holds the points and updates the PaymentIntent.

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

Your server provides three pieces:

| Piece | What it does |
| - | - |
| Balance data on page load | Reads the participant's balance and points asset from Scrip and passes both to the checkout page. |
| Apply route | Called by the widget's `onApply` callback. Runs `applyPoints`, updates the PaymentIntent, and returns the widget's expected result shape. |
| Remove route | Called by `onRemove`. Runs `removePoints` and returns `{ status: "removed" }`. |

Keep all authoritative cart state on your server (`totalMinor`, `intentId`, `redemptionIds`, and `card`). Treat browser requests as shopper intent only.

### Server helpers and apply route

Load the shopper's available balance at page render, and handle point applications on your server (`PROGRAM_ID` and `ASSET_ID` are your own constants):

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

// Load the participant's balance and asset metadata for the checkout page
async function getPointsBalance(cart: Cart) {
  try {
    const [page, asset] = await Promise.all([
      scrip.participants.listBalances({ path: { participant_id: cart.participantId } }),
      scrip.assets.get({ path: { asset_id: ASSET_ID } }),
    ]);
    const row = page.data?.find((b) => b.asset_id === ASSET_ID);
    // Returning null hides the points control
    return row && Number(row.available) > 0 ? { ...row, asset } : null;
  } catch (error) {
    // Shopper does not exist in Scrip yet
    if (error instanceof ScripError && error.status === 404) return null;
    throw error;
  }
}

// Called by POST /api/carts/:id/points with body { faceValue: { amount_minor, currency }, expectedPoints? }
// Validate that faceValue.amount_minor is positive, matches cart.currency, and does not exceed cart.totalMinor first.
async function applyToCart(cart: Cart, faceMinor: number, expectedPoints?: string) {
  await requireOpen(cart);

  const result = await scrip.stripe.applyPoints({
    participantId: cart.participantId,
    programId: PROGRAM_ID,
    assetId: ASSET_ID,
    cartId: cart.id,
    faceValue: { amount_minor: faceMinor, currency: cart.currency },
    expectedAmount: expectedPoints,
    replaces: cart.redemptionIds, // Always read from your server, never the browser
    paymentIntent: fullPrice(cart),
  });

  switch (result.status) {
    case "applied":
    case "fully_covered": {
      const hold = result.holds[0];
      cart.redemptionIds = result.redemptionIds;
      cart.card = result.status === "applied" ? result.params : { ...fullPrice(cart), amount: 0 };

      if (result.status === "fully_covered" && cart.intentId) {
        // Clear the hold ID before cancelling so payment_intent.canceled does not release the hold
        await stripe.paymentIntents.update(cart.intentId, {
          metadata: { scrip_redemption_ids: "" },
        });
        await stripe.paymentIntents.cancel(cart.intentId);
        cart.intentId = undefined;
        cart.clientSecret = undefined;
        cart.cancelledIntents += 1;
      }

      await syncIntent(cart);
      return {
        status: result.status,
        faceValue: { amount_minor: faceMinor, currency: cart.currency.toUpperCase() },
        points: hold.points,
        expiresAt: result.expiresAt,
      };
    }
    case "price_changed": {
      // The previous hold is still active at the old price; keep its IDs so the next call replaces it
      if (result.existingRedemptionIds) cart.redemptionIds = result.existingRedemptionIds;
      const asset = await scrip.assets.get({ path: { asset_id: ASSET_ID } });
      return {
        status: "price_changed",
        points: priceFaceValue({ faceValue: { amount_minor: faceMinor, currency: cart.currency }, asset }),
      };
    }
    case "insufficient_points":
    case "below_minimum_charge":
      return { status: result.status };
    default: // hold_conflict, already_completed
      return { status: "error", message: "Points could not be applied. Try again." };
  }
}
```

### Serve and mount the widget

Serve the global widget bundle from your server, include the script on your checkout page, and call `window.ScripCheckout.mount`:

```ts theme={null}
import { createRequire } from "node:module";

const require = createRequire(import.meta.url);

app.get("/scrip-checkout.global.js", (_req, res) => {
  res.sendFile(require.resolve("@scrip-systems/checkout-widget/global"));
});
```

```html theme={null}
<!-- If the script fails to load, this container stays empty and checkout continues by card -->
<div id="scrip-points"></div>
<script src="/scrip-checkout.global.js"></script>
```

```js theme={null}
// `view` is the checkout state returned by your server:
//   view.points  -> output of getPointsBalance(cart)
//   view.total   -> { amount_minor: 10000, currency: "USD" }
//   view.applied -> the cart's currently applied points (from your previous apply route response), or null
// `api` and `refresh` are your app's fetch helper and checkout-summary reloader.
window.ScripCheckout.mount("#scrip-points", {
  balance: view.points,
  cart: view.total,
  applied: view.applied,
  onApply: async (faceValue, ctx) => {
    const result = await api(`/api/carts/${cartId}/points`, "POST", {
      faceValue,
      expectedPoints: ctx.expectedPoints,
    });
    await refresh(); // Updates the displayed order summary and card form
    return result;
  },
  onRemove: async () => {
    const result = await api(`/api/carts/${cartId}/points`, "DELETE");
    await refresh();
    return result;
  },
});
```

If you use a frontend bundler, import the module directly instead of using a `<script>` tag:

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

`mount` also accepts `onChange`, `onError`, `labels`, `locale`, `minimumCharge`, `timeoutMs`, `showEmpty`, `poweredBy`, and `theme`. Pass Stripe's minimum card charge as `minimumCharge` (for example, `{ amount_minor: 50 }` for USD) so the widget blocks amounts that would leave the remaining card charge below Stripe's minimum.

If a callback times out, throws, or returns an unrecognized response, the widget shows an unavailable message with a **Retry** button. Retrying is safe because repeating the same cart and amount returns the same hold. If `onApply` returns `price_changed`, the widget asks the shopper to confirm the updated point count, then calls `onApply` again with `confirmed: true` and the new figure as `expectedPoints`.

### If the widget fails to load

No points are held and the PaymentIntent keeps the full order total, so the shopper pays by card as usual. Always render your order summary from your server's cart record.

## Build your own control

The widget is optional. A custom UI uses the exact same three server pieces: balance data on page load, the apply route above, and a remove route backed by [`removePoints`](https://docs.scrip.dev/guides/pay-with-points-at-checkout-with-stripe#remove-points). Your frontend handles the statuses documented in [Read the result](https://docs.scrip.dev/guides/pay-with-points-at-checkout-with-stripe.md#read-the-result).

Display the shopper's balance from `available_value` (the money value of `available`, such as `{ "amount_minor": 5730, "currency": "USD" }` for \$57.30). Hide the control when the shopper has no balance or `available_value` is absent. Validate the entered amount against the balance and cart total in the browser, and validate it again on your server.

```js theme={null}
// `$` (document.getElementById wrapper), `money` (currency formatter),
// `api`, and `refresh` are your own frontend helpers.
const available = view.points && view.points.available_value;
$("custom-points").hidden = !available;
if (available) $("custom-balance").textContent = `You have ${money(available)} in points.`;

let expected = null;

$("custom-apply").addEventListener("click", async () => {
  const cents = Math.round(parseFloat($("custom-amount").value) * 100);
  if (!(cents > 0)) {
    $("custom-message").textContent = "Enter an amount.";
    return;
  }

  const r = await api(`/api/carts/${cartId}/points`, "POST", {
    faceValue: { amount_minor: cents, currency: view.total.currency },
    expectedPoints: expected,
  });
  expected = null;

  if (r.status === "applied" || r.status === "fully_covered") {
    await refresh();
    $("custom-message").textContent = "Points applied.";
  } else if (r.status === "price_changed") {
    expected = r.points; // Next click confirms the updated point count
    $("custom-message").textContent = `The price of points changed: this uses ${r.points} points. Click Apply to continue.`;
  } else {
    $("custom-message").textContent =
      r.status === "insufficient_points"
        ? "You do not have enough points."
        : r.message || "Points could not be applied.";
  }
});

$("custom-remove").addEventListener("click", async () => {
  await api(`/api/carts/${cartId}/points`, "DELETE");
  await refresh();
  $("custom-message").textContent = "Points removed.";
});
```

Render your checkout order summary from your server's cart record so the displayed card total always matches what Stripe will charge.

> [card] [PaymentIntents integration](https://docs.scrip.dev/guides/pay-with-points-at-checkout-with-stripe.md)
>
> Server-side holds, webhooks, cart updates, and refunds.

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


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