@gr4vy/secure-fields-react

中文文档
2.13.0发布于 2026/11/03MITTypeScriptCommonJS近 30 天下载 4.8万

Gr4vy-hosted secure fields offering advanced theming, PCI compliance, event handling, and more.

原始使用文档
文档目录10 节
  1. Usage
  2. Get started
  3. Creating a form
  4. Validation
  5. Field Components
  6. Click to Pay
  7. Prerequisites
  8. Adding Click to Pay
  9. Click to Pay Global events
  10. Updating Checkout Options

Secure Fields for React

NPM Version GitHub license Changelog

Add Secure Fields in your React app.

Use @gr4vy/secure-fields in a non-React application.

Usage

Via the command line, install this package as follows.

npm install @gr4vy/secure-fields-react --save-prod
# yarn add @gr4vy/secure-fields-react

Get started

To use Secure Fields, import the SecureFields Provider component and wrap your app with it, making sure you pass the necessary configuration props and any event handlers.

require('@gr4vy/secure-fields-react/lib/style.css') // default styles
// import '@gr4vy/secure-fields-react/lib/style.css'

const { SecureFields } = require("@gr4vy/secure-fields-react")
// import { SecureFields } from "@gr4vy/secure-fields-react"

<SecureFields
  gr4vyId='[GR4VY_ID]'
  environment='sandbox'
  sessionId='[SESSION_ID]'
  // For stored payment methods (optional):
  // paymentMethod={{ id: '[PAYMENT_METHOD_ID]', scheme: [PAYMENT_METHOD_SCHEME] }}
  // Deprecated:
  // paymentMethodId='[PAYMENT_METHOD_ID]' // uuid of a stored payment method
  debug
  font="Lato"
  // autoAdvance={{ enabled: true, fieldOrder: ['number', 'expiryDate', 'securityCode'] }}
  onReady={(data) => console.log('Secure Fields loaded', data)}
  onCardVaultSuccess={() => console.log('Card tokenization successful')}
  onCardVaultFailure={(data) => console.error('Card tokenization failed', data)}
>
  <Form />
</SecureFields>

Note: Replace [GR4VY_ID] and [SESSION_ID] with the ID of your instance and the Session ID obtained from calling the Checkout Sessions API.

Prop NameDescription
gr4vyIdYour Gr4vy ID.
environmentYour Gr4vy environment. Can be either sandbox or production.
sessionIdThe Session ID.
paymentMethodAn optional object { id: string, scheme: string } for stored payment methods.
paymentMethodIdAn optional uuid for stored payment methods. Deprecated: This prop is no longer recommended for use and will be removed in a future release. Please use paymentMethod instead.
debugEnables / disables the debug mode.
fontLoads a custom font from Google Fonts to be used inside inputs. You can define the font family as well as styles or weights as a string (e.g. "Lato:400,600"). To use the loaded font, add the correct fontFamily property to the styles object when rendering fields.
onReadyAn event handler that listens for Secure Fields to be securely loaded. It listens for the READY event and accepts a callback function.
onFormChangeAn event handler that listens for Secure Fields change. It listens for the FORM_CHANGE event and accepts a callback function.
onCardVaultSuccessAn event handler that listens for card data to be securely vaulted. It listens for the CARD_VAULT_SUCCESS event and accepts a callback function.
onCardVaultFailureAn event handler that listens for any failures when storing any card data. It listens for the CARD_VAULT_FAILURE event and accepts a callback function.
validateOnSets when fields show validation errors: 'blur' (default), once the user leaves a field, or 'submit', once secureFields.validate() is called. Set on mount; later changes are ignored. See Validation.
autoAdvanceEnable auto-advance to automatically move focus to the next field when the current field's value is complete and valid. Accepts { enabled: boolean, fieldOrder?: Array<FieldType> }. See UX options for more details.

Creating a form

Within the SecureFields provider you can now create your own card form using each of the Secure Field components.

Additionally, a useSecureFields hook is available to get the configured Secure Fields instance which can be used to submit() the card form, and check if debug is enabled or not.

const {
  CardNumber,
  ExpiryDate,
  SecurityCode,
} = require('@gr4vy/secure-fields-react')

// Alternatively:
// import {
//   CardNumber,
//   ExpiryDate,
//   SecurityCode
// } from "@gr4vy/secure-fields-react"

const Form = () => {
  const { secureFields } = useSecureFields()

  const handleSubmit = () => {
    secureFields.submit()
  }

  return (
    <>
      <label htmlFor="cc-number">Card number</label>
      <CardNumber />

      <label htmlFor="cc-expiry-date">Expiry date</label>
      <ExpiryDate />

      <label htmlFor="cc-security-code">Security code</label>
      <SecurityCode />

      <button onClick={handleSubmit}>Submit</button>
    </>
  )
}

You can also collect other kind of information along with the card data. We currently support an additional postal code field, which can be added to your form using Field component, passing the specific type and the rest of the options.

const { Field } = require('@gr4vy/secure-fields-react')

<label htmlFor="postal-code">Postal code</label>
<Field
  type="postalCode"
  pattern="[A-Z][0-9]\s[0-9][A-Z]{2}" // optional, defaults to 5 characters minimum
/>

Validation

Call secureFields.validate() to flag every invalid field at once, including empty ones the user never touched, for example when the user clicks "Pay". Use the complete property from onFormChange to stop the submission if the form isn't ready.

const App = () => {
  const [complete, setComplete] = useState(false)

  return (
    <SecureFields
      // ...
      validateOn="submit" // optional
      onFormChange={(data) => setComplete(data.complete)}
    >
      <Form complete={complete} />
    </SecureFields>
  )
}

const Form = ({ complete }) => {
  const { secureFields } = useSecureFields()

  const handleSubmit = () => {
    secureFields.validate()
    if (secureFields.method === 'card' && !complete) return
    secureFields.submit()
  }

  // ...
}

With validateOn="submit", no field shows an error until validate() is called. After that, errors update as the user types.

Each field in the onFormChange data also reports touched (blurred or validated at least once) and dirty (value changed at least once, by typing or by browser autofill).

Field Components

The available secure fields components are CardNumber, ExpiryDate, SecurityCode and Field. You can pass the following props to customize each of them.

Prop NameDescription
placeholderInput placeholder text.
patternA pattern the field value should match, defined as a string (regular expression). Only for postal code fields.
stylesAn object of CSS rules to style the input inside the iframe. See Styles for more information.
onBlurAttaches an event handler to the input, listening for the blur event. The data available in the passed callback includes an id representing the field type (e.g. expiryDate).
onFocusAttaches an event handler to the input, listening for the focus event. The data available in the passed callback includes an id representing the field type (e.g. expiryDate).
onInputAttaches an event handler to the input, listening for the input event. The data available in the passed callback includes an id representing the field type (e.g. expiryDate) and some useful card validation information, such as the current scheme (e.g. visa) and security code label (e.g. CVV).
onRedactAttaches an event handler to the input, listening for the redacted event (fired when the field value is masked, either automatically via maskInput or programmatically via redactValue()).
onUnredactAttaches an event handler to the input, listening for the unredacted event (fired when the field value is unmasked, either automatically or programmatically via unredactValue()).
autoFocusAutomatically focus the field when loaded.
maskInputEnable input masking. Accepts true for default masking, or an object with character (masking character, default •), showLastFour (keep last 4 digits visible, CardNumber only — ignored on SecurityCode), and maskOnInput (mask in real-time). Only available on CardNumber and SecurityCode.
onCardDetailsChangedAttaches an event handler to the input, listening for the card-details-changed event. Fired when the API confirms card details for the entered BIN, including the confirmed scheme. Only available on CardNumber.
showSchemeIconsDisplay card scheme icons inside the card number field. Icons update in real-time as the user types and are refined when the API confirms the scheme. Accepts true to show scheme and additional scheme icons, or an object for granular control which accepts:

• scheme: (boolean) show detected scheme
• additionalSchemes: (boolean) show co-branded icons
• placeholders: (boolean) show Visa/Mastercard/Amex before detection

A maximum of 3 icons are shown — ensure the input is wide enough to accommodate them. Only available on CardNumber.

Each field component supports a ref that exposes clear(), redactValue(), and unredactValue() methods.

import { useRef } from 'react'
import { CardNumber } from '@gr4vy/secure-fields-react'

const CardNumberWithClear = () => {
  const cardNumberRef = useRef(null)

  return (
    <>
      <CardNumber ref={cardNumberRef} maskInput />
      <button type="button" onClick={() => cardNumberRef.current?.clear()}>
        Clear
      </button>
      <button
        type="button"
        onClick={() => cardNumberRef.current?.redactValue()}
      >
        Mask
      </button>
      <button
        type="button"
        onClick={() => cardNumberRef.current?.unredactValue()}
      >
        Unmask
      </button>
    </>
  )
}

Click to Pay

Click to Pay is the better way to pay online – featuring advanced payment technology built on secure remote commerce industry standards.

Prerequisites

Follow the instructions for Click to Pay Merchant Setup.

Adding Click to Pay

Once Secure Fields is configured, you can start adding Click to Pay to your checkout.

Firstly, add the ClickToPay component to your form so Secure Fields can render Click to Pay. Make sure to pass the required options to it as props.

Then, add a sign-in form to let users access their Click to Pay stored cards and wrap it with the ClickToPaySignIn component.

Additionally, add a checkbox to allow a customer not already enrolled to determine if they want to share their card data with Click to Pay.

Finally, ensure card inputs are wrapped with the CardForm component.

import { ClickToPay, ClickToPaySignIn, CardForm } from '@gr4vy/secure-fields-react'

...

const { secureFields } = useSecureFields()

<ClickToPay
  dpaLocale="en_AU"
  cardBrands={['mastercard', 'visa', 'american-express']}
  email="[email protected]"
  mobileNumber={{
    countryCode: '61',
    phoneNumber: '491570159',
  }}
  consentCheckbox="#click-to-pay-consent-checkbox"
/>

<ClickToPaySignIn
  onVisibilityChange={(visible: boolean) => {
    console.log('Sign in UI visibility changed. Visible', visible)
  }}
>
  <label>Access your Click to Pay stored cards</label>
  <input type="text" className="click-to-pay-email-phone" ref={phoneOrEmailRef} />
  <button
    className="px-4 py-2 text-white bg-blue-500 rounded-md hover:bg-blue-600"
    onClick={() => secureFields?.clickToPay?.signIn({ email: phoneOrEmailRef?.current?.value })}
  >Continue</button>
</ClickToPaySignIn>

<CardForm>
  <label htmlFor="cc-number">Card number</label>
  <CardNumber styles={styles} />

  <label htmlFor="cc-expiry-date">Expiry date</label>
  <ExpiryDate styles={styles} />

  <label htmlFor="cc-security-code">Security code</label>
  <SecurityCode styles={styles} />
</CardForm>

<div>
  <input type="checkbox" id="click-to-pay-consent-checkbox" />
  <label htmlFor="click-to-pay-consent-checkbox">Store my card with Click to Pay</label>
</div>

The ClickToPay component accepts the following props:

Prop NameDescription
srcDpaIdDPA Identifier. This is a unique identifier for you Digital Payment Application (DPA), which was generated during onboarding.
dpaNameLegal name of registered DPA.
cardBrandsList of card schemes the merchant accepts. We currently support mastercard, maestro, visa, amex, discover
consentCheckboxA reference to the opt-in consent checkbox element.
learnMoreLinkA reference to the learn more link element.
emailThe user email used to access Click to Pay.
mobileNumberThe user phone number used to access Click to Pay. Required format is { countryCode: string, phoneNumber: string }
dynamicDataTypeThe type of cryptogram or token used for the card data. See the Mastercard docs for more information. Possible values are NONE and CARD_APPLICATION_CRYPTOGRAM_SHORT_FORM. Defaults to CARD_APPLICATION_CRYPTOGRAM_SHORT_FORM.

Click to Pay Global events

The following props can be used on the SecureFields component to listen to specific Click to Pay events.

Prop NameDescription
onClickToPayInitializedAn event handler that listens for Click to Pay to be securely initialized. It listens for the CLICK_TO_PAY_INITIALIZED event and accepts a callback function with a clickToPay instance as argument.
onClickToPayReadyAn event handler that listens for Click to Pay to be ready. It listens for the CLICK_TO_PAY_READY event and accepts a callback function with an object { buyerExists: boolean }.
onClickToPaySignOutAn event handler that listens for users signing out of Click to Pay. It listens for the CLICK_TO_PAY_SIGN_OUT event and accepts a callback function.
onClickToPayErrorAn event handler that listens for any errors thrown by Click to Pay. It listens for the CLICK_TO_PAY_ERROR event and accepts a callback function with the error type (one of | 'RETRIES_EXCEEDED' | 'CODE_INVALID' | 'INVALID_CARD' | 'SIGN_OUT_FAILED' | 'ACCT_INACCESSIBLE' | 'UNKNOWN' | 'USER_NOT_RECOGNIZED').
onClickToPayCancelAn event handler that listens for users closing / cancelling Click to Pay. It listens for the CLICK_TO_PAY_CANCEL event and accepts a callback function.
onClickToPayCheckoutWithNewCardAn event handler that listens for users checking out with a new card. It listens for the CLICK_TO_PAY_CHECKOUT_WITH_NEW_CARD event and accepts a callback function.
onClickToPayUnableToLoadDpaAn event handler that listens for Click to Pay not being able to load the provided DPA. It listens for the CLICK_TO_PAY_UNABLE_TO_LOAD_DPA event and accepts a callback function.
onMethodChangeAn event handler that listens for users selecting a different method (either card or click-to-pay). It listens for the METHOD_CHANGE event and accepts a callback function with the selected method.

Updating Checkout Options

Update the Click to Pay checkout options after initialization. This is useful when the transaction amount changes (e.g. cart updates) before the user submits.

const { secureFields } = useSecureFields()

secureFields.clickToPay.updateCheckoutOptions({
  transactionAmount: 9.99,
  transactionCurrencyCode: 'AUD',
})

Options are merged with previously set values, so you can update individual fields without losing the rest.

OptionTypeDescription
transactionAmountnumberThe transaction amount.
transactionCurrencyCodestringThe transaction currency code.

版本与发布记录

@gr4vy/secure-fields-react 共发布 99 个版本,首次发布于 2022/08/13;过去 12 个月发布了 33 个版本。

版本发布日期距今
2.13.0latest2026/11/0313 天前
2.12.02026/11/0313 天前
2.11.22026/10/051 个月前
2.11.2--canary.1346.7573de9.0canary2026/10/051 个月前
2.11.2--canary.1339.789d550.02026/09/301 个月前
2.11.12026/09/251 个月前

关于 @gr4vy/secure-fields-react 的常见问题

@gr4vy/secure-fields-react 是什么?

Gr4vy-hosted secure fields offering advanced theming, PCI compliance, event handling, and more.

如何安装 @gr4vy/secure-fields-react?

在项目目录运行 npm install @gr4vy/secure-fields-react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=17.0.0)、react-dom(>=17.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gr4vy/secure-fields-react 支持 TypeScript 吗?

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

@gr4vy/secure-fields-react 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gr4vy/secure-fields-react 可以商用吗?

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

@gr4vy/secure-fields-react 的下载量有多少?

根据 npm 官方下载统计,@gr4vy/secure-fields-react 在 2026/10/17 – 2026/11/15 这 30 天内被下载 47,804 次,日均约 1,593 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gr4vy/secure-fields-react 还在维护吗?

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