@fragment-dev/payment-elements

中文文档
0.0.7发布于 2026/11/10MITTypeScriptES Module近 30 天下载 6853

React components for Fragment Payment Elements

原始使用文档
文档目录9 节
  1. Install
  2. Usage
  3. Custom layout
  4. Errors
  5. Save Payment Methods
  6. Billing details
  7. Saving a card
  8. Theming
  9. License

@fragment-dev/payment-elements

Embed Fragment's Payment Elements in your product to process payments through Fragment.

Install

npm install @fragment-dev/payment-elements

React 17, 18 or 19 must be a peer dependency.

Usage

Your server calls the server-side Fragment SDK's createPayment and passes the returned Payment to your product's payment page.

import {
  Checkout,
  PaymentElements,
  usePayment,
} from '@fragment-dev/payment-elements';

const PayButton = () => {
  const { state, canSubmit, submit, error } = usePayment();
  if (state.status === 'accepted') {
    return <p>Payment accepted.</p>;
  }
  return (
    <>
      <button
        type="button"
        disabled={!canSubmit}
        // Call submit() inside the click handler. It never rejects.
        onClick={() => submit()}
      >
        {state.status === 'processing' ? 'Paying…' : 'Pay'}
      </button>
      {state.status === 'declined' && <p role="alert">{state.message}</p>}
      {error && <p role="alert">{error.message}</p>}
    </>
  );
};

const PaymentPage = ({ payment, email }) => (
  <PaymentElements>
    <Checkout
      payment={payment}
      billingDetails={{ email }}
      onPaymentAccepted={close}
      onPaymentDeclined={recordDecline}
      onError={({ message }) => showError(message)}
    >
      <PayButton />
    </Checkout>
  </PaymentElements>
);

Checkout renders your Pay Button below the address and card fields. It takes the same props as PaymentSession.

Use usePayment().state to render the status in your product.

type PaymentCheckoutState =
  | { status: 'loading' }
  | { status: 'ready' }
  | { status: 'processing' }
  | { status: 'declined'; message: string; declineCode: string | null }
  | { status: 'accepted' };

On mount the session loads the Payment's status from Fragment and continues an attempt that is still in flight, so a reload does not charge twice. state reads loading until then.

  • submit() waits for any verification step the card's bank asks for, and resolves when the charge is accepted or declined, or when it fails with an error.
  • onPaymentAccepted fires when the charge is accepted. Read the Payment's status from Fragment on your server before you fulfill an order.
  • onPaymentDeclined fires when the card is declined. The person paying can enter another card and submit again. The decline stays in state until then.
  • onError is required and fires for every failure that is not a decline. Invalid payments report through this callback and render no children.

Custom layout

To customize the layout, render PaymentSession with AddressElement, CardElement and your Pay Button as children. Mount one CardElement per session. AddressElement is optional. See Billing details to learn more.

Errors

Use usePayment().error to render failures that are not declines. It clears when a field changes and when submit() starts. A failure leaves the session ready, so the person paying can submit again.

Save Payment Methods

Set savePaymentMethod to true to save the card for the payer in billingDetails.email when the payment confirms. Defaults to false.

Billing details

You can optionally provide the name and address of the person making the payment. Render the AddressElement if you don't provide them.

Saving a card

To save an end-user's card without charging it, your server calls the server-side Fragment SDK's createPaymentMethodSetup with the end-user's email and passes the returned PaymentMethodSetup to your page.

import {
  PaymentElements,
  SavePaymentMethod,
  usePaymentMethodSetup,
} from '@fragment-dev/payment-elements';

const SaveCardButton = () => {
  const { state, canSubmit, submit, error } = usePaymentMethodSetup();
  if (state.status === 'saved') {
    return <p>Card saved.</p>;
  }
  return (
    <>
      <button
        type="button"
        disabled={!canSubmit}
        // Call submit() inside the click handler. It never rejects.
        onClick={() => submit()}
      >
        {state.status === 'processing' ? 'Saving…' : 'Save card'}
      </button>
      {state.status === 'declined' && <p role="alert">{state.message}</p>}
      {error && <p role="alert">{error.message}</p>}
    </>
  );
};

const SaveCardPage = ({ paymentMethodSetup }) => (
  <PaymentElements>
    <SavePaymentMethod
      paymentMethodSetup={paymentMethodSetup}
      onPaymentMethodSaved={close}
      onPaymentMethodDeclined={recordDecline}
      onError={({ message }) => showError(message)}
    >
      <SaveCardButton />
    </SavePaymentMethod>
  </PaymentElements>
);

SavePaymentMethod renders your Save Button below the address and card fields. It takes the same props as PaymentMethodSetupSession.

To customize the layout, render PaymentMethodSetupSession with AddressElement, CardElement and your Save Button as children. Mount one CardElement per session. AddressElement is optional. See the billingDetails note below to learn more.

Use usePaymentMethodSetup().state to render the status in your product.

type PaymentMethodSetupState =
  | { status: 'loading' }
  | { status: 'ready' }
  | { status: 'processing' }
  | { status: 'declined'; message: string; declineCode: string | null }
  | { status: 'saved' };

On mount the session loads the setup's status from Fragment and continues an attempt that is still in flight. state reads loading until then.

  • submit() waits for any verification step the card's bank asks for, and resolves when the card is saved or declined, or when it fails with an error.
  • onPaymentMethodSaved fires when the payment method was successfully saved. The saved state carries no card details. To read the card, your server queries paymentMethodSetup and reads its paymentMethod field, or lists the end-user's cards with paymentMethods(filter: { user }).
  • onPaymentMethodDeclined fires when the card is declined. The end-user can enter another card and submit again. The decline stays in state until then.
  • onError is required and fires for every other non-decline failure. Invalid setups report through this callback and render no children.
  • billingDetails takes an optional name and address. Without an AddressElement, saving a card needs name, address.line1, address.postalCode and address.country. Render the AddressElement if you don't provide them.

Theming

Pass theme to style the hosted fields. Every setting has a default:

<PaymentElements
  theme={{
    appearance: 'light',
    fontFamily: 'Arial, sans-serif',
    input: {
      fontSize: '16px',
      backgroundColor: '#ffffff',
      borderColor: '#d6d1c7',
      borderWidth: '1px',
      borderRadius: '8px',
      padding: '12px',
      focus: { borderColor: '#00a7c9' },
      invalid: { borderColor: '#c62828' },
    },
    label: { fontSize: '12px', color: '#555562', spacing: '8px' },
    error: { fontSize: '12px', color: '#c62828' },
    layout: { rowGap: '16px', columnGap: '10px' },
  }}
>

input supports fontSize, color, backgroundColor, borderColor, borderWidth, borderRadius and padding. Its focus and invalid objects accept the same properties; unspecified properties inherit the base input style. Invalid styling takes precedence when an invalid field is focused. Set input.borderWidth to '0px' for borderless fields.

label and error style hosted labels and inline validation messages, not messages your application renders from session errors. label.spacing controls the gap below a label. layout controls gaps between fields, not their order. These settings apply to both card and address elements.

appearance is light or dark. When omitted it follows the dark class on <html>. The default uses 16px input text, 12px labels, 1px borders, 8px corners and 12px input padding.

Use literal colours and system fonts. Hosted fields cannot inherit your page's CSS custom properties or fonts. Keep input text at least 16px on mobile.

License

MIT

版本与发布记录

@fragment-dev/payment-elements 共发布 7 个版本,首次发布于 2026/09/16;过去 12 个月发布了 7 个版本。

版本发布日期距今
0.0.7latest2026/11/105 天前
0.0.62026/11/0511 天前
0.0.52026/11/0511 天前
0.0.42026/10/141 个月前
0.0.32026/10/141 个月前
0.0.22026/09/171 个月前

关于 @fragment-dev/payment-elements 的常见问题

@fragment-dev/payment-elements 是什么?

React components for Fragment Payment Elements

如何安装 @fragment-dev/payment-elements?

在项目目录运行 npm install @fragment-dev/payment-elements,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^17.0.0 || ^18.0.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fragment-dev/payment-elements 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fragment-dev/payment-elements 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@fragment-dev/payment-elements 可以商用吗?

@fragment-dev/payment-elements 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fragment-dev/payment-elements 的下载量有多少?

根据 npm 官方下载统计,@fragment-dev/payment-elements 在 2026/10/16 – 2026/11/14 这 30 天内被下载 6,853 次,日均约 228 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fragment-dev/payment-elements 还在维护吗?

最新版本 0.0.7 发布于 2026/11/10(5 天前);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2026/09/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。