# Payment

> The payment step of a checkout, with wallets, cards, PayPal and Pay in 4. Handles card validation, declines, 3-D Secure and slow banks.

Canonical: https://hextaui.com/blocks/payment
Last updated: 2026-10-29

## Overview

Payment is the last step of a checkout. Wrap the parts in Payment with the order total and an onPay callback, then place ExpressCheckout, PaymentMethods, BillingAddress, PayButton and PaymentStatus where they fit your layout. Payment owns the state between them, so the button label follows the chosen method: “Pay $123.45” for a card, “Continue to PayPal”, “Pay $30.87 today” for Pay in 4.

The card form detects the brand from the first digits and swaps its mark only when the brand changes. It groups digits as you type, 4-6-5 for American Express, writes the expiry as MM/YY with the slash added for you, and accepts “1/27”, “0127” and pasted numbers with spaces or dashes. Each field is checked on blur or once it’s complete, then live, so an error clears the moment it’s fixed. Focus moves from number to expiry to security code only when the field before it is complete, valid and the next one is empty.

onPay gets a typed request with the card details or saved card, the amount, the billing choice and a fresh idempotency key. Return nothing or { status: "succeeded" } to finish: the button shows a check, holds for 700 ms and calls onComplete. Return { status: "declined", code } and the error appears above the methods with copy written for that code, focus moves to it, the card stays filled in and “Try another card” clears it. Return { status: "requires_action" } to open the “Confirm with your bank” dialog, where renderChallenge mounts your 3-D Secure step.

While a payment runs the button can’t be pressed twice, the methods are inert, leaving the page asks for confirmation, and after three seconds the status line says “Confirming with your bank…”. Saved cards that have expired show as disabled, and declineMessage gives the same copy for your own error screens.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/payment
```

## Usage

### Stripe PaymentIntent

Create a PaymentIntent with the request’s idempotency key, confirm it with Stripe and return a declined result with Stripe’s decline code. In production, collect the card with Stripe Elements so raw card numbers never reach your server; the card form here is a visual reference that matches it.

```tsx
"use client"

import { money } from "../price/money"
import { Payment, PayButton, PaymentStatus } from "@/components/blocks/payment/payment"
import { PaymentMethods } from "@/components/blocks/payment/payment-methods"
import type { PaymentRequest, PaymentResult } from "@/components/blocks/payment/payment-model"

type StripeConfirmResult = {
  error?: { code?: string; decline_code?: string; message?: string }
  paymentIntent?: {
    id: string
    status: "succeeded" | "processing" | "requires_action"
  }
}

type Stripe = {
  confirmPayment: (options: {
    elements: unknown
    clientSecret: string
    redirect: "if_required"
    confirmParams?: { return_url: string }
  }) => Promise<StripeConfirmResult>
}

async function createPaymentIntent(idempotencyKey: string) {
  const response = await fetch("/api/payment-intents", {
    method: "POST",
    headers: { "Idempotency-Key": idempotencyKey },
  })
  if (!response.ok) throw new Error("We couldn’t start the payment. Try again.")
  const { clientSecret } = (await response.json()) as { clientSecret: string }
  return clientSecret
}

export function StripePayment({
  stripe,
  elements,
}: {
  stripe: Stripe
  elements: unknown
}) {
  const pay = async (request: PaymentRequest): Promise<PaymentResult> => {
    const clientSecret = await createPaymentIntent(request.idempotencyKey)
    const { error, paymentIntent } = await stripe.confirmPayment({
      elements,
      clientSecret,
      redirect: "if_required",
      confirmParams: { return_url: `${window.location.origin}/order/complete` },
    })
    if (error) {
      return {
        status: "declined",
        code: error.decline_code ?? error.code,
        message: error.message,
      }
    }
    return { status: "succeeded", id: paymentIntent?.id }
  }

  return (
    <Payment
      total={money("123.45", "USD")}
      methods={["card"]}
      onPay={pay}
      onComplete={() => window.location.assign("/order/complete")}
    >
      <PaymentMethods />
      <PayButton />
      <PaymentStatus />
    </Payment>
  )
}
```

### PayPal redirect

Create a PayPal order on your server and send the shopper to its approval URL. The button keeps its processing state while the page leaves, and PayPal-Request-Id stops a double order if the request is retried.

```tsx
"use client"

import { money } from "../price/money"
import { Payment, PayButton, PaymentStatus } from "@/components/blocks/payment/payment"
import { PaymentMethods } from "@/components/blocks/payment/payment-methods"
import type { PaymentRequest } from "@/components/blocks/payment/payment-model"

export function PayPalRedirect({ cartId }: { cartId: string }) {
  const pay = async (request: PaymentRequest) => {
    if (request.method !== "paypal") {
      throw new Error("This store only takes PayPal right now.")
    }
    const response = await fetch("/api/paypal/orders", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "PayPal-Request-Id": request.idempotencyKey,
      },
      body: JSON.stringify({ cartId }),
    })
    if (!response.ok) {
      throw new Error("PayPal isn’t responding. Nothing was charged.")
    }
    const { approveUrl } = (await response.json()) as { approveUrl: string }
    window.location.assign(approveUrl)
    await new Promise(() => {})
  }

  return (
    <Payment
      total={money("123.45", "USD")}
      methods={["paypal"]}
      defaultMethod="paypal"
      onPay={pay}
    >
      <PaymentMethods />
      <PayButton />
      <PaymentStatus />
    </Payment>
  )
}
```

### Shopify checkout handoff

Use the payment step as a branded front for Shopify’s checkout. Shop Pay opens checkoutUrl with payment=shop_pay, and PayPal hands off to the same URL.

```tsx
"use client"

import { ExpressCheckout } from "@/components/blocks/payment/express-checkout"
import { Payment, PayButton, PaymentStatus } from "@/components/blocks/payment/payment"
import { PaymentMethods } from "@/components/blocks/payment/payment-methods"

type ShopifyCart = {
  checkoutUrl: string
  cost: { totalAmount: { amount: string; currencyCode: string } }
}

function go(url: string) {
  window.location.assign(url)
  return new Promise<void>(() => {})
}

export function ShopifyHandoff({ cart }: { cart: ShopifyCart }) {
  const url = new URL(cart.checkoutUrl)

  return (
    <Payment
      total={cart.cost.totalAmount}
      methods={["paypal"]}
      defaultMethod="paypal"
      onPay={() => go(url.toString())}
    >
      <ExpressCheckout
        methods={["shop_pay"]}
        onExpress={() => {
          url.searchParams.set("payment", "shop_pay")
          return go(url.toString())
        }}
      />
      <PaymentMethods />
      <PayButton />
      <PaymentStatus />
    </Payment>
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `Payment` | Holds the method, card fields, billing choice and payment state, and renders the bank dialog. |
| `ExpressCheckout` | A row of equal wallet buttons for the wallets you pass, with an “or pay another way” divider. |
| `PaymentMethods` | Saved cards, the card form, PayPal and Pay in 4 as radio cards, with the decline message above them. |
| `BillingAddress` | The “Billing address same as shipping” checkbox and the billing form it reveals. |
| `PayButton` | The full-width pay button. Its label follows the method and it shows processing, waiting and paid. |
| `PaymentStatus` | A line under the button with reassurance or progress, and the live region for screen readers. |
| `declineMessage, PaymentDeclinedError` | Copy for each decline code, and an error you can throw from onPay with a code. |

## API reference

### Payment

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `total` | `Money` | – | The amount to charge, shown on the button. |
| `onPay` | `(request: PaymentRequest) => Promise<PaymentResult \| void> \| PaymentResult \| void` | – | Runs the payment. Throwing shows the error’s message at the payment section. |
| `onComplete` | `(request: PaymentRequest, result: PaymentResult) => void` | – | Called after the success check has held. |
| `validate` | `(request: PaymentRequest) => boolean` | – | Runs before onPay. Return false to stop, for example when your billing form has errors. |
| `methods` | `("card" \| "paypal" \| "bnpl" \| "apple_pay" \| "google_pay")[]` | `["card", "paypal", "bnpl"]` | Methods listed after any saved cards, in order. |
| `savedCards` | `SavedCard[]` | – | Cards on file. Expired ones are shown but can’t be picked. |
| `method` | `string` | – | The selected method, controlled. Saved cards use "saved:<id>". |
| `defaultMethod` | `string` | – | The first usable saved card, or the first method. |
| `onMethodChange` | `(method: string) => void` | – | Called when the shopper picks another method. |
| `sameAsShipping` | `boolean` | – | Whether billing matches shipping, controlled. |
| `defaultSameAsShipping` | `boolean` | `true` | The starting value of the billing checkbox. |
| `onSameAsShippingChange` | `(same: boolean) => void` | – | Called when the billing checkbox changes. |
| `bnpl` | `{ installments?: number; title?: string }` | `{ installments: 4 }` | How many payments Pay in 4 splits into, and its name. |
| `renderChallenge` | `(challenge: { action, amount, complete, cancel }) => ReactNode` | – | Content of the “Confirm with your bank” dialog. Call complete with the final result. |
| `successDelay` | `number` | `700` | How long the paid state holds before onComplete, in ms. |
| `slowAfter` | `number` | `3000` | When the status line switches to “Confirming with your bank…”, in ms. |
| `today` | `Date` | – | The date expiry checks use. The browser’s date by default. |
| `locale` | `Intl.LocalesArgument` | `"en-US"` | Locale for amounts. |
| `labels` | `Partial<PaymentLabels>` | – | Every user-facing string. |

### ExpressCheckout

Works inside Payment or on its own.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `methods` | `("apple_pay" \| "google_pay" \| "shop_pay" \| "paypal")[]` | – | Wallets to show, in order. Only these render. |
| `onExpress` | `(method: ExpressMethod) => Promise<PaymentResult \| void> \| PaymentResult \| void` | – | Opens the wallet. The button shows a spinner until it settles. |
| `divider` | `boolean` | `true` | Show the “or pay another way” divider. |
| `labels` | `Partial<ExpressCheckoutLabels>` | – | Button names, divider and group label. |

### BillingAddress

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `billingAddress` | `ReactNode` | – | Your billing form, revealed when the checkbox is cleared. Its first field gets focus. |

### PayButton

Also takes Button props. Children replace the automatic label.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |

### PaymentRequest

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `method` | `"card" \| "saved_card" \| "paypal" \| "bnpl" \| "apple_pay" \| "google_pay" \| "express"` | – | What the shopper chose. card adds card, saved_card adds savedCard, bnpl adds installments, express adds express. |
| `amount` | `Money` | – | The total. |
| `idempotencyKey` | `string` | – | New for every attempt. Send it to your payment provider. |
| `billingSameAsShipping` | `boolean` | – | The billing checkbox. |

### PaymentResult

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `status` | `"succeeded" \| "requires_action" \| "declined"` | – | What happened. |
| `code` | `DeclineCode \| string` | – | insufficient_funds, expired_card, incorrect_cvc, card_declined, processing_error or authentication_failed. |
| `message` | `string` | – | Overrides the copy for the code. |

## Keyboard

| Key | Action |
| --- | --- |
| `↑` `↓` | Move between payment methods. |
| `Tab` | Move from the chosen method into its card fields. |
| `Enter` | Pay from any card field. |
| `Esc` | Close the bank dialog, which cancels that attempt. |

## Accessibility

- Methods are a radio group, and each card field has a visible label, its own error message and autocomplete tokens (cc-number, cc-exp, cc-csc, cc-name) so browsers can fill them.
- A decline is announced as an alert and takes focus, so screen reader users hear what went wrong and land next to “Try another card”.
- Processing, waiting for the bank and success are announced through a polite live region. The detected brand is read with the card number field.
- The button keeps its size through every state, inputs are 16px on touch screens, and with reduced motion the reveals and icon swaps change without moving.

## Built with

The free HextaUI components Payment is made from. Each one installs on its own.

- [Alert](https://hextaui.com/docs/alert) - Inline messages for status and feedback, with a neutral surface, a colored icon and a dismiss that collapses smoothly.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Checkbox](https://hextaui.com/docs/checkbox) - A checkbox whose check draws in, with indeterminate parents, groups and labels that share its hover.
- [Dialog](https://hextaui.com/docs/dialog) - A window over the page for forms and focused tasks, with a pinned header and footer, nesting, and a swipeable bottom sheet on phones.
- [Field](https://hextaui.com/docs/field) - Labels, descriptions and errors wired to their control, with validation states and layouts for forms.
- [Input](https://hextaui.com/docs/input) - A text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Radio group](https://hextaui.com/docs/radio-group) - Pick one option from a set, with a dot that hands off between choices and cards whose selection ring slides to the new pick.
- [Separator](https://hextaui.com/docs/separator) - A hairline that divides content horizontally or vertically, with an optional label and a decorative mode for purely visual lines.
- [Spinner](https://hextaui.com/docs/spinner) - A loading indicator with Apple-style ticks or a breathing ring that can wait before showing and stay long enough not to flicker.

## Code

8 files, added to components/blocks/payment.
