# JavaScript

_Encrypt data client-side, collect card details & perform 3D Secure authentication._

## Installation

Our JavaScript SDK is distributed from our CDN and can be loaded with a simple script tag. The SDK must be loaded directly from our CDN and cannot be bundled with your application or self hosted.

```html
<script src="https://js.evervault.com/v2"></script>
```

### Using npm

You can also install Evervault via the `@evervault/js` package on npm. This package is a light wrapper which handles loading the SDK from our CDN and also provides TypeScript definitions.

```javascript
import { loadEvervault } from "@evervault/js";

const evervault = loadEvervault("<TEAM_ID>", "<APP_ID>");
```

Note: It is important to note that for PCI Compliance you must load the Evervault SDK directly from our CDN and cannot bundle it with your application. The loadEvervault function will always load the latest version of the Evervault SDK regardless of which version of @evervault/js you are using.

### Asynchronous Loading

You can load the SDK asynchronously using the `async` attribute on the script tag to prevent blocking the loading of your page. However, it is important to note that you will need to wait for the SDK to load before making any API calls.

```html
<!DOCTYPE html>
<html>
  <head>
    <script
      src="https://js.evervault.com/v2"
      onload="onEvervaultReady()"
      async
    ></script>
    <script>
      function onEvervaultReady() {
        const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
      }
    </script>
  </head>
</html>
```

## Usage

Once loaded, you can initialize the Evervault SDK with your Team and App ID found in the [Evervault Dashboard](https://app.evervault.com).

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
const encrypted = await evervault.encrypt("Hello, World!");
```

## Reference

### Evervault

Creates an instance of the Evervault SDK using your Team and App ID.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
```

**Parameters**

- `teamId` `string` _(required)_ — The ID of your Evervault team. This can be found inside of your team settings on the [Evervault dashboard](https://app.evervault.com).
- `appId` `string` _(required)_ — The ID of your Evervault app. This can be found inside of your app settings on the [Evervault dashboard](https://app.evervault.com).

### encrypt

Encrypts data using Evervault Encryption. The encrypted data can be stored in your database or file storage as normal. Evervault Strings can be used across all of our products. Evervault File Encryption is currently in Beta, and files can only be decrypted with Relay.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
const encrypted = await evervault.encrypt("Hello, world!");
```

**Parameters**

- `data` `string | Data | File | Blob` _(required)_ — The data to encrypt

### decrypt

Decrypts data previously encrypted with an Evervault product or SDK.

The decrypt() function uses Client-Side Tokens. The token can be generated using our backend SDKs or through our REST API.

The payload must be the same payload that was used to create the token and expires in a maximum of 10 minutes depending on the expiry set when creating the token.

```javascript
const encrypted = await evervault.encrypt("Hello, world!");
await evervault.decrypt("<CLIENT-SIDE-TOKEN>", encrypted);
```

**Parameters**

- `clientSideToken` `string` _(required)_ — A [Client-Side Token](/) with permission to decrypt the given payload.
- `encryptedData` `string` _(required)_ — The encrypted data to decrypt.

### ui.card

Initializes a Card component for [Card Collection](/cards/card-collection). The Card component makes it easy to collect and encrypt card data in a completely PCI-compliant environment.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");

const card = evervault.ui.card({
  theme: evervault.ui.themes.clean(),
});

card.on("change", (payload) => {
  console.log(payload.card.number);
  // ev:...
});

card.mount("#ev-card-fields");
```

**Parameters**

- `theme` — Allows you to completely customize the appearance of the component. See [Custom Styling](#custom-styling) for more information.
- `icons` `Boolean | Record<brand, string>` — If set to true, the component will display icons for the detected card brand. You can customize icons by passing an object with the brand as the key and src URL as the value.
- `autoFocus` `Boolean` — If set to true, the component will automatically focus when it mounts.
- `autoProgress` `Boolean` — If set to true, the component automatically moves focus to the next field when the current field is complete.
- `autoComplete` `Object` — Controls browser autocomplete behavior per field.
  - `autoComplete.name` `Boolean` — Enable browser autocomplete for the name field.
  - `autoComplete.number` `Boolean` — Enable browser autocomplete for the card number field.
  - `autoComplete.expiry` `Boolean` — Enable browser autocomplete for the expiry field.
  - `autoComplete.cvc` `Boolean` — Enable browser autocomplete for the CVC field.
- `acceptedBrands` `string[]` — Restricts the component to only accept the specified card brands. If not provided, all brands are accepted. Possible values are `visa`, `mastercard`, `american-express`, `diners-club`, `discover`, `jcb`, `unionpay`, `maestro`, `elo`, `mir`, `hiper`, `hipercard`, `szep`, `uatp`, `rupay`. Custom brands defined using `customBrands` are accepted regardless of this list.
- `customBrands` `CustomBrand[]` — An array of custom card brand definitions created with [`brands.create`](#brands-create). Custom brands are always accepted, even when `acceptedBrands` is set. See the [custom card brands](/cards/card-collection?client=browser#custom-card-brands) section for usage examples.
- `fields` `string[]` — Allows you to configure the fields displayed in the component. Possible values are 'name', 'number', 'expiry', and 'cvc'. By default only 'number', 'expiry' and 'cvc' will be shown.
- `defaultValues` `Object` — Sets default values for card fields on mount.
  - `defaultValues.name` `string` — Default value for the cardholder name field.
- `redactCVC` `Boolean` — Sets the `type` attribute of the CVC field to `password` in order to visually redact the CVC field..
- `allow3DigitAmexCVC` `Boolean` — If set to false, rejects 3-digit CVCs for American Express cards and requires a 4-digit CVC. Defaults to `true`.
- `colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
- `translations` `Object` — Allows you to customize the text shown inside of the component.
  - `translations.name.label` — Customize the label for the name field.
  - `translations.name.placeholder` — Customize the placeholder for the name field.
  - `translations.name.errors.invalid` — Customize the error message for the name field when the value is invalid.
  - `translations.name.errors.regex` — Customize the error message for when the name field fails regex validation.
  - `translations.number.label` — Customize the label for the number field.
  - `translations.number.placeholder` — Customize the placeholder for the number field.
  - `translations.number.errors.invalid` — Customize the error message for the number field when the value is invalid.
  - `translations.expiry.label` — Customize the label for the expiry field.
  - `translations.expiry.placeholder` — Customize the placeholder for the expiry field.
  - `translations.expiry.errors.invalid` — Customize the error message for the expiry field when the value is invalid.
  - `translations.cvc.label` — Customize the label for the cvc field.
  - `translations.cvc.placeholder` — Customize the placeholder for the cvc field.
  - `translations.cvc.errors.invalid` — Customize the error message for the cvc field when the value is invalid.
- `validation` `Object` — Allows you to customize validation logic for the component.
  - `validation.name.regex` `RegExp` — A regex pattern that the name must match in order to be considered valid. You can use this option to only allow certain characters.
  - `validation.cvc.optional` `Boolean` — When set to `true`, the CVC field is treated as optional. The card is considered valid even if no CVC is entered. If a CVC is entered, it is validated as normal. Defaults to `false`.

#### card.mount

Mounts the component to a given DOM node.

```javascript
card.mount("#card-details");
```

#### card.on('change')

Subscribe to changes made to the component. The encrypted card details can be accessed from the payload passed to the callback. The change event will fire any time there is a state update in the component. This includes when the user types in a field, looses focus on a field, or when an error is displayed.

```javascript
card.on("change", (data) => {
  console.log(data.card.number);
  // ev:...
});
```

**Callback Parameters**

- `data.card` `Object` — Information about the entered card, including meta data as well as the encrypted number aned CVC.
  - `data.card.number` `string` — The encrypted card number.
  - `data.card.brand` `string` — The card brand.
  - `data.card.lastFour` `string` — The last four digits of the card number.
  - `data.card.bin` `string` — The bin for the card. This will only be present if the number is valid.
  - `data.card.expiry.month` `string` — The month of the card expiry date.
  - `data.card.expiry.year` `string` — The year of the card expiry date.
  - `data.card.cvc` `string` — The encrypted CVC.
  - `data.card.name` `string` — The card holder name.
- `data.errors` `Record<string, string>` — Validation errors related to the card details.
- `data.isValid` `Boolean` — Whether or not there are any errors shown. Validation occurs as the user looses focus on a field. You can force validation to occur with the .validate method. **Note**: This field represents if there are any errors shown, not if the card details are valid. You should use the isComplete field to determine if the user has successfully entered a valid card.
- `data.isComplete` `Boolean` — Whether or not the card details are valid. This will only be true if the user has entered a valid card number, expiry date and CVC.

#### card.on('complete')

The complete event will fire once the user has successfully filled out all fields in the Card Component with valid values.

```javascript
card.on("complete", (data) => {
  console.log(data.card.number);
  // ev:...
});
```

**Callback Parameters**

- `data.card` `Object` — Information about the entered card, including meta data as well as the encrypted number aned CVC.
  - `data.card.number` `string` — The encrypted card number.
  - `data.card.brand` `string` — The card brand.
  - `data.card.lastFour` `string` — The last four digits of the card number.
  - `data.card.bin` `string` — The bin for the card. This will only be present if the number is valid.
  - `data.card.expiry.month` `string` — The month of the card expiry date.
  - `data.card.expiry.year` `string` — The year of the card expiry date.
  - `data.card.cvc` `string` — The encrypted CVC.
  - `data.card.name` `string` — The card holder name.
- `data.errors` `Record<string, string>` — Validation errors related to the card details.
- `data.isValid` `Boolean` — Whether or not there are any errors shown. Validation occurs as the user looses focus on a field. You can force validation to occur with the .validate method. **Note**: This field represents if there are any errors shown, not if the card details are valid. You should use the isComplete field to determine if the user has successfully entered a valid card.
- `data.isComplete` `Boolean` — Whether or not the card details are valid. This will only be true if the user has entered a valid card number, expiry date and CVC.

#### card.on('ready')

The ready event will be fired once the component has fully loaded and is ready to be displayed. This is often used to show a loading state while the component loads.

```javascript
card.on("ready", () => {
  document.getElementById("loading").addClass("hide");
  document.getElementById("card-details").removeClass("hide");
});
```

#### card.on('error')

The error event will be fired if the component fails to load. If you want to respond to validation errors you should use the [change event](#cardonchange) instead.

```javascript
card.on("error", () => {
  alert("Opps, something went wrong!");
});
```

#### card.on('swipe')

Subscribe to swipe events from card readers. The encrypted card details can be accessed from the payload passed to the callback. The component must have focus for the card reader event to be detected.

```javascript
card.on("swipe", (data) => {
  console.log(data.card.number);
  // ev:...
});
```

**Callback Parameters**

- `data.card` `Object` — Information about the entered card, including meta data as well as the encrypted number aned CVC.
  - `data.card.number` `string` — The encrypted card number.
  - `data.card.brand` `string` — The card brand.
  - `data.card.lastFour` `string` — The last four digits of the card number.
  - `data.card.bin` `string` — The bin for the card. This will only be present if the number is valid.
  - `data.card.month` `string` — The month of the card expiry date.
  - `data.card.year` `string` — The year of the card expiry date.
  - `data.card.cvc` `string` — The encrypted CVC.
  - `data.card.firstName` `string` — The card holder first name if one was detected.
  - `data.card.lastName` `string` — The card holder last name if one was detected.

#### card.on('validate')

Fired when `card.validate()` is called. Use this to read the validation result after triggering programmatic validation.

```javascript
card.on("validate", (data) => {
  console.log(data.isValid);
});

card.validate();
```

**Callback Parameters**

- `data.card` `Object` — Information about the card, including metadata, the encrypted number, and CVC.
  - `data.card.number` `string` — The encrypted card number.
  - `data.card.brand` `string` — The card brand.
  - `data.card.lastFour` `string` — The last four digits of the card number.
  - `data.card.bin` `string` — The BIN for the card. Only present when a valid card numbers is entered.
  - `data.card.expiry.month` `string` — The month of the card expiry date.
  - `data.card.expiry.year` `string` — The year of the card expiry date.
  - `data.card.cvc` `string` — The encrypted CVC.
  - `data.card.name` `string` — The cardholder name.
- `data.isValid` `Boolean` — Whether all fields are currently valid.
- `data.isComplete` `Boolean` — Whether all required fields are currently valid.
- `data.errors` `Record<string, string>` — Validation errors for each field.

#### card.on('focus')

Fired when a card field receives focus.

```javascript
card.on("focus", (event) => {
  console.log(event.field); // "number" | "expiry" | "cvc" | "name"
});
```

**Callback Parameters**

- `event.field` `string` — The field that received focus. One of `name`, `number`, `expiry`, or `cvc`.
- `event.data` `Object` — The current card payload at the time of the event. Same shape as the `change` event payload.

#### card.on('blur')

Fired when a card field loses focus.

```javascript
card.on("blur", (event) => {
  console.log(event.field); // "number" | "expiry" | "cvc" | "name"
});
```

**Callback Parameters**

- `event.field` `string` — The field that lost focus. One of `name`, `number`, `expiry`, or `cvc`.
- `event.data` `Object` — The current card payload at the time of the event.

#### card.on('keyup')

Fired on a key-up event within a card field.

```javascript
card.on("keyup", (event) => {
  console.log(event.field);
});
```

**Callback Parameters**

- `event.field` `string` — The active field. One of `name`, `number`, `expiry`, or `cvc`.
- `event.data` `Object` — The current card payload at the time of the event.

#### card.on('keydown')

Fired on a key-down event within a card field.

```javascript
card.on("keydown", (event) => {
  console.log(event.field);
});
```

**Callback Parameters**

- `event.field` `string` — The active field. One of `name`, `number`, `expiry`, or `cvc`.
- `event.data` `Object` — The current card payload at the time of the event.

#### card.update()

Update the configuration for the component after it has been initialized. Any arguments passed will be merged with the arguments passed when the component was initialized. This can be used to dynamically update the translations for the component, or update the styling.

```javascript
card.update({
  translations: {
    number: {
      label: "uimhir chárta",
    },
  },
});
```

**Parameters**

- `theme` — Allows you to completely customize the appearance of the component. See [Custom Styling](#custom-styling) for more information.
- `icons` `Boolean | Record<brand, string>` — If set to true, the component will display icons for the detected card brand. You can customize icons by passing an object with the brand as the key and src URL as the value.
- `autoFocus` `Boolean` — If set to true, the component will automatically focus when it mounts.
- `autoProgress` `Boolean` — If set to true, the component automatically moves focus to the next field when the current field is complete.
- `autoComplete` `Object` — Controls browser autocomplete behavior per field.
  - `autoComplete.name` `Boolean` — Enable browser autocomplete for the name field.
  - `autoComplete.number` `Boolean` — Enable browser autocomplete for the card number field.
  - `autoComplete.expiry` `Boolean` — Enable browser autocomplete for the expiry field.
  - `autoComplete.cvc` `Boolean` — Enable browser autocomplete for the CVC field.
- `acceptedBrands` `string[]` — Restricts the component to only accept the specified card brands. If not provided, all brands are accepted. Possible values are `american-express`, `visa`, `mastercard`, `discover`, `jcb`, `diners-club`, `unionpay`, `maestro`, `mir`, `elo`, `hipercard`, `hiper`, `szep`, `uatp`, `rupay`. Custom brands defined using `customBrands` are accepted regardless of this list.
- `customBrands` `CustomBrand[]` — An array of custom card brand definitions created with [`brands.create`](#brands-create). Custom brands are always accepted, even when `acceptedBrands` is set.
- `colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
- `fields` `string[]` — Allows you to configure the fields displayed in the component. Possible values are 'name', 'number', 'expiry', and 'cvc'. By default only 'number', 'expiry' and 'cvc' will be shown.
- `defaultValues` `Object` — Sets default values for card fields.
  - `defaultValues.name` `string` — Default value for the cardholder name field.
- `allow3DigitAmexCVC` `Boolean` — If set to false, rejects 3-digit CVCs for American Express cards and requires a 4-digit CVC. Defaults to `true`.
- `translations` `Object` — Allows you to customize the text shown inside of the component.
  - `translations.name.label` — Customize the label for the name field.
  - `translations.name.placeholder` — Customize the placeholder for the name field.
  - `translations.name.errors.invalid` — Customize the error message for the name field when the value is invalid.
  - `translations.name.errors.regex` — Customize the error message for when the name field fails regex validation.
  - `translations.number.label` — Customize the label for the number field.
  - `translations.number.placeholder` — Customize the placeholder for the number field.
  - `translations.number.errors.invalid` — Customize the error message for the number field when the value is invalid.
  - `translations.expiry.label` — Customize the label for the expiry field.
  - `translations.expiry.placeholder` — Customize the placeholder for the expiry field.
  - `translations.expiry.errors.invalid` — Customize the error message for the expiry field when the value is invalid.
  - `translations.cvc.label` — Customize the label for the cvc field.
  - `translations.cvc.placeholder` — Customize the placeholder for the cvc field.
  - `translations.cvc.errors.invalid` — Customize the error message for the cvc field when the value is invalid.
- `validation` `Object` — Allows you to customize validation logic for the component.
  - `validation.name.regex` `RegExp` — A regex pattern that the name must match in order to be considered valid. You can use this option to only allow certain characters.
  - `validation.cvc.optional` `Boolean` — When set to `true`, the CVC field is treated as optional. The card is considered valid even if no CVC is entered. If a CVC is entered, it is validated as normal. Defaults to `false`.

#### card.validate()

Manually trigger validation for the card details fields. This method is useful if you want to force validation to display error messages inside of the component. This is an asynchronous operation and will not return an immediate result. You can use the `validate` event to listen for the result of calling this method.

```javascript
card.on("validate", (data) => {
  console.log(data.isValid);
});

card.validate();
```

#### card.unmount()

Removes the component from the DOM.

```javascript
card.unmount();
```

### brands.create

Creates a custom card brand definition that can be passed to the `customBrands` option on [`ui.card`](#uicard). Use this to add support for card networks that aren't included in Evervault's built-in brand list.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");

const acmeBrand = evervault.brands.create("acme-card", {
  numberValidationRules: {
    ranges: [[88000, 88999]],
    lengths: [16],
  },
  securityCodeValidationRules: {
    lengths: [3],
  },
});

const card = evervault.ui.card({
  customBrands: [acmeBrand],
});
```

**Parameters**

- `name` `string` _(required)_ — A unique identifier for the brand. This value is returned in the `localBrands` array of the card change payload.
- `options` `Object` _(required)_ — Configuration for the custom brand.
  - `options.numberValidationRules` `Object` _(required)_ — Rules used to validate card numbers for this brand.
    - `options.numberValidationRules.ranges` `Array<number | [number, number]>` _(required)_ — Bank identification number (BIN) prefixes or ranges that identify cards belonging to this brand. A single number matches cards starting with that prefix (e.g., `9900`). A two-element tuple defines an inclusive range of BIN prefixes (e.g., `[88000, 88999]`).
    - `options.numberValidationRules.lengths` `number[]` _(required)_ — The valid card number lengths for this brand.
    - `options.numberValidationRules.luhnCheck` `Boolean` — Whether to validate the card number using the Luhn algorithm. Defaults to `true`.
  - `options.securityCodeValidationRules` `Object` _(required)_ — Rules used to validate the CVC for this brand.
    - `options.securityCodeValidationRules.lengths` `Array<3 | 4>` _(required)_ — The valid CVC lengths for this brand. Accepts 3, 4 or both.
  - `options.iconSrc` `string` — A URL for the brand's icon. Displayed in the card component when a matching card number is entered.

### ui.pin

Initializes a component for collecting and encrypting PIN numbers in a PCI-compliant environment.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");

const pin = evervault.ui.pin({
  length: 4,
  mode: "numeric",
});

pin.on("complete", (data) => {
  console.log(data.value); // encrypted PIN
});

pin.mount("#pin-field");
```

**Parameters**

- `theme` — Allows you to customize the component's appearance. See [Custom Styling](#custom-styling) for more information.
- `colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
- `length` `number` — The number of PIN digits to collect. Defaults to `4`, maximum `10`.
- `autoFocus` `Boolean` — If set to true, the component automatically focuses when it mounts.
- `mode` `"numeric" | "alphanumeric"` — If set to `"alphanumeric"`, the PIN field accepts letters as well as digits. Defaults to `"numeric"`.
- `inputType` `"number" | "text" | "password"` — Sets the `type` attribute of the underlying input elements used to capture the PIN. Defaults to `"number"`.

#### pin.mount()

Mounts the component to a given DOM node.

```javascript
pin.mount("#pin-field");
```

#### pin.on('change')

Fired whenever the PIN value changes.

```javascript
pin.on("change", (data) => {
  console.log(data.value); // encrypted PIN or null
  console.log(data.isComplete);
});
```

**Callback Parameters**

- `data.value` `string | null` — The encrypted PIN value, or `null` if the field is empty.
- `data.isComplete` `Boolean` — Whether the PIN field is complete.

#### pin.on('complete')

Fired when the user enters all PIN digits.

```javascript
pin.on("complete", (data) => {
  console.log(data.value); // encrypted PIN
});
```

**Callback Parameters**

- `data.value` `string | null` — The encrypted PIN value.
- `data.isComplete` `Boolean` — Whether the PIN field is complete.

#### pin.on('ready')

Fired when the component loads and is ready to be displayed.

```javascript
pin.on("ready", () => {
  document.getElementById("pin-field").style.display = "block";
});
```

#### pin.on('error')

Fired if the component fails to load.

```javascript
pin.on("error", () => {
  console.error("PIN component failed to load");
});
```

#### pin.update()

Updates the component configuration after initialization. Any arguments passed are merged with the original options.

```javascript
pin.update({ length: 6 });
```

#### pin.unmount()

Removes the component from the DOM.

```javascript
pin.unmount();
```

### ui.threeDSecure

The ThreeDSecure component can be used in combination with the Evervault API to perform [3D Secure](/cards/3d-secure?client=Browser) authentication. In order to use the ThreeDSecure component you must first [create a 3D Secure session](api#createThreeDSSession) on your backend and pass it to your frontend. The component will display the 3D Secure iframe and handle the authentication process.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
const threeDSecure = evervault.ui.threeDSecure("tds_visa_123456789");
threeDSecure.mount();
```

**Parameters**

- `session` `string` _(required)_ — The 3D Secure session ID. A 3D Secure session can be created using the [Create 3D Secure Session](/api#createThreeDSSession) API endpoint.
- `options` — Configuration options for the ThreeDSecure component.
  - `options.colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
  - `options.theme` `Object` — Allows you to customize the appearance of the component. See [Custom Styling](#custom-styling) for more information. **Note**: You can't customize the appearance of the iframe content itself. This is controlled by the card issuer.
  - `options.size` `{ width: string, height: string }` — This size of the 3D Secure iframe. Card issuers are required to support content at 250x400, 390x400, 500x600, 600x400. The default size is 500x600.
  - `options.failOnChallenge` `Boolean | () => Boolean | () => Promise<Boolean>` — If set to true, the component will fail 3DS authentication when a challenge is requested and no challenge will be shown. Alternatively, you can provide a function which will be called when a challenge is requested. If the function returns true 3DS authentication will fail, if it returns false the challenge will be shown.

#### threeDSecure.mount()

Mounts the component to the DOM. If no selector is provided the component will be rendered as a modal window.

```javascript
threeDSecure.mount();
```

**Parameters**

- `selector` `string` — The selector of the DOM node to mount the component to. If no selector is provided the component will be rendered as a modal window.

#### threeDSecure.on('success')

The 'success' event will be fired once the 3D Secure authentication process has been completed successfully. You should use this event to trigger your backend to finalize the payment. Your backend can use the [Retrieve 3DS Session](/api#retrieveThreeDSSession) endpoint to retrieve the cryptogram for the session and complete the payment.

**Note**: The component is automatically unmounted after the 'success' event is fired.

```javascript
threeDSecure.on("success", () => {
  // 3DS is complete and payment can be finalized
});
```

#### threeDSecure.on('failure')

The 'failure' event will be fired if the 3D Secure authentication process fails. You should use this event to handle the failure and inform the user and prompt them to try again.

**Note**: The component is automatically unmounted after the 'failure' event is fired.

```javascript
threeDSecure.on("failure", () => {
  // 3DS failed and user should be informed
});
```

#### threeDSecure.on('ready')

The ready event will be fired once the component has fully loaded and is ready to be displayed. This is often used to show a loading state while the component loads.

```javascript
threeDSecure.on("ready", () => {
  document.getElementById("threeDSecure").removeClass("hide");
});
```

#### threeDSecure.on('error')

The error event will be fired if the component fails to load.

```javascript
threeDSecure.on("error", (error) => {
  console.error(error);
});
```

**Callback Parameters**

- `error.error` `String` — A unique code representing the error that occurred.
- `error.message` `String` — A human readable message describing the error.

#### threeDSecure.update()

Update the configuration for the component after it has been initialized. Any arguments passed will be merged with the arguments passed when the component was initialized.

```javascript
threeDSecure.update({
  size: {
    width: "300px",
    height: "400px",
  },
});
```

**Parameters**

- `colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
- `theme` — Allows you to customize the appearance of the component. See [Custom Styling](#custom-styling) for more information. **Note**: You can't customize the appearance of the iframe content itself. This is controlled by the card issuer.
- `size` `{ width: string, height: string }` — This size of the 3D Secure iframe. Card issuers are required to support content at 250x400, 390x400, 500x600, 600x400. The default size is 500x600.
- `failOnChallenge` `Boolean | () => Boolean | () => Promise<Boolean>` — If set to true, the component will fail 3DS authentication when a challenge is requested and no challenge will be shown. Alternatively, you can provide a function which will be called when a challenge is requested. If the function returns true 3DS authentication will fail, if it returns false the challenge will be shown.

#### threeDSecure.unmount()

Removes the component from the DOM.

```javascript
threeDSecure.unmount();
```

### ui.reveal

The Reveal component allows you to display previously encrypted card data to your users in plaintext in a secure iframe hosted by Evervault. Before using Reveal you'll first need to have a JSON endpoint to retrieve data from. This is often your own API endpoint combined with Relay to decrypt previously encrypted data from your database or a third-party API.

> It is important that the endpoint that you create sets the applicable CORS
>   headers so that it can be accessed from the Reveal iframe. Otherwise your
>   requests will fail!

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
// Create a request to your endpoint to fetch the data
const request = new Request("<YOUR_ENDPOINT>");
// Create a reveal instance, passing the request as an argument
const reveal = evervault.ui.reveal(request);
// Use JSON path to select the data in the response you want to
// display and mount it to the DOM.
reveal.text("$.card.number").mount("#card-number");
```

#### reveal.on("ready")

The ready event will be fired once the request has been completed and all reveal consumer components are ready to be shown.

```javascript
reveal.on("ready", () => {
  console.log("Reveal is ready");
});
```

#### reveal.on("error")

The error event will be fired if the Reveal Component fails to load or the passed request fails.

```javascript
reveal.on("error", () => {
  console.log("Something went wrong");
});
```

#### reveal.text()

Creates a Reveal Text consumer. The Reveal Text consumer allows you to render a selected field from the request response.

```javascript
const request = new Request("<YOUR_ENDPOINT>");
const reveal = evervault.ui.reveal(request);
const text = reveal.text("$.card.number", {
  format: {
    regex: /(.{4})(.{4})(.{4})(.{4})/g,
    replace: "$1 $2 $3 $4",
  },
});

text.mount("#card-number");
```

**Parameters**

- `path` `string` _(required)_ — The JSON path to the field you want to display.
- `options.colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
- `options.theme` `Theme` — Allows you to completely customize the appearance of the component. See [Custom Styling](#custom-styling) for more information.
- `options.format` `Object` — Allows you to use regex matching to format the field value.
  - `format.regex` `RegExp` _(required)_ — The regex statment to match against the value.
  - `format.replace` `string` _(required)_ — The text to replace the value with. You can use $ to reference matched regex groups.

##### text.mount()

Mounts the Reveal Text component to a given DOM node.

```javascript
text.mount("#card-details");
```

##### text.unmount()

Removes the Text Component from the DOM.

```javascript
text.unmount();
```

#### reveal.copyButton()

Creates a Reveal Copy Button consumer. This renders a button which when clicked will copy a response field to the users clipboard.

```javascript
const request = new Request("<YOUR_ENDPOINT>");
const reveal = evervault.ui.reveal(request);
const text = reveal.copyButton("$.card.number", {
  theme: evervault.ui.themes.clean(),
  text: "Copy Number",
  format: {
    regex: /(.{4})(.{4})(.{4})(.{4})/g,
    replace: "$1 $2 $3 $4",
  },
});

text.mount("#card-number");
```

**Parameters**

- `path` `string` _(required)_ — The JSON path to the field you want to display.
- `options.text` `string` — The text to display on the button.
- `options.icon` `string` — A URL for an icon to display on the button.
- `options.colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
- `options.theme` `Theme` — Allows you to completely customize the appearance of the component. See [Custom Styling](#custom-styling) for more information.
- `options.format` `Object` — Allows you to use regex matching to format the field value.
  - `format.regex` `RegExp` _(required)_ — The regex statment to match against the value.
  - `format.replace` `string` _(required)_ — The text to replace the value with. You can use $ to reference matched regex groups.

##### copyButton.on("copy")

The copy event will be fired when the button is clicked and the value has been copied to the clipboard.

```javascript
copyButton.on("copy", () => {
  console.log("Copied to clipboard");
});
```

##### copyButton.mount()

Mounts the Reveal Copy Button component to a given DOM node.

```javascript
copyButton.mount("#node");
```

##### copyButton.unmount()

Removes the Copy Button Component from the DOM.

```javascript
copyButton.unmount();
```

### transactions.create

Creates a transaction object that can be used with Apple Pay and Google Pay components.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
const transaction = evervault.transactions.create({
  amount: 1299,
  currency: "USD",
  country: "US",
  merchantId: "merchant_abc123",
});
```

**Parameters**

- `options.amount` `number` _(required)_ — The transaction amount in smallest currency unit (e.g., cents).
- `options.currency` `string` _(required)_ — The three-letter ISO currency code.
- `options.country` `string` _(required)_ — The two-letter ISO country code.
- `options.merchantId` `string` _(required)_ — Your Evervault merchant ID.
- `options.type` `payment | disbursement | recurring` — Specify the type of transaction. Disbursement requests are only available with Apple Pay. Default: `payment`.
- `options.lineItems` `TransactionLineItem[]` — Optional array of line items to display in the payment sheet.
  - `lineItem.amount` `string` _(required)_ — The line item amount in smallest currency unit.
  - `lineItem.label` `number` _(required)_ — Description of the line item.
- `options.requiredRecipientDetails` `string[]` — Optional array of recipient details required for collection on a disbursement transaction. Possible values: `name`, `email`, `phone`, `address`.
- `options.merchantCapabilities` `string[]` — Optional array of Apple Pay merchant capabilities for disbursement transactions. When omitted, defaults to `supports3DS`, and adds `supportsInstantFundsOut` when `instantTransfer` is set. Supported values: `supports3DS`, `supportsEMV`, `supportsCredit`, `supportsDebit`, `supportsInstantFundsOut`. On iOS the equivalent is the singular `merchantCapability` field on `DisbursementTransaction`.
- `options.managementURL` `string` — URL for managing the recurring payment subscription. Required when `type` is `recurring`.
- `options.billingAgreement` `string` — Description of the billing agreement shown to the user. Required when `type` is `recurring`.
- `options.description` `string` — Description of the recurring payment. Required when `type` is `recurring`.
- `options.regularBilling` `object` — Billing details for the recurring charge. Required when `type` is `recurring`.
  - `regularBilling.amount` `string` _(required)_ — The billing amount as a decimal string (e.g., `"2.13"`).
  - `regularBilling.label` `string` _(required)_ — Description of the billing charge.
  - `regularBilling.recurringPaymentStartDate` `Date` _(required)_ — The start date for the recurring payment.
  - `regularBilling.recurringPaymentIntervalUnit` `minute | hour | day | week | month | year` — The interval unit for the recurring payment frequency. The default value is "month".
  - `regularBilling.recurringPaymentIntervalCount` `number` — The number of interval units between each recurring charge. The default value is 1.
- `options.trialBilling` `object` — Optional trial billing details for the recurring payment.
  - `trialBilling.amount` `string` _(required)_ — The trial billing amount as a decimal string (e.g., `"0.99"`).
  - `trialBilling.label` `string` _(required)_ — Description of the trial billing charge.
  - `trialBilling.trialPaymentStartDate` `Date` _(required)_ — The start date for the trial period.

### ui.applePay

Initializes an Apple Pay button that handles the payment flow and returns encrypted payment details.

In [Sandbox apps](/developers/sandbox), the encrypted `networkToken.number` maps to a [test card](/cards/apple-pay#testing-sandbox) that matches the brand of the card the customer selects in their Apple Wallet.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
const transaction = evervault.transactions.create({
  amount: 1299,
  currency: "USD",
  country: "US",
  merchantId: "<MERCHANT_ID>",
});

const component = evervault.ui.applePay(transaction, {
  process: async (data, { fail }) => {
    try {
      await processPayment(data);
    } catch (error) {
      fail({
        message: "Payment failed",
      });
    }
  },
});

component.mount("#apple-pay");
```

**Parameters**

- `transaction` `Transaction` _(required)_ — The transaction object created with [`transactions.create`](#transactionscreate).
- `options` `Object` _(required)_ — Configuration options for the Apple Pay button.
  - `options.process` `Function` _(required)_ — Callback function called when payment is authorized. Receives encrypted payment data and helper functions.
  - `options.type` `string` — Apple Pay button type. Possible values: `add-money`, `book`, `buy`, `check-out`, `continue`, `contribute`, `donate`, `order`, `pay`, `plain`, `reload`, `rent`, `set-up`, `subscribe`, `support`, `tip`, `top-up`
  - `options.style` `string` — Apple Pay button style. Possible values: `black`, `white`, `white-outline`
  - `options.locale` `string` — An ISO-639-1 code for localization.
  - `options.padding` `string` — The padding around the button as a CSS string with units (e.g., `"10px"`).
  - `options.borderRadius` `string | number` — The border radius of the button. This can be a string with units (e.g., `"10px"`) or a number (e.g., `10`).
  - `options.size` `{ width: number | string, height: number | string }` — An object defining the width and height of the button.
  - `options.allowedCardNetworks` `string[]` — An array of supported card networks. Supported card networks: `AMEX`, `DISCOVER`, `ELECTRON`, `ELO`, `ELO_DEBIT`, `INTERAC`, `JCB`, `MAESTRO`, `MASTERCARD`, `VISA`
  - `options.requestPayerDetails` `string[]` — An array of payer details to request. Possible values: `name`, `email`, `phone`.
  - `options.requestBillingAddress` `boolean` — Whether to request billing address information.
  - `options.requestShipping` `boolean` — Whether to request shipping information.
  - `options.billingContact` `Object` — Prefill billing contact details on the Apple Pay sheet. Requires `requestBillingAddress: true` for the postal address to appear. Payment and recurring transactions only — ignored for disbursements.
    - `options.billingContact.givenName` `string` — Given (first) name.
    - `options.billingContact.familyName` `string` — Family (last) name.
    - `options.billingContact.emailAddress` `string` — Email address.
    - `options.billingContact.phoneNumber` `string` — Phone number.
    - `options.billingContact.addressLines` `string[]` — Street address lines.
    - `options.billingContact.locality` `string` — City or locality.
    - `options.billingContact.administrativeArea` `string` — State, province, or region.
    - `options.billingContact.postalCode` `string` — Postal or ZIP code.
    - `options.billingContact.countryCode` `string` — Two-letter ISO country code.
    - `options.billingContact.country` `string` — Country name.
  - `options.shippingContact` `Object` — Prefill shipping contact details on the Apple Pay sheet. Requires `requestShipping: true` for the postal address to appear. Payment and recurring transactions only — ignored for disbursements. Accepts the same fields as `billingContact`.
  - `options.supportsCouponCode` `boolean` — When `true`, shows a coupon code field on the Apple Pay sheet.
  - `options.couponCode` `string` — Initial coupon code shown in the sheet when `supportsCouponCode` is `true`.
  - `options.onCouponCodeChange` `Function` — Called when the customer changes the coupon code on the sheet. Receives the new coupon code string and must return a promise resolving to an updated `amount` and optional `lineItems`. You can also return an optional `error` (`code`: `couponCodeInvalid` or `couponCodeExpired`, plus `message`) to show validation feedback in the Apple Pay UI. Requires `supportsCouponCode: true`.
  - `options.onPaymentMethodChange` `Function` — Called when the user changes their payment method. Receives the new payment method and returns a promise resolving to an updated `amount` and optional `lineItems`. Requires `requestBillingAddress: true` to receive billing address data.
  - `options.onShippingAddressChange` `Function` — Called when the user changes their shipping address. Receives the new address and returns a promise resolving to an updated `amount` and optional `lineItems`. Requires `requestShipping: true`.
  - `options.prepareTransaction` `Function` — Called before the Apple Pay modal is shown. Use this to perform async logic (e.g., fetch a discount) and return an updated `amount` and optional `lineItems`.
  - `options.appleMerchantId` `string` — Optional Apple Pay merchant identifier for the payment sheet. Defaults to `merchant.com.evervault.{merchantId}`, which works with Evervault's domain verification and merchant-session flow. A custom value is only used by the browser to open the Apple Pay sheet. It doesn't change merchant validation — that still uses Evervault's registered identifier unless separately configured with Apple for your domain.
  - `options.paymentOverrides` `Object` — Advanced overrides for the underlying Payment Request.
    - `options.paymentOverrides.paymentMethodData` `PaymentMethodData[]` — Override the payment method data passed to the Payment Request API.
    - `options.paymentOverrides.paymentDetails` `PaymentDetailsInit` — Override the payment details passed to the Payment Request API.
  - `options.disbursementOverrides` `Object` — Advanced overrides for disbursement Payment Requests.
    - `options.disbursementOverrides.disbursementDetails` `PaymentDetailsInit` — Override the disbursement details passed to the Payment Request API.

The object passed to `options.process` includes metadata on `card` when present. Optional `card.paymentMethodType` is `credit`, `debit`, `prepaid`, or `store` when the wallet reports the funding type for the card the user selected. See the [Apple Pay](/cards/apple-pay#process-the-payment) guide for how this relates to BIN-derived fields such as `funding`.

`paymentDataType` reflects the Apple token format from the credentials API (for example `3DSecure`). `transactionType` indicates the transaction category (`oneOff`, `recurring`, or `disbursement`) based on how you created the transaction. `transactionId` is Apple's identifier for the token, and comes from the [PKPaymentToken header](https://developer.apple.com/documentation/passkit/payment-token-format-reference#Header-keys-and-values). Some payment gateways require it to be passed through, though it isn't used to authorize the transaction itself. `billingContact` and `shippingContact` are only populated when the transaction requested those contact fields. `phoneticFamilyName` and `phoneticGivenName` are populated when the customer's Apple Wallet contact card includes a phonetic reading of their name (common in locales like Japan). If there's no phonetic reading, then these two values are `null`.

#### applePay.mount()

Mounts the Apple Pay button to a given DOM node.

```javascript
component.mount("#apple-pay");
```

#### applePay.unmount()

Removes the Apple Pay button from the DOM. If an Apple Pay session is active, the sheet is dismissed first.

```javascript
component.unmount();
```

#### applePay.abort()

Programmatically dismisses the Apple Pay sheet while a session is in progress. This maps to the browser's [`PaymentRequest.abort()`](https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequest/abort) API. When the sheet closes, the `cancel` event is fired.

Use this when you need to close and reopen Apple Pay — for example, when a shipping address change requires a different currency. Currency cannot be updated mid-session via `onShippingAddressChange`; abort the session, update the transaction, and let the user open Apple Pay again.

```javascript
onShippingAddressChange: async (address) => {
  const newCurrency = currencyForCountry(address.country);

  if (newCurrency !== transaction.details.currency) {
    await apple.abort();
    updateCheckoutCurrency(newCurrency);
    return { amount: 0, lineItems: [] };
  }

  return { amount: updatedAmount, lineItems };
},
```

`abort()` is a no-op when no session is in progress. After the user authorizes payment, use `fail()` in the `process` callback instead.

#### applePay.availability()

Checks whether Apple Pay is available on the current device. Returns a promise resolving to `"available"`, `"unavailable"`, or `"unsupported"`.

```javascript
const availability = await component.availability();

if (availability === "available") {
  component.mount("#apple-pay");
} else {
  // Show a fallback payment method
}
```

#### applePay.on("ready")

Fired when the Apple Pay button is mounted and ready to be displayed.

#### applePay.on("success")

Fired when the payment has been successfully authorized.

#### applePay.on("error")

Fired if there's an error initializing the Apple Pay button.

#### applePay.on("cancel")

Fired when the user cancels the Apple Pay payment flow.

### ui.googlePay

Initializes a Google Pay button that handles the payment flow and returns encrypted payment details.

```javascript
const evervault = new Evervault("<TEAM_ID>", "<APP_ID>");
const transaction = evervault.transactions.create({
  amount: 1299,
  currency: "USD",
  country: "US",
  merchantId: "MERCHANT_ID",
});

const googlePay = evervault.ui.googlePay(transaction, {
  type: "pay",
  color: "black",
  borderRadius: 4,
  allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
  allowedCardNetworks: ["VISA", "MASTERCARD"],
  process: async (data, { fail }) => {
    try {
      await processPayment(data);
    } catch (error) {
      fail({
        message: "Payment failed",
      });
    }
  },
});

googlePay.mount("#google-pay-button");
```

**Parameters**

- `transaction` `Transaction` _(required)_ — The transaction object created with [`transactions.create`](#transactionscreate).
- `options` `Object` _(required)_ — Configuration options for the Google Pay button.
  - `options.process` `Function` _(required)_ — Callback function called when payment is authorized. Receives encrypted payment data and helper functions.
  - `options.type` `string` — Google Pay button type. Possible values: `book`, `buy`, `checkout`, `donate`, `order`, `pay`, `plain`, `subscribe`, `top-up`
  - `options.color` `string` — Google Pay button color. Possible values: `black`, `white`
  - `options.locale` `string` — An ISO-639-1 code for localization.
  - `options.size` `{ width: number | string, height: number | string }` — An object defining the width and height of the button.
  - `options.allowedAuthMethods` `string[]` — Allowed authentication methods. With `CRYPTOGRAM_3DS` set, users on mobile can authenticate with their fingerprint which acts as a Strong Customer Authentication and so a cryptogram and ECI value are returned. Users on web cannot authenticate with their fingerprint so only the PAN is returned. Possible values: `PAN_ONLY`, `CRYPTOGRAM_3DS`
  - `options.allowedCardNetworks` `string[]` — An array of supported card networks. Supported card networks: `AMEX`, `DISCOVER`, `ELECTRON`, `ELO`, `ELO_DEBIT`, `INTERAC`, `JCB`, `MAESTRO`, `MASTERCARD`, `VISA`
  - `options.colorScheme` `string` — Allows you to set the root [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/color-scheme) for the iframe document. For a seamless transparent background, use the same color scheme as the parent document.
  - `options.emailRequired` `boolean` — When set to true, the user will be required to provide their email address.
  - `options.billingAddress` `boolean | Object` — Request billing address information.
    - `billingAddress.format` `FULl | MIN` — Format of the billing address. `FULL` will request the full address, `MIN` will only request name, country code and postal code.
    - `billingAddress.phoneNumber` `boolean` — Whether to request the phone number.

The object passed to `options.process` includes metadata on `card` when present. Optional `card.paymentMethodType` matches Google Pay's funding source for the selected card when available. See the [Google Pay](/cards/google-pay#process-the-payment) guide.

#### googlePay.on("success")

Fired when the payment has been successfully authorized.

#### googlePay.on("error")

Fired if there's an error initializing the Google Pay button.

#### googlePay.on("cancel")

Fired when the user cancels the Google Pay payment flow.

#### googlePay.on("ready")

Fired when the Google Pay button is ready to be displayed.

### Custom Styling

Some components in the SDK allow you to customize the appearance of the component using a `theme` object. A theme is just an object with a `styles` property. This styles property uses a CSS-as-JS format to define CSS rules for the component. These rules will be compiled to CSS and injected into the iframe.

Although you can customize the CSS inside of the iframe, you cannot modify the HTML. We know that layout can have a big impact on style definitions and so to help with this, we apply custom attributes to various elements within the iframe. These attributes are prefixed with ev-.

You can see our premade [Card Collection themes](https://github.com/evervault/evervault-js/tree/master/packages/themes) for an example of how these attributes can be used when creating themes.

```javascript
const theme = {
  styles: {
    ":root": {
      "color-scheme": "light",
    },
    label: {
      fontSize: 11,
      fontWeight: 500,
      textTransform: "uppercase",
    },
    ".error": {
      color: "red",
      fontSize: 12,
      marginTop: 5,
    },
    ".field input": {
      marginTop: 5,
      padding: "8px 12px",
      border: "2px solid #dddddd",
    },
    ".field:focus-within input": {
      borderColor: "#6633ee",
    },
  },
};
```

#### Responsive Styling

You can define media queries inside of the themes `styles` object, however, this may lead to unexpected behaviour as the media queries will be matched against the iframe document, not the parent document. To get around this, we provide a media utility which allows you to define styles based on media queries that match the parent document.

To access the media utility you will need to define your theme as a function that returns a theme object. This function will be passed a utilities object as an argument, which contains the media utility. The media utility should be spread into the styles object of the returned theme.

```javascript
const theme = (utilities) => {
  return {
    styles: {
      label: {
        fontSize: 16,
      },
      ...utilities.media("(max-width: 400px)", {
        label: {
          fontSize: 20,
        },
      }),
    },
  };
};
```

