> ## Documentation Index
> Fetch the complete documentation index at: https://developer.hellgate.io/llms.txt
> Use this file to discover all available pages before exploring further.

# API

> Web SDK API reference for client sessions and payment processing.

## Create Client

This method will create and initialise the Hellgate® client using an existing `session_id`.

```javascript theme={null}
const { Hellgate } = window;
const client = await Hellgate.init('7f2c9460-7e2e-403f-a08a-bc58cdcaea83', {
  base_url: 'https://sandbox.hellgate.io',
});
```

| Parameter | Type   | Required? | Description                                                                             |
| --------- | ------ | --------- | --------------------------------------------------------------------------------------- |
| sessionID | String | Yes       | The session id that was handed over to the integrator as part of an action requirement. |
| options   | Object | No        | [Options](#element-options) to customise the form to specific requirements              |

### Options

| Attribute                   | Type        | Description                                                                          |
| --------------------------- | ----------- | ------------------------------------------------------------------------------------ |
| base\_url                   | String      | Set custom Hellgate® backend. Default -`https://api.hellgate.io`                     |
| challenge\_3ds\_container   | HTMLElement | Custom DOM container for rendering 3D Secure Challenge iframe. Default - `undefined` |
| challenge\_3ds\_label\_text | String      | Display custom label text for 3D Secure Challenge iframe                             |

### Session Complete

This event is called once the session is completely finished.

```javascript theme={null}
client.onSessionComplete((result) => {
  // handling logic
});
```

The handler receives a `result` object.

#### Session Result

| Attribute | Type                                | Description                      |
| --------- | ----------------------------------- | -------------------------------- |
| status    | "success" \| "failure" \| "pending" | Status of the current processing |
| data      | Object                              | Result data                      |

#### Session Result status

| Name    | Description                                                                                                                                                                                                                                                                           |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| success | The SDK session was completed successfully. Result could be found in the `data` attribute                                                                                                                                                                                             |
| failure | The SDK session failed. Failure reason and reason code could be found in the `data` attribute                                                                                                                                                                                         |
| pending | The SDK session concluded successfully; however, the ultimate outcome of the operation initiated by the session remains indeterminate due to its asynchronous nature. The definitive results will be delivered to the backend via webhook or can be retrieved through an API request. |

## Create Card Handler

In order to process card payments (and later other payment methods as well), a handler has to be obtained from the client.

```javascript theme={null}
const cardHandler = await client.use('CARD');
```

## Reset Card Handler

This method will remove the card form or card fields from the client, disconnect handlers and unmount the fields from the DOM.

```javascript theme={null}
cardHandler.reset();
```

## Handling Cards

### Create Card Form

This method will create a new one-line card form.

```javascript theme={null}
const cardForm = cardHandler.createForm(options);
```

#### Parameters

| Parameter | Type   | Required? | Description                                                                 |
| --------- | ------ | --------- | --------------------------------------------------------------------------- |
| options   | Object | No        | [Options](#element-options) to customise the form to specific requirements. |

### Create Card Fields

This method will create the full set of card fields as shown below in the demo.

```javascript theme={null}
const { cardNumber, expiryDate, securityCode } = cardHandler.createFormFields(options);
```

#### Parameters

| Parameter                 | Type   | Required?                  | Description                                                                                                                                                                                                                                                         |
| ------------------------- | ------ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| options                   | Object | No                         | [Options](#element-options) to customise the form fields to specific requirements. The options can be prefixed with `cardNumber: {}`, `expiryDate: {}`, and `securityCode: {}` to apply them specifically (e.g. `cardNumber: {placeholder: 'Custom Placeholder'}`). |
| options.expiryDateElement | String | `"combined" \| "separate"` | `combined` - expiration month and year is a single form field. `separate` - expiration month and year are two separate fields. Default: `combined`.                                                                                                                 |

### Create Text Field

The "text" element type is a secure replacement for the `<input>` tag and enables collecting user string data like Cardholder Name as demonstrated.

```javascript theme={null}
cardHandler.createTextField({ placeholder: 'Cardholder Name' });
```

The created `TextField` can be directly passed as a property for `additionalData` and the value does not need to be extracted.

#### Parameters

| Parameter | Type   | Required? | Description                                                                        |
| --------- | ------ | --------- | ---------------------------------------------------------------------------------- |
| options   | Object | No        | [Options](#element-options) to customise the form fields to specific requirements. |

### 3D-Secure

3D Secure handling works out of the box with the SDK and usually doesn't require any extra code.

### Process

This method will read the data from the card form or the card fields and send them to processing. Prerequisite is that card fields or a card form was created before. A loading indicator can be shown until the promise is resolved.

```javascript theme={null}
const result = await cardHandler.process({
  // cardholderTextField can be created by cardHandler.createTextField()
  // the value from the text field will be extracted automatically during processing
  cardholder_name: cardholderTextField,
});
```

We recommend performing a preliminary check to ensure that the card [data](#formstatechange) is complete and valid before calling this method. Otherwise, the promise returned by the `cardHandler.process()` call will be rejected with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object.

#### Parameters

| Parameter      | Type   | Required? | Description                                                      |
| -------------- | ------ | --------- | ---------------------------------------------------------------- |
| additionalData | Object | No        | Further information that needs to be passed into the processing. |

#### Additional Data

| Attribute                     | Type                | Description                                                                                                |
| ----------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------- |
| cardholder\_name              | String \| TextField | The name of the cardHolder                                                                                 |
| email                         | String \| TextField | Email address of the customer                                                                              |
| billing\_address.line1        | String \| TextField | The first line of the address                                                                              |
| billing\_address.line2        | String \| TextField | The second line of the address                                                                             |
| billing\_address.line3        | String \| TextField | The third line of the address                                                                              |
| billing\_address.postal\_code | String \| TextField | The postal code of the address                                                                             |
| billing\_address.city         | String \| TextField | The name of the city                                                                                       |
| billing\_address.country      | String \| TextField | The three letter country code following [ISO3166-Alpha3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) |

#### Token lifecycle

Pass these fields in the same object as the additional data to control how long the resulting token is retained. This supports a "Save my card" consent UX: keep the default until the cardholder consents, then set `ephemeral: false` (or an `expiration_date`) on consent.

| Attribute        | Type    | Description                                                                                                                                                           |
| ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ephemeral        | Boolean | Defaults to `true`. When `true`, the token is single-use and Guardian cleans it up after a short TTL. Set to `false` to persist the token (the cardholder consented). |
| expiration\_date | String  | An ISO-8601 timestamp setting an explicit expiration for the token. When supplied, Guardian uses it as the token's expiration and `ephemeral` is ignored.             |

```javascript theme={null}
const result = await cardHandler.process({
  cardholder_name: cardholderTextField,
  // cardholder ticked "Save my card", so the token must persist
  ephemeral: false,
});
```

#### Result

Session result [data](#session-result)

#### Result status

Session result [status](#session-result-status)

# Elements API

The Elements API allows to interact with the created card form or the card fields.

## Mount Element

This operation mounts an element to the DOM at the specified element.

```javascript theme={null}
await cardForm.mount('#my-card-form-id');
```

### Parameters

| Parameter | Type   | Required? | Description                                                                                  |
| --------- | ------ | --------- | -------------------------------------------------------------------------------------------- |
| selector  | String | Yes       | A CSS-selector that identifies the container in the DOM to where the element will be mounted |

## Update Element

This operations allows to change the options on an element. Please note that not all options can be changed.

```javascript theme={null}
cardNumberField.update({ icon: 'none' });
```

### Parameters

| Parameter | Type   | Required? | Description                                               |
| --------- | ------ | --------- | --------------------------------------------------------- |
| options   | Object | No        | The [options](#element-options) to customise the element. |

## Unmount Element

This operation removes an element from the DOM.

```javascript theme={null}
cardNumberField.unmount();
```

## Element Values / States

### Focus

Set the focus on an element's input.

```javascript theme={null}
cardNumberField.focus();
```

### Clear

Clear the value of an element.

```javascript theme={null}
cardNumberField.clear();
```

### Blur

Blur an element's input.

```javascript theme={null}
cardNumberField.blur();
```

## Element Options

| Attribute    | Element                                                    | Type      | Description                                                                                                                                                                                                                                                                                  |
| ------------ | ---------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| style        | All                                                        | Object    | [Data](#element-styles) that defines the styling of the element.                                                                                                                                                                                                                             |
| height       | All                                                        | String    | [CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/height) to customise the height of the element                                                                                                                                                                               |
| disabled     | All                                                        | Boolean   | Set the disabled state of the form field(s).                                                                                                                                                                                                                                                 |
| autocomplete | All                                                        | String    | String used to set the [autocomplete attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) of the input(s). Expected values are: off (default), or on.                                                                                                       |
| placeholder  | text, cardNumber, cardExpirationDate, cardVerificationCode | String    | String to customise the placeholder attribute of the form field.                                                                                                                                                                                                                             |
| ariaLabel    | text, cardNumber, cardExpirationDate, cardVerificationCode | String    | String to customise the aria-label attribute of the form field.                                                                                                                                                                                                                              |
| icon         | card, cardNumber                                           | String    | String to determine the position of the icon in the cardNumber field. `left` is the default value. It can be overwritten to `right` and to `none` in order to hide the icon entirely.                                                                                                        |
| schemes      | card, cardNumber                                           | String\[] | Whitelist of card schemes which are supported by the merchant. Available schemes: `visa`, `mastercard`, `american-express`, `discover`, `diners-club`, `jcb` `unionpay`. The input of a restricted scheme will lead to a validation error in the form. All schemes are supported by default. |

## Element Styles

The form fields are encapsulated into iframes to allow for maximum protection of sensitive data. This means that CSS from the embedding page cannot be propagated directly into the form or the fields.

```javascript theme={null}
cardNumberField.update({
  style: {
    fonts: ['https://fonts.googleapis.com/css2?family=Playfair:wght@300&display=swap'],
    base: {
      color: '#fff',
      fontWeight: 500,
      fontFamily: '"Playfair"',
      fontSize: '16px',
      '::placeholder': {
        color: '#6b7294',
      },
      ':disabled': {
        backgroundColor: '#ffff3b',
      },
    },
    invalid: {
      color: '#ffa474',
    },
  },
});
```

| Attribute | Required? | Description                                                               |
| --------- | --------- | ------------------------------------------------------------------------- |
| fonts     | No        | List of URLs to fonts on the Google API.                                  |
| base      | No        | Basic styling of the element. The other variants will use it as baseline. |
| complete  | No        | Variant of the baseline for an element with completed input.              |
| empty     | No        | Variant of the baseline for an element with empty input.                  |
| invalid   | No        | Variant of the baseline for an element with invalid input.                |

You can customise the elements using these pseudo-classes and pseudo-elements inside each variant using a nested object:

* `:hover`
* `:focus`
* `:disabled`
* `::placeholder`
* `::selection`

These CSS properties are supported in terms of styling:

* backgroundColor
* color
* fontFamily
* fontSize
* fontSmooth (will be mapped to user-agent naming automatically)
* fontStyle
* fontVariant
* fontWeight
* lineHeight
* letterSpacing
* textAlign
* padding
* textDecoration
* textShadow
* textTransform

# Events

Both the clients and the elements send out events so that solutions can actively react to changes in state.

## Card Handler Events

### FormStateChange

This event notifies every time the card form fields state changes.

```javascript theme={null}
cardHandler.onStateChange((state) => {
  // handling logic
});
```

The handler receives an aggregated `state` object that is derived from all card fields states.

```json theme={null}
{
  "valid": false,
  "complete": false,
  "empty": true,
  "error": "cardNumber is not complete"
}
```

| Attribute | Type    | Description                                                                                      |
| --------- | ------- | ------------------------------------------------------------------------------------------------ |
| valid     | Boolean | Indicates that all fields content successfully passed validation.                                |
| complete  | Boolean | Indicates that all fields are valid and maskSatisfied properties are true                        |
| empty     | Boolean | Form will be empty only if all inputs are                                                        |
| error     | String  | Human readable error message with an explanation why `valid: false`                              |
| errorCode | String  | Values are `NOT_COMPLETE`, `SCHEME_NOT_SUPPORTED`, `LUHN_CHECK_FAILED` and `INVALID_EXPIRY_DATE` |

## 3D-Secure Events

In standard cases 3D Secure handling works out of the box with the SDK and usually doesn't require any extra code. However, there are some events that can be used to handle the 3DS Challenge experience in the UI.

In order to use the 3DS Handler, it has to be obtained from the client:

```javascript theme={null}
const threeDSHandler = await client.use('3DS');
```

### Decoupled Authentication

Decoupled authentication can be supported by the SDK with a specific event.

```javascript theme={null}
threeDSHandler.onDecoupledAuth((cardholderInfo) => {
  // handle decoupled flow here and display cardholderInfo on the UI
  // to inform the customer how they should complete 3DS authentication
});
```

| Parameter      | Type   | Description                                                                                                                           |
| -------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| cardholderInfo | String | Instructions from the card issuer what method the customer should use to complete 3DS authentication. For example, mobile banking app |

### Start Challenge

This event is called once the 3DS Challenge is started. It can be used to show a loading indicator or to inform the customer about the ongoing process.

```javascript theme={null}
threeDSHandler.onStartChallenge(() => {
  // called once 3DS Challenge is started
});
```

### Challenge Finished

This event is called once the 3DS Challenge is finished. It can be used to hide the loading indicator or to inform the customer about the result.

```javascript theme={null}
threeDSHandler.onChallengeFinished(() => {
  // called when 3DS Handler finishes the task
});
```

## Element Events

### Change

This event notifies that the value of an element has changed. By default this event is emitted `onBlur` which can be overwritten with the element options.

```
cardNumberField.on('change', (changeEvent) => {  // handling logic});
```

The handler receives a ChangeEvent with information about the state of the element.

```
{  "complete": true,  "valid": false,  "empty": false,  "error": "Card Number Luhn check failed",  "cardBrand": "amex"}
```

| Attribute | Element    | Type    | Description                                                               |
| --------- | ---------- | ------- | ------------------------------------------------------------------------- |
| valid     | All        | Boolean | Indicates that the content successfully passed validation.                |
| empty     | All        | Boolean | Indicates that the element is empty.                                      |
| error     | All        | String  | Human readable error message with an explanation why `valid: false`       |
| cardBrand | CardNumber | String  | Values are `amex`, `visa`, `mastercard`, `diners`, `jcb`, and `unionpay`. |

### Focus

This event indicates that an element is focussed.

```javascript theme={null}
cardNumberField.on('focus', () => {
  // handling logic
});
```

### Blur

This event indicates that an element lost focussed.

```javascript theme={null}
cardNumberField.on('blur', () => {
  // handling logic
});
```

### Key Down

This event indicates that a key was pressed on the element.

```javascript theme={null}
cardNumberField.on('keydown', (keyDownEvent) => {
  // handling logic
});
```

The handler receives a KeyDownEvent with information about the state of the element.

```json theme={null}
{
  "key": "enter",
  "ctrlKey": false,
  "altKey": false,
  "shiftKey": false,
  "metaKey": false
}
```

| Attribute | Type    | Description                                                                            |
| --------- | ------- | -------------------------------------------------------------------------------------- |
| key       | String  | Indicator of the key that was pressed. Can be `Enter` or `Escape`.                     |
| ctrlKey   | Boolean | Indicates if the control key was pressed when the event occurred.                      |
| altKey    | Boolean | Indicates if the alt / option key was pressed when the event occurred.                 |
| shiftKey  | Boolean | Indicates if the shift key was pressed when the event occurred.                        |
| metaKey   | Boolean | Indicates if the meta (e.g. command on a Mac) key was pressed when the event occurred. |
