npm package: @gr4vy/secure-fields-react
Description: Gr4vy-hosted secure fields offering advanced theming, PCI compliance, event handling, and more.
Author: Gr4vy
Latest version: 2.3.1

# Secure Fields for React

![NPM Version](https://img.shields.io/npm/v/@gr4vy/secure-fields-react?color=green)
[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/gr4vy/secure-fields/blob/main/LICENSE)
[![Changelog](https://img.shields.io/badge/changelog-dimgrey?logo=npm&logoColor=white)](https://www.runpkg.com/?@gr4vy/secure-fields/CHANGELOG.md)

Add Secure Fields in your React app.

Use [`@gr4vy/secure-fields`](../secure-fields) in a non-React application.

## Usage

Via the command line, install this package as follows.

```bash
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.

```jsx
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"
  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](https://gr4vy.com/docs/reference#tag/Checkout-Sessions).

| Prop Name            | Description                                                                                                                                                                                                                                                                                           |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `gr4vyId`            | Your Gr4vy ID.                                                                                                                                                                                                                                                                                        |
| `environment`        | Your Gr4vy environment. Can be either `sandbox` or `production`.                                                                                                                                                                                                                                      |
| `sessionId`          | The Session ID.                                                                                                                                                                                                                                                                                       |
| `paymentMethod`      | An optional object `{ id: string, scheme: string }` for stored payment methods.                                                                                                                                                                                                                       |
| `paymentMethodId`    | An 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.                                                                                                                  |
| `debug`              | Enables / disables the debug mode.                                                                                                                                                                                                                                                                    |
| `font`               | Loads a custom font from [Google Fonts](https://fonts.google.com/) 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. |
| `onReady`            | An event handler that listens for Secure Fields to be securely loaded. It listens for the [`READY`](https://docs.gr4vy.com/guides/payments/secure-fields/events) event and accepts a callback function.                                                                                               |
| `onFormChange`       | An event handler that listens for Secure Fields change. It listens for the [`FORM_CHANGE`](https://docs.gr4vy.com/guides/payments/secure-fields/events) event and accepts a callback function.                                                                                                        |
| `onCardVaultSuccess` | An event handler that listens for card data to be securely vaulted. It listens for the [`CARD_VAULT_SUCCESS`](https://docs.gr4vy.com/guides/payments/secure-fields/events) event and accepts a callback function.                                                                                     |
| `onCardVaultFailure` | An event handler that listens for any failures when storing any card data. It listens for the [`CARD_VAULT_FAILURE`](https://docs.gr4vy.com/guides/payments/secure-fields/events) event and accepts a callback function.                                                                              |

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

```js
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.

```js
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
/>
```

## 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 Name     | Description                                                                                                                                                                                                                                                                                                   |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `placeholder` | Input placeholder text.                                                                                                                                                                                                                                                                                       |
| `pattern`     | A pattern the field value should match, defined as a string (regular expression). Only for postal code fields.                                                                                                                                                                                                |
| `styles`      | An object of CSS rules to style the input inside the iframe. See [Styles](https://docs.gr4vy.com/guides/payments/secure-fields/theming) for more information.                                                                                                                                                 |
| `onBlur`      | Attaches 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`).                                                                                                                             |
| `onFocus`     | Attaches 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`).                                                                                                                            |
| `onInput`     | Attaches 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`). |

Each field component supports a `ref` that exposes a `clear()` method to reset the value programmatically.

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

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

  return (
    <>
      <CardNumber ref={cardNumberRef} />
      <button type="button" onClick={() => cardNumberRef.current?.clear()}>
        Clear
      </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](https://docs.gr4vy.com/guides/payments/secure-fields/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.

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

...

const { secureFields } = useSecureFields()

<ClickToPay
  dpaLocale="en_AU"
  cardBrands={['mastercard', 'visa', 'american-express']}
  email="john@example.com"
  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 Name         | Description                                                                                                                                                                                                                                                                                           |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `srcDpaId`        | DPA Identifier. This is a unique identifier for you Digital Payment Application (DPA), which was generated during onboarding.                                                                                                                                                                         |
| `dpaName`         | Legal name of registered DPA.                                                                                                                                                                                                                                                                         |
| `cardBrands`      | List of card schemes the merchant accepts. We currently support `mastercard`, `maestro`, `visa`, `amex`, `discover`                                                                                                                                                                                   |
| `consentCheckbox` | A reference to the opt-in consent checkbox element.                                                                                                                                                                                                                                                   |
| `learnMoreLink`   | A reference to the learn more link element.                                                                                                                                                                                                                                                           |
| `email`           | The user email used to access Click to Pay.                                                                                                                                                                                                                                                           |
| `mobileNumber`    | The user phone number used to access Click to Pay. Required format is `{ countryCode: string, phoneNumber: string }`                                                                                                                                                                                  |
| `dynamicDataType` | The type of cryptogram or token used for the card data. See the [Mastercard docs](https://developer.mastercard.com/unified-checkout-solutions/documentation/sdk-reference/parameters/#payment-options) for more information. Possible values are `NONE` and `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 Name                         | Description                                                                                                                                                                                                                                                                                                                                                                                               |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onClickToPayInitialized`         | An event handler that listens for Click to Pay to be securely initialized. It listens for the [`CLICK_TO_PAY_INITIALIZED`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function with a `clickToPay` instance as argument.                                                                                                                     |
| `onClickToPayReady`               | An event handler that listens for Click to Pay to be ready. It listens for the [`CLICK_TO_PAY_READY`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function with an object `{ buyerExists: boolean }`.                                                                                                                                         |
| `onClickToPaySignOut`             | An event handler that listens for users signing out of Click to Pay. It listens for the [`CLICK_TO_PAY_SIGN_OUT`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function.                                                                                                                                                                       |
| `onClickToPayError`               | An event handler that listens for any errors thrown by Click to Pay. It listens for the [`CLICK_TO_PAY_ERROR`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) 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'). |
| `onClickToPayCancel`              | An event handler that listens for users closing / cancelling Click to Pay. It listens for the [`CLICK_TO_PAY_CANCEL`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function.                                                                                                                                                                   |
| `onClickToPayCheckoutWithNewCard` | An event handler that listens for users checking out with a new card. It listens for the [`CLICK_TO_PAY_CHECKOUT_WITH_NEW_CARD`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function.                                                                                                                                                        |
| `onClickToPayUnableToLoadDpa`     | An 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`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function.                                                                                                                                          |
| `onMethodChange`                  | An event handler that listens for users selecting a different method (either `card` or `click-to-pay`). It listens for the [`METHOD_CHANGE`](https://docs.gr4vy.com/guides/payments/secure-fields/events#global-events) event and accepts a callback function with the selected method.                                                                                                                   |