# Client-sdk

It is a solution for collecting and handling payment sources in secure way.

With SDK you can create a payment form widget as an independent part or insert use inside your form.

The SDK supports methods for customization of widget by your needs (styling, form fields, etc)

## Other information 

To work with the widget you will need public_key or access_token ([see Authentication](https://docs.paydock.com/#authentication))

Also you will need added gateway ([see API Reference by gateway](https://docs.paydock.com/#gateways))



## Get started

The Client SDK ships in JavaScript ES6 (EcmaScript 2015) in three different
formats (CJS, ESM and UMD) along with respective TypeScript declarations. Below,
we exemplify how to import each format.

### With package manager

Our NPM package is compatible with all package managers (e.g., `npm`, `yarn`,
`pnpm`, `bun`). Using `npm` the following command would add the Client SDK as a
production dependency.

```bash
npm install @paydock/client-sdk
```

After installation is complete, if you are developing in NodeJS environments or
using tools that expect your JavaScript code to be in CJS format (e.g., Jest,
Karma, RequireJS, Webpack), you can import the Client SDK using CommonJS modules.
For these environments the UMD format (`@paydock/client-sdk/bundles/widget.umd.js`)
can also be used as a fallback. Alternatively, in case you are developing in
projects that have access to modern bundlers such as Vite or others (e.g., SPA
libs or SSR Metaframeworks), you can import the Client SDK features using ESM
through named imports or namespaced imports.


```cjs
// module import - CommonJS/Node projects ✅
const paydock = require('@paydock/client-sdk')
const api = new paydock.Api('publicKey');
```

```mjs
// named import - ESM projects or TypeScript projects ✅
import { HtmlWidget } from '@paydock/client-sdk'
const widget = new HtmlWidget('#selector', 'publicKey', 'gatewayId');
```

```mjs
// namespaced import - ESM projects or TypeScript projects ✅
import * as Paydock from '@paydock/client-sdk'
const widget = new Paydock.HtmlWidget('#selector', 'publicKey', 'gatewayId');
```

```js
// default import - Not officially supported . They are handled differently by different tools / settings!
 ❌
import paydock from '@paydock/client-sdk'
>>> "Uncaught SyntaxError: The requested module does not provide an export named 'default'"
```


### Download from CDN

For browser environments, you can import the Client SDK directly from our CDN to
your project's HTML. To accomplish this, include the Client SDK in your page
using one and only of the two script tags below. After this step you will be
able to access the Client SDK features via the global variable `paydock`.

For production we recommend using the compressed version (`.min.js`) since
it will result in faster loading times for your end users.

- *Compressed version for production: `https://widget.paydock.com/sdk/latest/widget.umd.min.js`*

- *Full version for development and debug: `https://widget.paydock.com/sdk/latest/widget.umd.js`*

You may download the production version of the Client SDK scripts [here][min],
and, the development version [here][max].

[min]: https://widget.paydock.com/sdk/latest/widget.umd.min.js
[max]: https://widget.paydock.com/sdk/latest/widget.umd.js

For more advanced use-cases, the library has [UMD](https://github.com/umdjs/umd)
format that can be used in RequireJS, Webpack, etc.


```html
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script>
<script>
    var widget = new paydock.HtmlWidget('#tag', 'publicKey', 'gatewayId');
</script>
```


## Widget

You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#widget-simple-example)

A payment form where it is possible to enter card data/bank accounts and then receive a one-time
token for charges, subscriptions etc. This form can be customized, you can customize the fields and set styles.
It is possible in real-time to monitor the actions of user with widget and get information about payment-source using events.

## Widget simple example

### Container

```html
<div id="widget"></div>
```

You must create a container for the widget. Inside this tag, the widget will be initialized

### Initialization

```javascript
var widget = new paydock.HtmlWidget('#widget', 'publicKey');
widget.load();
```

```javascript
// ES2015 | TypeScript

import { HtmlWidget } from '@paydock/client-sdk';

var widget = new HtmlWidget('#widget', 'publicKey');
widget.load();
```

Then write only need 2 lines of code in js to initialize widget

### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 100%;height: 300px;}</style>
</head>
<body>
    <form id="paymentForm">
        <div id="widget"></div>
        <input name="payment_source_token" id="payment_source_token" type="hidden">
    </form>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
    <script>
        var widget = new paydock.HtmlWidget('#widget', 'publicKey');
        widget.onFinishInsert('input[name="payment_source_token"]', 'payment_source');
        widget.load();
    </script>
</body>
</html>
```

## Widget advanced example

### Customization

```javascript
widget.setStyles({
  background_color: 'rgb(0, 0, 0)',
  border_color: 'yellow',
  text_color: '#FFFFAA',
  button_color: 'rgba(255, 255, 255, 0.9)',
  font_size: '20px'
 });
```

This example shows how you can customize to your needs and design

### Customization from html

```html
<div id="widget"
  widget-style="text-color: #FFFFAA; border-color: #yellow"
  title="Payment form"
  finish-text="Payment resource was successfully accepted"></div>
```

This example shows how you can set style and texts from html

### Settings

```javascript
widget.setRefId('id'); // your unique identifier to identify the data

widget.setFormFields(['phone', 'email']); // add additional fields for form of widget

widget.setSupportedCardIcons(['mastercard', 'visa']); // add icons of supported card types
```

This example shows how you can use a lot of other methods to settings your form

### Error handling

## Overview

Error events are emitted when an error occurs during widget operations. These events provide detailed information about the error, including its category, cause, and contextual details.

## Error Event Structure

### Base Properties

| Property | Type | Description |
|----------|------|-------------|
| `event` | `string` | Always set to `"error"` |
| `purpose` | `string` | Indicates the purpose of the action that triggered the error event (e.g., `"payment_source"`) |
| `message_source` | `string` | Source of the message (e.g., `"widget.paydock"`) |
| `ref_id` | `string` | Reference ID for the operation |
| `widget_id` | `string` | Unique identifier of the widget instance |
| `error` | `object` | Error object containing error information |

### Error Object Properties

The `error` object contains detailed information about the error:

| Property | Type | Description |
|----------|------|-------------|
| `category` | `string` | High-level error classification |
| `cause` | `string` | Specific error cause |
| `retryable` | `boolean` | Indicates if the operation can be retried |
| `details` | `object` | Additional error context |

## Error Categories

| Category | Description |
|----------|-------------|
| `configuration` | Configuration-related errors |
| `identity_access_management` | Authentication and authorization errors |
| `internal` | Internal system errors |
| `process` | Process and operation errors |
| `resource` | Resource-related errors |
| `validation` | Input validation errors |

## Error Causes

| Cause | Category | Description |
|-------|----------|-------------|
| `aborted` | `process` | Operation was aborted |
| `access_forbidden` | `identity` | Access to resource is forbidden |
| `already_exists` | `validation` | Resource already exists |
| `canceled` | `process` | Operation was canceled |
| `invalid_configuration` | `configuration` | Invalid widget configuration |
| `invalid_input` | `validation` | Invalid input provided |
| `not_found` | `resource` | Requested resource not found |
| `not_implemented` | `process` | Requested feature not implemented |
| `rate_limited` | `process` | Too many requests |
| `server_busy` | `process` | Server is too busy to handle request |
| `service_unreachable` | `process` | Unable to reach required service |
| `unauthorized` | `identity` | Authentication required |
| `unknown_error` | `internal` | Unexpected error occurred |
| `unprocessable_entity` | `validation` | Valid input but cannot be processed |

## Error Details Object

| Property | Type | Description |
|----------|------|-------------|
| `cause` | `string` | Matches the top-level error cause |
| `contextId` | `string` | Context identifier (usually matches widget_id) |
| `message` | `string` | Human-readable error message |
| `timestamp` | `string` | ISO 8601 timestamp of when the error occurred |

## Example

```javascript
widget.hideUiErrors(); // hide default UI errors and handle errors by listening to error events with widget.on('error')

widget.on('error', (error) => {
    console.log(error);
    // {
    //     "event": "error",
    //     "purpose": "payment_source",
    //     "message_source": "widget.paydock",
    //     "ref_id": "",
    //     "widget_id": "d4744f30-dcf5-168e-7f78-c8273a3401d4",
    //     "error": {
    //         "category": "process",
    //         "cause": "service_unreachable",
    //         "details": {
    //             "cause": "service_unreachable",
    //             "contextId": "d4744f30-dcf5-168e-7f78-c8273a3401d4",
    //             "message": "The service is not availabe",
    //             "timestamp": "2025-02-13T09:30:21.157Z"
    //         },
    //         "retryable": false
    //     }
    // }
});
```

## Handling Errors (Tips)

When handling errors, consider:

1. Check the `retryable` flag to determine if the operation can be retried
2. Use the `category` for high-level error handling logic
3. Use the `cause` for specific error handling cases
4. The `contextId` can be used for error tracking and debugging
5. The `timestamp` helps with error logging and debugging

### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>iframe {border: 0;width: 100%;height: 400px;}</style>
</head>
<body>
<form id="paymentForm">
    <div id="widget"
        widget-style="text-color: #FFFFAA; border-color: #yellow"
        title="Payment form"
        finish-text="Payment resource was successfully accepted">
    </div>

    <div 
        id="error" 
        style="
            display: none;
            max-width: 600px;
            margin: 16px auto;
            padding: 16px 20px;
            border-radius: 8px;
            background-color: #FEF2F2;
            border: 1px solid #FEE2E2;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            font-family: system-ui, -apple-system, sans-serif;
            color: #991B1B;
            line-height: 1.5;
            font-size: 14px;
        "
        title="error"
        >
        <div style="display: flex; align-items: flex-start; gap: 12px;">
            <div>
                <h4 style="margin: 0 0 4px 0; font-size: 14px; font-weight: 600;">Access Error</h4>
                <div id="error-message"></div>
            </div>
        </div>
    </div> 
</form>

<script src="https://widget.paydock.com/sdk/latest/widget.umd.js" ></script>
<script>
 var widget = new paydock.HtmlWidget('#widget', 'publicKey', 'gatewayId');

 widget.setSupportedCardIcons(['mastercard', 'visa']);
 widget.setFormFields(['phone', 'email']);
 widget.setRefId('custom-ref-id');
    widget.onFinishInsert('input[name="payment_source_token"]', 'payment_source');

    widget.on('error', ({ error }) => {
        document.getElementById('error-message').textContent = error.details.message;
        document.getElementById('error').style.display = 'block';
    });
 widget.load();
</script>

</body>
</html>
```

## Constants

<dl>
<dt><a href="#user-content-w_FORM_FIELD">FORM_FIELD</a> : <code>object</code></dt>
<dd><p>Current constant include available type of fields which can be included to widget</p>
</dd>
<dt><a href="#user-content-w_STYLE">STYLE</a> : <code>object</code></dt>
<dd><p>List of available style params for widget</p>
</dd>
<dt><a href="#user-content-w_TEXT">TEXT</a> : <code>object</code></dt>
<dd><p>List of available text item params for widget</p>
</dd>
<dt><a href="#user-content-w_ELEMENT">ELEMENT</a> : <code>object</code></dt>
<dd><p>List of available params for hide elements</p>
</dd>
<dt><a href="#user-content-w_SUPPORTED_CARD_TYPES">SUPPORTED_CARD_TYPES</a> : <code>object</code></dt>
<dd><p>The list of available parameters for showing card icons</p>
</dd>
<dt><a href="#user-content-w_STYLABLE_ELEMENT">STYLABLE_ELEMENT</a> : <code>object</code></dt>
<dd><p>Current constant include available type of element for styling</p>
</dd>
<dt><a href="#user-content-w_STYLABLE_ELEMENT_STATE">STYLABLE_ELEMENT_STATE</a> : <code>object</code></dt>
<dd><p>Current constant include available states of element for styling</p>
</dd>
<dt><a href="#user-content-w_CARD_VALIDATORS">CARD_VALIDATORS</a> : <code>Record.&lt;string, string&gt;</code></dt>
<dd><p>List of available form field validators dedicated to cards and their definition</p>
</dd>
<dt><a href="#user-content-w_GENERIC_VALIDATORS">GENERIC_VALIDATORS</a> : <code>Record.&lt;string, string&gt;</code></dt>
<dd><p>List of available generic form field validators and their definition</p>
</dd>
<dt><a href="#user-content-w_TRIGGER">TRIGGER</a> : <code>object</code></dt>
<dd><p>List of available triggers</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#user-content-w_IPayPalMeta">IPayPalMeta</a></dt>
<dd><p>Interface for PayPal checkout meta information</p>
</dd>
<dt><a href="#user-content-w_IStyles">IStyles</a></dt>
<dd><p>Interface for classes that represent widget&#39;s styles.</p>
</dd>
<dt><a href="#user-content-w_ITexts">ITexts</a></dt>
<dd><p>Interface for classes that represent widget&#39;s text.</p>
</dd>
<dt><a href="#user-content-w_IBamboraMeta">IBamboraMeta</a></dt>
<dd><p>Interface for Bamboora meta information</p>
</dd>
<dt><a href="#user-content-w_IElementStyleInput">IElementStyleInput</a></dt>
<dd><p>Interface for styling input element.</p>
</dd>
<dt><a href="#user-content-w_IElementStyleSubmitButton">IElementStyleSubmitButton</a></dt>
<dd><p>Interface for styling submit_button element.</p>
</dd>
<dt><a href="#user-content-w_IElementStyleLabel">IElementStyleLabel</a></dt>
<dd><p>Interface for styling label element.</p>
</dd>
<dt><a href="#user-content-w_IElementStyleTitle">IElementStyleTitle</a></dt>
<dd><p>Interface for styling title element.</p>
</dd>
<dt><a href="#user-content-w_IElementStyleTitleDescription">IElementStyleTitleDescription</a></dt>
<dd><p>Interface for styling title_description element.</p>
</dd>
<dt><a href="#user-content-w_ITriggerData">ITriggerData</a></dt>
<dd><p>Interface for classes that represent a trigger data.</p>
</dd>
</dl>

<a name="w_IPayPalMeta" id="w_IPayPalMeta" href="#user-content-w_IPayPalMeta">&nbsp;</a>

## IPayPalMeta
Interface for PayPal checkout meta information

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [brand_name] | <code>string</code> | A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages |
| [cart_border_color] | <code>string</code> | The HTML hex code for your principal identifying color |
| [reference] | <code>string</code> | Merchant Customer Service number displayed on the PayPal pages |
| [email] | <code>string</code> | The consumer’s email |
| [hdr_img] | <code>string</code> | URL for the image you want to appear at the top left of the payment page |
| [logo_img] | <code>string</code> | A URL to your logo image |
| [pay_flow_color] | <code>string</code> | Sets the background color for the payment page. By default, the color is white. |
| [first_name] | <code>string</code> | The consumer’s given names |
| [last_name] | <code>string</code> | The consumer’s surname |
| [address_line] | <code>string</code> | Street address |
| [address_line2] | <code>string</code> | Second line of the address |
| [address_city] | <code>string</code> | City |
| [address_state] | <code>string</code> | State |
| [address_postcode] | <code>string</code> | Postcode |
| [address_country] | <code>string</code> | Country |
| [phone] | <code>string</code> | The consumer’s phone number in E.164 international notation (Example: +12345678901) |
| [hide_shipping_address] | <code>boolean</code> | Determines whether PayPal displays shipping address fields on the PayPal pages |

<a name="w_IStyles" id="w_IStyles" href="#user-content-w_IStyles">&nbsp;</a>

## IStyles
Interface for classes that represent widget's styles.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| [background_color] | <code>string</code> | 
| [text_color] | <code>string</code> | 
| [border_color] | <code>string</code> | 
| [button_color] | <code>string</code> | 
| [error_color] | <code>string</code> | 
| [success_color] | <code>string</code> | 
| [font_size] | <code>string</code> | 
| [font_family] | <code>string</code> | 

<a name="w_ITexts" id="w_ITexts" href="#user-content-w_ITexts">&nbsp;</a>

## ITexts
Interface for classes that represent widget's text.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| [title] | <code>string</code> | 
| [title_h1] | <code>string</code> | 
| [title_h2] | <code>string</code> | 
| [title_h3] | <code>string</code> | 
| [title_h4] | <code>string</code> | 
| [title_h5] | <code>string</code> | 
| [title_h6] | <code>string</code> | 
| [finish_text] | <code>string</code> | 
| [title_description] | <code>string</code> | 
| [submit_button] | <code>string</code> | 
| [submit_button_processing] | <code>string</code> | 

<a name="w_IBamboraMeta" id="w_IBamboraMeta" href="#user-content-w_IBamboraMeta">&nbsp;</a>

## IBamboraMeta
Interface for Bamboora meta information

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [customer_storage_number] | <code>string</code> | Customer storage number |
| [tokenise_algorithm] | <code>number</code> | Tokenise algorithm |

<a name="w_IElementStyleInput" id="w_IElementStyleInput" href="#user-content-w_IElementStyleInput">&nbsp;</a>

## IElementStyleInput
Interface for styling input element.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) |
| [border] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/border) |
| [border_radius] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) |
| [background_color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) |
| [height] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/height) |
| [text_decoration] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) |
| [font_size] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) |
| [font_family] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) |
| [transition] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) |
| [line_height] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) |
| [font_weight] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) |
| [padding] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) |
| [margin] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) |

<a name="w_IElementStyleSubmitButton" id="w_IElementStyleSubmitButton" href="#user-content-w_IElementStyleSubmitButton">&nbsp;</a>

## IElementStyleSubmitButton
Interface for styling submit_button element.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) |
| [border] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/border) |
| [border_radius] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) |
| [background_color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) |
| [text_decoration] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) |
| [font_size] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) |
| [font_family] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) |
| [padding] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) |
| [margin] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) |
| [transition] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) |
| [line_height] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) |
| [font_weight] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) |
| [opacity] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) |

<a name="w_IElementStyleLabel" id="w_IElementStyleLabel" href="#user-content-w_IElementStyleLabel">&nbsp;</a>

## IElementStyleLabel
Interface for styling label element.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) |
| [text_decoration] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) |
| [font_size] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) |
| [font_family] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) |
| [line_height] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) |
| [font_weight] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) |
| [padding] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) |
| [margin] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) |

<a name="w_IElementStyleTitle" id="w_IElementStyleTitle" href="#user-content-w_IElementStyleTitle">&nbsp;</a>

## IElementStyleTitle
Interface for styling title element.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) |
| [text_decoration] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) |
| [font_size] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) |
| [font_family] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) |
| [line_height] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) |
| [font_weight] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) |
| [padding] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) |
| [margin] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) |
| ['text-align',] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) |

<a name="w_IElementStyleTitleDescription" id="w_IElementStyleTitleDescription" href="#user-content-w_IElementStyleTitleDescription">&nbsp;</a>

## IElementStyleTitleDescription
Interface for styling title_description element.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [color] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) |
| [text_decoration] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) |
| [font_size] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) |
| [font_family] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) |
| [line_height] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) |
| [font_weight] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) |
| [padding] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) |
| [margin] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) |
| ['text-align',] | <code>string</code> | Look more [mozilla.org/color](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) |

<a name="w_ITriggerData" id="w_ITriggerData" href="#user-content-w_ITriggerData">&nbsp;</a>

## ITriggerData
Interface for classes that represent a trigger data.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| [configuration_token] | <code>string</code> | 
| [tab_number] | <code>string</code> | 
| [elements] | <code>string</code> | 
| [form_values] | <code>string</code> | 

<a name="w_FORM_FIELD" id="w_FORM_FIELD" href="#user-content-w_FORM_FIELD">&nbsp;</a>

## FORM\_FIELD : <code>object</code>
Current constant include available type of fields which can be included to widget

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| CARD_NAME | <code>string</code> | <code>&quot;card_name&quot;</code> | 
| CARD_NUMBER | <code>string</code> | <code>&quot;card_number&quot;</code> | 
| EXPIRE_MONTH | <code>string</code> | <code>&quot;expire_month&quot;</code> | 
| EXPIRE_YEAR | <code>string</code> | <code>&quot;expire_year&quot;</code> | 
| CARD_CCV | <code>string</code> | <code>&quot;card_ccv&quot;</code> | 
| CARD_PIN | <code>string</code> | <code>&quot;card_pin&quot;</code> | 
| ACCOUNT_NAME | <code>string</code> | <code>&quot;account_name&quot;</code> | 
| ACCOUNT_BSB | <code>string</code> | <code>&quot;account_bsb&quot;</code> | 
| ACCOUNT_NUMBER | <code>string</code> | <code>&quot;account_number&quot;</code> | 
| ACCOUNT_ROUTING | <code>string</code> | <code>&quot;account_routing&quot;</code> | 
| ACCOUNT_HOLDER_TYPE | <code>string</code> | <code>&quot;account_holder_type&quot;</code> | 
| ACCOUNT_BANK_NAME | <code>string</code> | <code>&quot;account_bank_name&quot;</code> | 
| ACCOUNT_TYPE | <code>string</code> | <code>&quot;account_type&quot;</code> | 
| FIRST_NAME | <code>string</code> | <code>&quot;first_name&quot;</code> | 
| LAST_NAME | <code>string</code> | <code>&quot;last_name&quot;</code> | 
| EMAIL | <code>string</code> | <code>&quot;email&quot;</code> | 
| PHONE | <code>string</code> | <code>&quot;phone&quot;</code> | 
| PHONE2 | <code>string</code> | <code>&quot;phone2&quot;</code> | 
| ADDRESS_LINE1 | <code>string</code> | <code>&quot;address_line1&quot;</code> | 
| ADDRESS_LINE2 | <code>string</code> | <code>&quot;address_line2&quot;</code> | 
| ADDRESS_STATE | <code>string</code> | <code>&quot;address_state&quot;</code> | 
| ADDRESS_COUNTRY | <code>string</code> | <code>&quot;address_country&quot;</code> | 
| ADDRESS_CITY | <code>string</code> | <code>&quot;address_city&quot;</code> | 
| ADDRESS_POSTCODE | <code>string</code> | <code>&quot;address_postcode&quot;</code> | 
| ADDRESS_COMPANY | <code>string</code> | <code>&quot;address_company&quot;</code> | 

<a name="w_STYLE" id="w_STYLE" href="#user-content-w_STYLE">&nbsp;</a>

## STYLE : <code>object</code>
List of available style params for widget

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| BACKGROUND_COLOR | <code>string</code> | <code>&quot;background_color&quot;</code> | 
| TEXT_COLOR | <code>string</code> | <code>&quot;text_color&quot;</code> | 
| BORDER_COLOR | <code>string</code> | <code>&quot;border_color&quot;</code> | 
| BUTTON_COLOR | <code>string</code> | <code>&quot;button_color&quot;</code> | 
| ERROR_COLOR | <code>string</code> | <code>&quot;error_color&quot;</code> | 
| SUCCESS_COLOR | <code>string</code> | <code>&quot;success_color&quot;</code> | 
| FONT_SIZE | <code>string</code> | <code>&quot;font_size&quot;</code> | 
| FONT_FAMILY | <code>string</code> | <code>&quot;font_family&quot;</code> | 

<a name="w_TEXT" id="w_TEXT" href="#user-content-w_TEXT">&nbsp;</a>

## TEXT : <code>object</code>
List of available text item params for widget

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| TITLE | <code>string</code> | <code>&quot;title&quot;</code> | 
| FINISH | <code>string</code> | <code>&quot;finish_text&quot;</code> | 

<a name="w_ELEMENT" id="w_ELEMENT" href="#user-content-w_ELEMENT">&nbsp;</a>

## ELEMENT : <code>object</code>
List of available params for hide elements

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| SUBMIT_BUTTON | <code>string</code> | <code>&quot;submit_button&quot;</code> | 
| TABS | <code>string</code> | <code>&quot;tabs&quot;</code> | 

<a name="w_SUPPORTED_CARD_TYPES" id="w_SUPPORTED_CARD_TYPES" href="#user-content-w_SUPPORTED_CARD_TYPES">&nbsp;</a>

## SUPPORTED\_CARD\_TYPES : <code>object</code>
The list of available parameters for showing card icons

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| AMEX | <code>string</code> | <code>&quot;amex&quot;</code> | 
| AUSBC | <code>string</code> | <code>&quot;ausbc&quot;</code> | 
| DINERS | <code>string</code> | <code>&quot;diners&quot;</code> | 
| DISCOVER | <code>string</code> | <code>&quot;discover&quot;</code> | 
| JAPCB | <code>string</code> | <code>&quot;japcb&quot;</code> | 
| LASER | <code>string</code> | <code>&quot;laser&quot;</code> | 
| MASTERCARD | <code>string</code> | <code>&quot;mastercard&quot;</code> | 
| SOLO | <code>string</code> | <code>&quot;solo&quot;</code> | 
| VISA | <code>string</code> | <code>&quot;visa&quot;</code> | 
| VISA_WHITE | <code>string</code> | <code>&quot;visa_white&quot;</code> | 
| UNIONPAY | <code>string</code> | <code>&quot;unionpay&quot;</code> | 

<a name="w_STYLABLE_ELEMENT" id="w_STYLABLE_ELEMENT" href="#user-content-w_STYLABLE_ELEMENT">&nbsp;</a>

## STYLABLE\_ELEMENT : <code>object</code>
Current constant include available type of element for styling

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| INPUT | <code>string</code> | <code>&quot;input.&quot;</code> | These states are available: [STYLABLE_ELEMENT_STATE.ERROR](#user-content-w_STYLABLE_ELEMENT_STATE), [STYLABLE_ELEMENT_STATE.FOCUS](#user-content-w_STYLABLE_ELEMENT_STATE).   These styles are available [IElementStyleInput](#user-content-w_IElementStyleInput) |
| SUBMIT_BUTTON | <code>string</code> | <code>&quot;submit_button&quot;</code> | These states are available: [STYLABLE_ELEMENT_STATE.HOVER](#user-content-w_STYLABLE_ELEMENT_STATE).   These styles are available [IElementStyleSubmitButton](#user-content-w_IElementStyleSubmitButton) |
| LABEL | <code>string</code> | <code>&quot;label.&quot;</code> | These styles are available [IElementStyleLabel](#user-content-w_IElementStyleLabel) |
| TITLE | <code>string</code> | <code>&quot;title.&quot;</code> | These styles are available [IElementStyleTitle](#user-content-w_IElementStyleTitle) |
| TITLE_DESCRIPTION | <code>string</code> | <code>&quot;title_description.&quot;</code> | These styles are available [IElementStyleTitleDescription](#user-content-w_IElementStyleTitleDescription) |

<a name="w_STYLABLE_ELEMENT_STATE" id="w_STYLABLE_ELEMENT_STATE" href="#user-content-w_STYLABLE_ELEMENT_STATE">&nbsp;</a>

## STYLABLE\_ELEMENT\_STATE : <code>object</code>
Current constant include available states of element for styling

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| ERROR | <code>string</code> | <code>&quot;error&quot;</code> | client|server validation. This state applies to: input |
| FOCUS | <code>string</code> | <code>&quot;focus&quot;</code> | focus. This state applies to: input |
| HOVER | <code>string</code> | <code>&quot;hover&quot;</code> | focus. This state applies to: submit_button |

<a name="w_CARD_VALIDATORS" id="w_CARD_VALIDATORS" href="#user-content-w_CARD_VALIDATORS">&nbsp;</a>

## CARD\_VALIDATORS : <code>Record.&lt;string, string&gt;</code>
List of available form field validators dedicated to cards and their definition

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| CVV | <code>string</code> | <code>&quot;cardCvvValidation&quot;</code> | Asserts that CVV contains zero or more digits and is a number |
| EXPIRY_DATE | <code>string</code> | <code>&quot;expireDateValidation&quot;</code> | Asserts value is a date in the future with format MM/YY |
| HOLDER_NAME | <code>string</code> | <code>&quot;cardHoldernameValidation&quot;</code> | Asserts value is a name that respects the ITU-T T.50 standard (@see https://www.itu.int/rec/T-REC-T.50/en) |
| NUMBER | <code>string</code> | <code>&quot;cardNumberValidation&quot;</code> | Asserts the value matches a known card scheme and as a the correct length.     E.g., matches a 13, 16 or 19 digit bank card, **or**, a 13 to 25 digit Vii Gift card |
| PIN | <code>string</code> | <code>&quot;cardPinValidation&quot;</code> | Asserts the value is a number with exactly 4 digits |

<a name="w_GENERIC_VALIDATORS" id="w_GENERIC_VALIDATORS" href="#user-content-w_GENERIC_VALIDATORS">&nbsp;</a>

## GENERIC\_VALIDATORS : <code>Record.&lt;string, string&gt;</code>
List of available generic form field validators and their definition

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| REQUIRED | <code>string</code> | <code>&quot;required&quot;</code> | Asserts the input or form field has a value defined truthy value |

<a name="w_TRIGGER" id="w_TRIGGER" href="#user-content-w_TRIGGER">&nbsp;</a>

## TRIGGER : <code>object</code>
List of available triggers

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| SUBMIT_FORM | <code>string</code> | <code>&quot;submit_form&quot;</code> | 
| CHANGE_TAB | <code>string</code> | <code>&quot;tab&quot;</code> | 
| HIDE_ELEMENTS | <code>string</code> | <code>&quot;hide_elements&quot;</code> | 
| SHOW_ELEMENTS | <code>string</code> | <code>&quot;show_elements&quot;</code> | 
| REFRESH_CHECKOUT | <code>string</code> | <code>&quot;refresh_checkout&quot;</code> | 
| UPDATE_FORM_VALUES | <code>string</code> | <code>&quot;update_form_values&quot;</code> | 
| INIT_CHECKOUT | <code>string</code> | <code>&quot;init_checkout&quot;</code> | 
| INJECT_CUSTOMER_DATA | <code>string</code> | <code>&quot;inject_customer_data&quot;</code> | 


## Payment sources widget
You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#payment-sources-simple-example)

This widget provides a list of previously added (saved) payment-sources by customer_id or reference.
The widget provides an opportunity to use events to track the process of selecting payment-sources and provide meta information about the payment-sources.

Payment-source requires a query_token that represents a pre-generated and secure token for limiting the list
payment-sources, for a specific user or reference.

In order to generate this token, you need to send a GET request to [getCustomerList](#get-customer-list-with-parameters)
where required query parameter must be id or reference. In response you get response.query_token which you can use in the widget.

## Payment sources simple example

### Container

```html
<div id="list"></div>
```

You must create a container for the widget. Inside this tag, the widget will be initialized


### Initialization
```javascript
var list = new paydock.HtmlPaymentSourceWidget('#list', 'publicKey', 'queryToken');
list.load();
```

```javascript
// ES2015 | TypeScript

import { HtmlPaymentSourceWidget } from '@paydock/client-sdk';

var list = new HtmlPaymentSourceWidget('#list', 'publicKey', 'queryToken');
list.load();
```

Then write only need 2 lines of code in js to initialize widget


### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 300px;}</style>
</head>
<body>
    <div id="list"></div>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
    <script>
        var list = new paydock.HtmlPaymentSourceWidget('#list', 'publicKey', 'queryToken');
        list.load();
    </script>
</body>
</html>
```


## Payment sources advanced example

### Customization

```javascript
list.setStyles({
    icon_size: 'small'
});
```

This example shows how you can customize to your needs and design

### Settings

```javascript

list.filterByTypes(['card', 'checkout']); // filter by any payment source types
list.filterByGatewayIds(['gateway1']); // also other filters

list.setRefId('id'); // your unique identifier to identify the data

list.setLimit(4); // Pagination elements will show if count of elements more then argument passed

list.onSelectInsert('input[name="ps_id"]', 'payment_source_id'); // insert one-time-token to your input after finish checkout

list.on('select', function(data) {
    console.log(data);
});
```

This example shows how you can use a lot of other methods to settings your form

### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 300px;}</style>
</head>
<body>
    <div id="list"></div>
    <input type="text" name="ps_id" />
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
    <script>
        var list = new paydock.HtmlPaymentSourceWidget('#list', 'publicKey', 'queryToken');
        list.filterByTypes(['card', 'checkout']);
        list.filterByGatewayIds(['gateway1']);
        list.setRefId('id');
        list.setLimit(4);
        list.setStyles({
            icon_size: 'small'
        });

        list.load();

        list.onSelectInsert('input[name="ps_id"]', 'payment_source_id');
        list.on('select', function(data) {
            console.log(data);
        });
    </script>
</body>
</html>
```

## Classes

<dl>
<dt><a href="#user-content-psw_HtmlPaymentSourceWidget">HtmlPaymentSourceWidget</a> ⇐ <code><a href="#user-content-psw_PaymentSourceWidget">PaymentSourceWidget</a></code></dt>
<dd><p>Class HtmlPaymentSourceWidget include method for working on html</p>
</dd>
<dt><a href="#user-content-psw_PaymentSourceWidget">PaymentSourceWidget</a></dt>
<dd><p>Class PaymentSourceWidget include method for for creating iframe url</p>
</dd>
</dl>

## Constants

<dl>
<dt><a href="#user-content-psw_EVENT">EVENT</a> : <code>object</code></dt>
<dd><p>List of available event&#39;s name</p>
</dd>
<dt><a href="#user-content-psw_STYLE">STYLE</a> : <code>object</code></dt>
<dd><p>List of available style params for widget</p>
</dd>
<dt><a href="#user-content-psw_PAYMENT_SOURCE_TYPE">PAYMENT_SOURCE_TYPE</a> : <code>object</code></dt>
<dd><p>List of available payment source types</p>
</dd>
</dl>

## Typedefs

<dl>
<dt><a href="#user-content-psw_listener--PaymentSourceWidget">listener--PaymentSourceWidget</a> : <code>function</code></dt>
<dd><p>This callback will be called for each event in payment source widget</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#user-content-psw_IEventSelectData">IEventSelectData</a></dt>
<dd><p>Interface of data from event.</p>
</dd>
<dt><a href="#user-content-psw_IEventPaginationData">IEventPaginationData</a></dt>
<dd><p>Interface of data from event.</p>
</dd>
<dt><a href="#user-content-psw_IEventAfterLoadData">IEventAfterLoadData</a></dt>
<dd><p>Interface of data from event.</p>
</dd>
<dt><a href="#user-content-psw_IEventFinishData">IEventFinishData</a></dt>
<dd><p>Interface of data from event.</p>
</dd>
<dt><a href="#user-content-psw_IEventSizeData">IEventSizeData</a></dt>
<dd><p>Interface of data from event.</p>
</dd>
<dt><a href="#user-content-psw_IStyles">IStyles</a></dt>
<dd><p>Interface for classes that represent widget&#39;s styles.</p>
</dd>
</dl>

<a name="psw_IEventSelectData" id="psw_IEventSelectData" href="#user-content-psw_IEventSelectData">&nbsp;</a>

## IEventSelectData
Interface of data from event.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| event | <code>string</code> | 
| purpose | <code>string</code> | 
| message_source | <code>string</code> | 
| [ref_id] | <code>string</code> | 
| customer_id | <code>string</code> | 
| payment_source_id | <code>string</code> | 
| gateway_id | <code>string</code> | 
| primary | <code>boolean</code> | 
| [widget_id] | <code>string</code> | 
| [card_number_last4] | <code>string</code> | 
| [card_scheme] | <code>string</code> | 
| gateway_type | <code>string</code> | 
| [checkout_email] | <code>string</code> | 
| payment_source_type | <code>string</code> | 
| [account_name] | <code>string</code> | 
| [account_number] | <code>string</code> | 

<a name="psw_IEventPaginationData" id="psw_IEventPaginationData" href="#user-content-psw_IEventPaginationData">&nbsp;</a>

## IEventPaginationData
Interface of data from event.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| event | <code>string</code> | 
| purpose | <code>string</code> | 
| message_source | <code>string</code> | 
| [ref_id] | <code>string</code> | 
| total_item | <code>number</code> | 
| skip | <code>number</code> | 
| limit | <code>number</code> | 

<a name="psw_IEventAfterLoadData" id="psw_IEventAfterLoadData" href="#user-content-psw_IEventAfterLoadData">&nbsp;</a>

## IEventAfterLoadData
Interface of data from event.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | The name of the event. |
| purpose | <code>string</code> | A system variable that states the purpose of the event. |
| message_source | <code>string</code> | A system variable that identifies the event source. |
| [ref_id] | <code>string</code> | Custom unique value that identifies result of processed operation. |
| total_item | <code>number</code> | Pagination param. Total item count |
| skip | <code>number</code> | Pagination param. Skip items from first item |
| limit | <code>number</code> | Pagination param. Query limit |

<a name="psw_IEventFinishData" id="psw_IEventFinishData" href="#user-content-psw_IEventFinishData">&nbsp;</a>

## IEventFinishData
Interface of data from event.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | The name of the event. |
| purpose | <code>string</code> | A system variable that states the purpose of the event. |
| message_source | <code>string</code> | A system variable that identifies the event source. |
| [ref_id] | <code>string</code> | Custom unique value that identifies result of processed operation. |

<a name="psw_IEventSizeData" id="psw_IEventSizeData" href="#user-content-psw_IEventSizeData">&nbsp;</a>

## IEventSizeData
Interface of data from event.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>number</code> | The name of the event. |
| purpose | <code>number</code> | A system variable that states the purpose of the event. |
| message_source | <code>string</code> | A system variable that identifies the event source. |
| [ref_id] | <code>string</code> | Custom unique value that identifies result of processed operation. |
| height | <code>number</code> | Height of iFrame |
| width | <code>number</code> | Width of iFrame |

<a name="psw_IStyles" id="psw_IStyles" href="#user-content-psw_IStyles">&nbsp;</a>

## IStyles
Interface for classes that represent widget's styles.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| [background_color] | <code>string</code> | 
| [background_active_color] | <code>string</code> | 
| [text_color] | <code>string</code> | 
| [border_color] | <code>string</code> | 
| [font_size] | <code>string</code> | 
| [icon_size] | <code>string</code> | 

<a name="psw_HtmlPaymentSourceWidget" id="psw_HtmlPaymentSourceWidget" href="#user-content-psw_HtmlPaymentSourceWidget">&nbsp;</a>

## HtmlPaymentSourceWidget ⇐ [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)
Class HtmlPaymentSourceWidget include method for working on html

**Kind**: global class  
**Extends**: [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

* [HtmlPaymentSourceWidget](#user-content-psw_HtmlPaymentSourceWidget) ⇐ [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)
    * [new HtmlPaymentSourceWidget(selector, publicKey, queryToken)](#user-content-psw_new_HtmlPaymentSourceWidget_new)
    * [.load()](#user-content-psw_HtmlPaymentSourceWidget+load)
    * [.on(eventName, cb)](#user-content-psw_HtmlPaymentSourceWidget+on)
    * [.hide([saveSize])](#user-content-psw_HtmlPaymentSourceWidget+hide)
    * [.show()](#user-content-psw_HtmlPaymentSourceWidget+show)
    * [.reload()](#user-content-psw_HtmlPaymentSourceWidget+reload)
    * [.onSelectInsert(selector, dataType)](#user-content-psw_HtmlPaymentSourceWidget+onSelectInsert)
    * [.setStyles(fields)](#user-content-psw_PaymentSourceWidget+setStyles)
    * [.setRefId(refId)](#user-content-psw_PaymentSourceWidget+setRefId)
    * [.setLimit(count)](#user-content-psw_PaymentSourceWidget+setLimit)
    * [.setEnv(env, [alias])](#user-content-psw_PaymentSourceWidget+setEnv)
    * [.getIFrameUrl()](#user-content-psw_PaymentSourceWidget+getIFrameUrl)
    * [.filterByGatewayIds(ids)](#user-content-psw_PaymentSourceWidget+filterByGatewayIds)
    * [.filterByTypes(types)](#user-content-psw_PaymentSourceWidget+filterByTypes)
    * [.setLanguage(code)](#user-content-psw_PaymentSourceWidget+setLanguage)

<a name="psw_new_HtmlPaymentSourceWidget_new" id="psw_new_HtmlPaymentSourceWidget_new" href="#user-content-psw_new_HtmlPaymentSourceWidget_new">&nbsp;</a>

### new HtmlPaymentSourceWidget(selector, publicKey, queryToken)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | Selector of html element. Container for widget |
| publicKey | <code>string</code> | PayDock users public key |
| queryToken | <code>string</code> | PayDock's query token that represents params to search customer by id or reference |

**Example**  

```javascript
* var widget = new HtmlPaymentSourceWidget('#widget', 'publicKey','queryToken');
```
<a name="psw_HtmlPaymentSourceWidget+load" id="psw_HtmlPaymentSourceWidget+load" href="#user-content-psw_HtmlPaymentSourceWidget+load">&nbsp;</a>

### htmlPaymentSourceWidget.load()
The final method to beginning, the load process of widget to html

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
<a name="psw_HtmlPaymentSourceWidget+on" id="psw_HtmlPaymentSourceWidget+on" href="#user-content-psw_HtmlPaymentSourceWidget+on">&nbsp;</a>

### htmlPaymentSourceWidget.on(eventName, cb)
Listen to events of widget

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| eventName | <code>string</code> | Available event names [EVENT](#user-content-psw_EVENT) |
| cb | [<code>listener--PaymentSourceWidget</code>](#user-content-psw_listener--PaymentSourceWidget) |  |

**Example**  

```javascript
widget.on('select', function (data) {
     console.log(data);
});
```
<a name="psw_HtmlPaymentSourceWidget+hide" id="psw_HtmlPaymentSourceWidget+hide" href="#user-content-psw_HtmlPaymentSourceWidget+hide">&nbsp;</a>

### htmlPaymentSourceWidget.hide([saveSize])
Using this method you can hide widget after load

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [saveSize] | <code>boolean</code> | <code>false</code> | using this param you can save iframe's size |

<a name="psw_HtmlPaymentSourceWidget+show" id="psw_HtmlPaymentSourceWidget+show" href="#user-content-psw_HtmlPaymentSourceWidget+show">&nbsp;</a>

### htmlPaymentSourceWidget.show()
Using this method you can show widget after using hide method

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
<a name="psw_HtmlPaymentSourceWidget+reload" id="psw_HtmlPaymentSourceWidget+reload" href="#user-content-psw_HtmlPaymentSourceWidget+reload">&nbsp;</a>

### htmlPaymentSourceWidget.reload()
Using this method you can reload widget

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
<a name="psw_HtmlPaymentSourceWidget+onSelectInsert" id="psw_HtmlPaymentSourceWidget+onSelectInsert" href="#user-content-psw_HtmlPaymentSourceWidget+onSelectInsert">&nbsp;</a>

### htmlPaymentSourceWidget.onSelectInsert(selector, dataType)
After select event of widget, data (dataType) will be insert to input (selector)

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | css selector . [] # |
| dataType | <code>string</code> | data type of [IEventSelectData](#user-content-psw_IEventSelectData). |

<a name="psw_PaymentSourceWidget+setStyles" id="psw_PaymentSourceWidget+setStyles" href="#user-content-psw_PaymentSourceWidget+setStyles">&nbsp;</a>

### htmlPaymentSourceWidget.setStyles(fields)
Object contain styles for widget

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>setStyles</code>](#user-content-psw_PaymentSourceWidget+setStyles)  

| Param | Type | Description |
| --- | --- | --- |
| fields | [<code>IStyles</code>](#user-content-psw_IStyles) | name of styles which can be shown in widget [STYLE](#user-content-psw_STYLE) |

**Example**  

```javascript
widget.setStyles({
      background_color: 'rgb(0, 0, 0)',
      border_color: 'yellow',
      text_color: '#FFFFAA',
      icon_size: 'small',
      font_size: '20px'
  });
```
<a name="psw_PaymentSourceWidget+setRefId" id="psw_PaymentSourceWidget+setRefId" href="#user-content-psw_PaymentSourceWidget+setRefId">&nbsp;</a>

### htmlPaymentSourceWidget.setRefId(refId)
Current method can set custom ID to identify the data in the future

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>setRefId</code>](#user-content-psw_PaymentSourceWidget+setRefId)  

| Param | Type | Description |
| --- | --- | --- |
| refId | <code>string</code> | custom id |

**Example**  

```javascript
widget.setRefId('id');
```
<a name="psw_PaymentSourceWidget+setLimit" id="psw_PaymentSourceWidget+setLimit" href="#user-content-psw_PaymentSourceWidget+setLimit">&nbsp;</a>

### htmlPaymentSourceWidget.setLimit(count)
Current method can set limit for payment sources count. In case when limit sets less then general count will be shown pagination buttons prev and next.

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>setLimit</code>](#user-content-psw_PaymentSourceWidget+setLimit)  

| Param | Type | Description |
| --- | --- | --- |
| count | <code>string</code> | payment source count |

<a name="psw_PaymentSourceWidget+setEnv" id="psw_PaymentSourceWidget+setEnv" href="#user-content-psw_PaymentSourceWidget+setEnv">&nbsp;</a>

### htmlPaymentSourceWidget.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox
Also we can change domain alias for this environment. By default domain_alias = paydock.com

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>setEnv</code>](#user-content-psw_PaymentSourceWidget+setEnv)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  

```javascript
widget.setEnv('production');
```
<a name="psw_PaymentSourceWidget+getIFrameUrl" id="psw_PaymentSourceWidget+getIFrameUrl" href="#user-content-psw_PaymentSourceWidget+getIFrameUrl">&nbsp;</a>

### htmlPaymentSourceWidget.getIFrameUrl()
Method for getting iframe's url

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>getIFrameUrl</code>](#user-content-psw_PaymentSourceWidget+getIFrameUrl)  
<a name="psw_PaymentSourceWidget+filterByGatewayIds" id="psw_PaymentSourceWidget+filterByGatewayIds" href="#user-content-psw_PaymentSourceWidget+filterByGatewayIds">&nbsp;</a>

### htmlPaymentSourceWidget.filterByGatewayIds(ids)
Show payment source inside widget only with requested gateway ids

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>filterByGatewayIds</code>](#user-content-psw_PaymentSourceWidget+filterByGatewayIds)  

| Param | Type | Description |
| --- | --- | --- |
| ids | <code>Array.&lt;string&gt;</code> | List of gateway_id |

<a name="psw_PaymentSourceWidget+filterByTypes" id="psw_PaymentSourceWidget+filterByTypes" href="#user-content-psw_PaymentSourceWidget+filterByTypes">&nbsp;</a>

### htmlPaymentSourceWidget.filterByTypes(types)
Show payment source inside widget only with requested payment source types

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>filterByTypes</code>](#user-content-psw_PaymentSourceWidget+filterByTypes)  

| Param | Description |
| --- | --- |
| types | List of payment source types. Available parameters [PAYMENT_TYPE](PAYMENT_TYPE) |

<a name="psw_PaymentSourceWidget+setLanguage" id="psw_PaymentSourceWidget+setLanguage" href="#user-content-psw_PaymentSourceWidget+setLanguage">&nbsp;</a>

### htmlPaymentSourceWidget.setLanguage(code)
Method for setting a custom language code

**Kind**: instance method of [<code>HtmlPaymentSourceWidget</code>](#user-content-psw_HtmlPaymentSourceWidget)  
**Overrides**: [<code>setLanguage</code>](#user-content-psw_PaymentSourceWidget+setLanguage)  

| Param | Type | Description |
| --- | --- | --- |
| code | <code>string</code> | ISO 639-1 |

**Example**  

```javascript
config.setLanguage('en');
```
<a name="psw_PaymentSourceWidget" id="psw_PaymentSourceWidget" href="#user-content-psw_PaymentSourceWidget">&nbsp;</a>

## PaymentSourceWidget
Class PaymentSourceWidget include method for for creating iframe url

**Kind**: global class  

* [PaymentSourceWidget](#user-content-psw_PaymentSourceWidget)
    * [new PaymentSourceWidget(publicKey, customer, [useReference])](#user-content-psw_new_PaymentSourceWidget_new)
    * [.setStyles(fields)](#user-content-psw_PaymentSourceWidget+setStyles)
    * [.setRefId(refId)](#user-content-psw_PaymentSourceWidget+setRefId)
    * [.setLimit(count)](#user-content-psw_PaymentSourceWidget+setLimit)
    * [.setEnv(env, [alias])](#user-content-psw_PaymentSourceWidget+setEnv)
    * [.getIFrameUrl()](#user-content-psw_PaymentSourceWidget+getIFrameUrl)
    * [.filterByGatewayIds(ids)](#user-content-psw_PaymentSourceWidget+filterByGatewayIds)
    * [.filterByTypes(types)](#user-content-psw_PaymentSourceWidget+filterByTypes)
    * [.setLanguage(code)](#user-content-psw_PaymentSourceWidget+setLanguage)

<a name="psw_new_PaymentSourceWidget_new" id="psw_new_PaymentSourceWidget_new" href="#user-content-psw_new_PaymentSourceWidget_new">&nbsp;</a>

### new PaymentSourceWidget(publicKey, customer, [useReference])

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| publicKey | <code>string</code> |  | PayDock users public key |
| customer | <code>string</code> |  | PayDock's customer_id or customer_reference (In order to use the customer_reference, you must explicitly specify useReference as true) |
| [useReference] | <code>boolean</code> | <code>false</code> |  |

**Example**  

```javascript
var widget = new PaymentSourceWidget('publicKey','customerId');
// or
var widget = new PaymentSourceWidget('publicKey', customerReference, true);
```
<a name="psw_PaymentSourceWidget+setStyles" id="psw_PaymentSourceWidget+setStyles" href="#user-content-psw_PaymentSourceWidget+setStyles">&nbsp;</a>

### paymentSourceWidget.setStyles(fields)
Object contain styles for widget

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| fields | [<code>IStyles</code>](#user-content-psw_IStyles) | name of styles which can be shown in widget [STYLE](#user-content-psw_STYLE) |

**Example**  

```javascript
widget.setStyles({
      background_color: 'rgb(0, 0, 0)',
      border_color: 'yellow',
      text_color: '#FFFFAA',
      icon_size: 'small',
      font_size: '20px'
  });
```
<a name="psw_PaymentSourceWidget+setRefId" id="psw_PaymentSourceWidget+setRefId" href="#user-content-psw_PaymentSourceWidget+setRefId">&nbsp;</a>

### paymentSourceWidget.setRefId(refId)
Current method can set custom ID to identify the data in the future

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| refId | <code>string</code> | custom id |

**Example**  

```javascript
widget.setRefId('id');
```
<a name="psw_PaymentSourceWidget+setLimit" id="psw_PaymentSourceWidget+setLimit" href="#user-content-psw_PaymentSourceWidget+setLimit">&nbsp;</a>

### paymentSourceWidget.setLimit(count)
Current method can set limit for payment sources count. In case when limit sets less then general count will be shown pagination buttons prev and next.

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| count | <code>string</code> | payment source count |

<a name="psw_PaymentSourceWidget+setEnv" id="psw_PaymentSourceWidget+setEnv" href="#user-content-psw_PaymentSourceWidget+setEnv">&nbsp;</a>

### paymentSourceWidget.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox
Also we can change domain alias for this environment. By default domain_alias = paydock.com

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  

```javascript
widget.setEnv('production');
```
<a name="psw_PaymentSourceWidget+getIFrameUrl" id="psw_PaymentSourceWidget+getIFrameUrl" href="#user-content-psw_PaymentSourceWidget+getIFrameUrl">&nbsp;</a>

### paymentSourceWidget.getIFrameUrl()
Method for getting iframe's url

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  
<a name="psw_PaymentSourceWidget+filterByGatewayIds" id="psw_PaymentSourceWidget+filterByGatewayIds" href="#user-content-psw_PaymentSourceWidget+filterByGatewayIds">&nbsp;</a>

### paymentSourceWidget.filterByGatewayIds(ids)
Show payment source inside widget only with requested gateway ids

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| ids | <code>Array.&lt;string&gt;</code> | List of gateway_id |

<a name="psw_PaymentSourceWidget+filterByTypes" id="psw_PaymentSourceWidget+filterByTypes" href="#user-content-psw_PaymentSourceWidget+filterByTypes">&nbsp;</a>

### paymentSourceWidget.filterByTypes(types)
Show payment source inside widget only with requested payment source types

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Description |
| --- | --- |
| types | List of payment source types. Available parameters [PAYMENT_TYPE](PAYMENT_TYPE) |

<a name="psw_PaymentSourceWidget+setLanguage" id="psw_PaymentSourceWidget+setLanguage" href="#user-content-psw_PaymentSourceWidget+setLanguage">&nbsp;</a>

### paymentSourceWidget.setLanguage(code)
Method for setting a custom language code

**Kind**: instance method of [<code>PaymentSourceWidget</code>](#user-content-psw_PaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| code | <code>string</code> | ISO 639-1 |

**Example**  

```javascript
config.setLanguage('en');
```
<a name="psw_EVENT" id="psw_EVENT" href="#user-content-psw_EVENT">&nbsp;</a>

## EVENT : <code>object</code>
List of available event's name

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| AFTER_LOAD | <code>string</code> | <code>&quot;afterLoad&quot;</code> | 
| SYSTEM_ERROR | <code>string</code> | <code>&quot;systemError&quot;</code> | 
| SELECT | <code>string</code> | <code>&quot;select&quot;</code> | 
| UNSELECT | <code>string</code> | <code>&quot;unselect&quot;</code> | 
| NEXT | <code>string</code> | <code>&quot;next&quot;</code> | 
| PREV | <code>string</code> | <code>&quot;prev&quot;</code> | 
| META_CHANGE | <code>string</code> | <code>&quot;metaChange&quot;</code> | 
| RESIZE | <code>string</code> | <code>&quot;resize&quot;</code> | 

<a name="psw_STYLE" id="psw_STYLE" href="#user-content-psw_STYLE">&nbsp;</a>

## STYLE : <code>object</code>
List of available style params for widget

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| BACKGROUND_COLOR | <code>string</code> | <code>&quot;background_color&quot;</code> | 
| BACKGROUND_ACTIVE_COLOR | <code>string</code> | <code>&quot;background_active_color&quot;</code> | 
| TEXT_COLOR | <code>string</code> | <code>&quot;text_color&quot;</code> | 
| BORDER_COLOR | <code>string</code> | <code>&quot;border_color&quot;</code> | 
| ICON_SIZE | <code>string</code> | <code>&quot;icon_size&quot;</code> | 
| FONT_SIZE | <code>string</code> | <code>&quot;font_size&quot;</code> | 

<a name="psw_PAYMENT_SOURCE_TYPE" id="psw_PAYMENT_SOURCE_TYPE" href="#user-content-psw_PAYMENT_SOURCE_TYPE">&nbsp;</a>

## PAYMENT\_SOURCE\_TYPE : <code>object</code>
List of available payment source types

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| CARD | <code>string</code> | <code>&quot;card&quot;</code> | 
| BANK_ACCOUNT | <code>string</code> | <code>&quot;bank_account&quot;</code> | 
| CHECKOUT | <code>string</code> | <code>&quot;checkout&quot;</code> | 

<a name="psw_listener--PaymentSourceWidget" id="psw_listener--PaymentSourceWidget" href="#user-content-psw_listener--PaymentSourceWidget">&nbsp;</a>

## listener--PaymentSourceWidget : <code>function</code>
This callback will be called for each event in payment source widget

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| response | <code>IEventData</code> \| [<code>IEventSelectData</code>](#user-content-psw_IEventSelectData) \| [<code>IEventPaginationData</code>](#user-content-psw_IEventPaginationData) \| [<code>IEventAfterLoadData</code>](#user-content-psw_IEventAfterLoadData) | 


## Checkout button

You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#cb_CheckoutButton)
Zipmoney meta parameters description [here](https://www.npmjs.com/package/@paydock/client-sdk#izipmoneymeta)

This widget allows you to turn your button into a full Checkout Button.
As a result, you will be able to receive a one-time token for charges, subscriptions etc. And other data given to the user by the payment gateway.



## Checkout button simple example

### Container

```html
<button type="button" id="button">
    checkout
</button>
```

You must create a button to turn it into checkout-button


### Initialization
```javascript
var button = new paydock.ZipmoneyCheckoutButton('#button', 'publicKey', 'gatewayId');
```

```javascript
// ES2015 | TypeScript


var button = new ZipmoneyCheckoutButton('#button', 'publicKey');
```

Then write only need 1 line of code in js to initialize widget

### Full ZipMoney example

```html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
<form id="paymentForm">
    <button type="button" id="button">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTVrrEYxDmq4WXv7hfHygKD9ltnOqv0K6soSAhmbKNllPNYWiLiJA" align="left" style="margin-right:7px;">
    </button>
</form>

<input type="text" name="pst" />

<script src="https://widget.paydock.com/sdk/latest/widget.umd.js" ></script>
<script>
	var button = new paydock.ZipmoneyCheckoutButton('#button', 'publicKey', 'gatewayId');
	button.onFinishInsert('input[name="pst"]', 'payment_source_token');
    button.setMeta("first_name": "Joshua",
       "tokenize": true,
       "last_name": "Wood",
       "email":"joshuawood@hotmail.com.au",
       "gender": "male",
       "charge": {
           "amount": "4",
           "currency":"AUD",
           "shipping_type": "delivery",
           "shipping_address": {
               "first_name": "Joshua",
               "last_name": "Wood",
               "line1": "Suite 660",
               "line2": "822 Ruiz Square",
               "country": "AU",
               "postcode": "3223",
               "city": "Sydney",
               "state": "LA"
           },
           "billing_address": {
               "first_name": "Joshua",
               "last_name": "Wood",
               "line1": "Suite 660",
               "line2": "test",
               "country": "AU",
               "postcode": "3223",
               "city": "Sydney",
               "state": "LA"
           },
           "items": [
               {
                   "name":"ACME Toolbox",
                   "amount":"2",
                   "quantity": 1,
                   "reference":"Fuga consequuntur sint ab magnam"
               },
               {
                   "name":"Device 42",
                   "amount":"2",
                   "quantity": 1,
                   "reference":"Fuga consequuntur sint ab magnam"
               }
           ]
       },

       "statistics": {
           "account_created": "2017-05-05",
           "sales_total_number": "5",
           "sales_total_amount": "4",
           "sales_avg_value": "45",
           "sales_max_value": "400",
           "refunds_total_amount": "21",
           "previous_chargeback": "true",
           "currency": "AUD",
           "last_login": "2017-06-01"
       });

    button.on('finish', function (data) {
           console.log('on:finish', data);
    });
</script>
</body>
</html>
```

## Classes

<dl>
<dt><a href="#user-content-cb_CheckoutButton">CheckoutButton</a></dt>
<dd><p>Class CheckoutButton transform usual button into checkout</p>
</dd>
<dt><a href="#user-content-cb_ZipmoneyCheckoutButton">ZipmoneyCheckoutButton</a> ⇐ <code><a href="#user-content-cb_CheckoutButton">CheckoutButton</a></code></dt>
<dd><p>Class ZipmoneyCheckoutButton is wrapper of CheckoutButton transform usual button into checkout</p>
</dd>
</dl>

## Members

<dl>
<dt><a href="#user-content-cb_CHECKOUT_MODE">CHECKOUT_MODE</a> : <code>object</code></dt>
<dd></dd>
<dt><a href="#user-content-cb_GATEWAY_TYPE">GATEWAY_TYPE</a> : <code>object</code></dt>
<dd></dd>
</dl>

## Constants

<dl>
<dt><a href="#user-content-cb_CHECKOUT_BUTTON_EVENT">CHECKOUT_BUTTON_EVENT</a> : <code>object</code></dt>
<dd></dd>
</dl>

## Typedefs

<dl>
<dt><a href="#user-content-cb_listener">listener</a> : <code>function</code></dt>
<dd><p>This callback will be called for each event in payment source widget</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#user-content-cb_IEventCheckoutFinishData">IEventCheckoutFinishData</a></dt>
<dd></dd>
<dt><a href="#user-content-cb_IPayPalMeta">IPayPalMeta</a></dt>
<dd><p>Interface for PayPal checkout meta information</p>
</dd>
<dt><a href="#user-content-cb_IZipmoneyMeta">IZipmoneyMeta</a></dt>
<dd><p>Interface for ZipMoney checkout meta information</p>
</dd>
<dt><a href="#user-content-cb_IAfterpayMeta">IAfterpayMeta</a></dt>
<dd><p>Interface for Afterpay checkout meta information</p>
</dd>
</dl>

<a name="cb_IEventCheckoutFinishData" id="cb_IEventCheckoutFinishData" href="#user-content-cb_IEventCheckoutFinishData">&nbsp;</a>

## IEventCheckoutFinishData
**Kind**: global interface  

| Param | Type |
| --- | --- |
| [payment_source_token] | <code>string</code> | 

<a name="cb_IPayPalMeta" id="cb_IPayPalMeta" href="#user-content-cb_IPayPalMeta">&nbsp;</a>

## IPayPalMeta
Interface for PayPal checkout meta information

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [brand_name] | <code>string</code> | A  label that overrides the business name in the PayPal account on the PayPal hosted checkout pages |
| [cart_border_color] | <code>string</code> | The HTML hex code for your principal identifying color |
| [reference] | <code>string</code> | Merchant Customer Service number displayed on the PayPal pages |
| [email] | <code>string</code> | The consumer’s email |
| [hdr_img] | <code>string</code> | URL for the image you want to appear at the top left of the payment page |
| [logo_img] | <code>string</code> | A URL to your logo image |
| [pay_flow_color] | <code>string</code> | Sets the background color for the payment page. By default, the color is white. |
| [first_name] | <code>string</code> | The consumer’s given names |
| [last_name] | <code>string</code> | The consumer’s surname |
| [address_line] | <code>string</code> | Street address |
| [address_line2] | <code>string</code> | Second line of the address |
| [address_city] | <code>string</code> | City |
| [address_state] | <code>string</code> | State |
| [address_postcode] | <code>string</code> | Postcode |
| [address_country] | <code>string</code> | Country |
| [phone] | <code>string</code> | The consumer’s phone number in E.164 international notation (Example: +12345678901) |
| [hide_shipping_address] | <code>boolean</code> | Determines whether PayPal displays shipping address fields on the PayPal pages |

<a name="cb_IZipmoneyMeta" id="cb_IZipmoneyMeta" href="#user-content-cb_IZipmoneyMeta">&nbsp;</a>

## IZipmoneyMeta
Interface for ZipMoney checkout meta information

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| first_name | <code>string</code> | First name for the customer |
| last_name | <code>string</code> | Last name for the customer |
| [phone] | <code>string</code> | The consumer’s phone number in E.164 international notation (Example: +12345678901) |
| [tokenize] | <code>boolean</code> | Controls whether to tokenize the zip pay / zip money account, defaults to ‘false’ |
| email | <code>string</code> | The consumer’s email |
| [gender] | <code>string</code> | Gender name for the customer |
| [date_of_birth] | <code>string</code> | Date of birth name for the customer |
| charge.amount | <code>number</code> | Amount to be paid |
| [charge.currency] | <code>string</code> | Currency code |
| [charge.reference] | <code>string</code> | Reference |
| charge.items | <code>array</code> | Collections of orders |
| charge.items[].name | <code>string</code> | Name of the item |
| charge.items[].amount | <code>number</code> | Amount of the item |
| charge.items[].quantity | <code>integer</code> | Quantity of the item |
| [charge.items[].type] | <code>string</code> | type of the item, values can be: ‘sku’, ‘tax’, ‘shipping’, ‘discount’ |
| [charge.items[].reference] | <code>string</code> | reference of the item |
| [charge.items[].item_uri] | <code>string</code> | url of the item in your store |
| [charge.items[].image_url] | <code>string</code> | url of the image in your store |
| [charge.shipping_type] | <code>string</code> | Shipping type, values can be: ‘pickup’, ‘delivery’, defaults to ‘delivery’ |
| [charge.shipping_address] | <code>string</code> | Object with shipping address details |
| [charge.shipping_address.first_name] | <code>string</code> | Shipping first name |
| [charge.shipping_address.last_name] | <code>string</code> | Shipping last name |
| charge.shipping_address.line1 | <code>string</code> | Shipping address line 1 |
| charge.shipping_address.line2 | <code>string</code> | Shipping address line 2 |
| charge.shipping_address.city | <code>string</code> | Shipping city |
| charge.shipping_address.state | <code>string</code> | Shipping state |
| charge.shipping_address.postcode | <code>string</code> | Shipping postcode |
| charge.shipping_address.country | <code>string</code> | Shipping country |
| charge.billing_address | <code>string</code> | Object with billing address details |
| [charge.billing_address.first_name] | <code>string</code> | Billing first name |
| [charge.billing_address.last_name] | <code>string</code> | Billing last name |
| charge.billing_address.line1 | <code>string</code> | Billing address line 1 |
| [charge.billing_address.line2] | <code>string</code> | Billing address line 1 |
| charge.billing_address.city | <code>string</code> | Billing city |
| charge.billing_address.state | <code>string</code> | Billing state |
| charge.billing_address.postcode | <code>string</code> | Billing postcode |
| charge.billing_address.country | <code>string</code> | Billing country |

<a name="cb_IAfterpayMeta" id="cb_IAfterpayMeta" href="#user-content-cb_IAfterpayMeta">&nbsp;</a>

## IAfterpayMeta
Interface for Afterpay checkout meta information

**Kind**: global interface  

| Param | Type |
| --- | --- |
| [amount] | <code>number</code> | 
| [currency] | <code>number</code> | 
| [first_name] | <code>string</code> | 
| [last_name] | <code>string</code> | 
| [email] | <code>string</code> | 
| [address_line] | <code>string</code> | 
| [address_line2] | <code>string</code> | 
| [address_city] | <code>string</code> | 
| [address_state] | <code>string</code> | 
| [address_postcode] | <code>string</code> | 
| [address_country] | <code>string</code> | 
| [phone] | <code>string</code> | 

<a name="cb_CheckoutButton" id="cb_CheckoutButton" href="#user-content-cb_CheckoutButton">&nbsp;</a>

## CheckoutButton
Class CheckoutButton transform usual button into checkout

**Kind**: global class  

* [CheckoutButton](#user-content-cb_CheckoutButton)
    * [new CheckoutButton(selector, aceessToken, [gatewayId], [type])](#user-content-cb_new_CheckoutButton_new)
    * [.on(eventName, cb)](#user-content-cb_CheckoutButton+on)
    * [.close()](#user-content-cb_CheckoutButton+close)
    * [.onFinishInsert(selector, dataType)](#user-content-cb_CheckoutButton+onFinishInsert)
    * [.setMeta(meta)](#user-content-cb_CheckoutButton+setMeta)
    * [.setBackdropDescription(text)](#user-content-cb_CheckoutButton+setBackdropDescription)
    * [.setBackdropTitle(string)](#user-content-cb_CheckoutButton+setBackdropTitle)
    * [.setSuspendedRedirectUri(string)](#user-content-cb_CheckoutButton+setSuspendedRedirectUri)
    * [.setRedirectUrl(string)](#user-content-cb_CheckoutButton+setRedirectUrl)
    * [.turnOffBackdrop()](#user-content-cb_CheckoutButton+turnOffBackdrop)

<a name="cb_new_CheckoutButton_new" id="cb_new_CheckoutButton_new" href="#user-content-cb_new_CheckoutButton_new">&nbsp;</a>

### new CheckoutButton(selector, aceessToken, [gatewayId], [type])

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| selector | <code>string</code> |  | Selector of html element. |
| aceessToken | <code>string</code> |  | PayDock access token or users public key |
| [gatewayId] | <code>string</code> | <code>&quot;default&quot;</code> | PayDock's gatewayId. By default or if put 'default', it will use the selected default gateway |
| [type] | <code>string</code> | <code>&quot;PaypalClassic&quot;</code> | Type of gateway (PaypalClassic, Zipmoney) |

**Example**  

```javascript
var widget = new CheckoutButton('#button', 'accessToken','gatewayId');
```
<a name="cb_CheckoutButton+on" id="cb_CheckoutButton+on" href="#user-content-cb_CheckoutButton+on">&nbsp;</a>

### checkoutButton.on(eventName, cb)
Listen to events of widget

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| eventName | <code>string</code> | Available event names [CHECKOUT_BUTTON_EVENT](#user-content-cb_CHECKOUT_BUTTON_EVENT) |
| cb | [<code>listener</code>](#user-content-cb_listener) |  |

**Example**  

```javascript
widget.on('click', function () {

});
```
<a name="cb_CheckoutButton+close" id="cb_CheckoutButton+close" href="#user-content-cb_CheckoutButton+close">&nbsp;</a>

### checkoutButton.close()
Close popup window forcibly.
Only for 'contextual' mode.

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  
<a name="cb_CheckoutButton+onFinishInsert" id="cb_CheckoutButton+onFinishInsert" href="#user-content-cb_CheckoutButton+onFinishInsert">&nbsp;</a>

### checkoutButton.onFinishInsert(selector, dataType)
After finish event of checkout button, data (dataType) will be insert to input (selector)

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | css selector . [] # |
| dataType | <code>string</code> | data type of IEventCheckoutFinishData [IEventCheckoutFinishData](#user-content-cb_IEventCheckoutFinishData). |

<a name="cb_CheckoutButton+setMeta" id="cb_CheckoutButton+setMeta" href="#user-content-cb_CheckoutButton+setMeta">&nbsp;</a>

### checkoutButton.setMeta(meta)
Method for setting meta information for checkout page

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>IPayPalMeta</code>](#user-content-cb_IPayPalMeta) \| [<code>IAfterpayMeta</code>](#user-content-cb_IAfterpayMeta) \| [<code>IZipmoneyMeta</code>](#user-content-cb_IZipmoneyMeta) | Data which can be shown on checkout page [IPayPalMeta](#user-content-cb_IPayPalMeta) [IZipmoneyMeta](#user-content-cb_IZipmoneyMeta) [IAfterpayMeta](#user-content-cb_IAfterpayMeta) |

**Example**  

```javascript
button.setMeta({
            brand_name: 'paydock',
            reference: '15',
            email: 'wault@paydock.com'
        });
```
<a name="cb_CheckoutButton+setBackdropDescription" id="cb_CheckoutButton+setBackdropDescription" href="#user-content-cb_CheckoutButton+setBackdropDescription">&nbsp;</a>

### checkoutButton.setBackdropDescription(text)
Method for setting backdrop description.
Only for 'contextual' mode.

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| text | <code>string</code> | description which can be shown in overlay of back side checkout page |

**Example**  

```javascript
button.setBackdropDescription('Custom description');
```
<a name="cb_CheckoutButton+setBackdropTitle" id="cb_CheckoutButton+setBackdropTitle" href="#user-content-cb_CheckoutButton+setBackdropTitle">&nbsp;</a>

### checkoutButton.setBackdropTitle(string)
Method for setting backdrop title.
Only for 'contextual' mode.

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| string | <code>text</code> | title which can be shown in overlay of back side checkout page |

**Example**  

```javascript
button.setBackdropTitle('Custom title');
```
<a name="cb_CheckoutButton+setSuspendedRedirectUri" id="cb_CheckoutButton+setSuspendedRedirectUri" href="#user-content-cb_CheckoutButton+setSuspendedRedirectUri">&nbsp;</a>

### checkoutButton.setSuspendedRedirectUri(string)
Method for setting suspended redirect uri. Redirect after referred checkout.
Only for 'contextual' mode.

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| string | <code>uri</code> | uri for redirect (by default) |

<a name="cb_CheckoutButton+setRedirectUrl" id="cb_CheckoutButton+setRedirectUrl" href="#user-content-cb_CheckoutButton+setRedirectUrl">&nbsp;</a>

### checkoutButton.setRedirectUrl(string)
Method for setting the merchant redirect URL.
Merchant's customers redirect after successfull checkout.
Only for 'redirect' mode.

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

| Param | Type | Description |
| --- | --- | --- |
| string | <code>url</code> | redirect url |

<a name="cb_CheckoutButton+turnOffBackdrop" id="cb_CheckoutButton+turnOffBackdrop" href="#user-content-cb_CheckoutButton+turnOffBackdrop">&nbsp;</a>

### checkoutButton.turnOffBackdrop()
Method for disable backdrop on the page.
Only for 'contextual' mode.

**Kind**: instance method of [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  
**Example**  

```javascript
button.turnOffBackdrop();
```
<a name="cb_ZipmoneyCheckoutButton" id="cb_ZipmoneyCheckoutButton" href="#user-content-cb_ZipmoneyCheckoutButton">&nbsp;</a>

## ZipmoneyCheckoutButton ⇐ [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)
Class ZipmoneyCheckoutButton is wrapper of CheckoutButton transform usual button into checkout

**Kind**: global class  
**Extends**: [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)  

* [ZipmoneyCheckoutButton](#user-content-cb_ZipmoneyCheckoutButton) ⇐ [<code>CheckoutButton</code>](#user-content-cb_CheckoutButton)
    * [new ZipmoneyCheckoutButton(selector, publicKey, [gatewayId], [gatewayId])](#user-content-cb_new_ZipmoneyCheckoutButton_new)
    * [.setSuspendedRedirectUri(string)](#user-content-cb_ZipmoneyCheckoutButton+setSuspendedRedirectUri)
    * [.setRedirectUrl(string)](#user-content-cb_ZipmoneyCheckoutButton+setRedirectUrl)
    * [.onClick(handler)](#user-content-cb_ZipmoneyCheckoutButton+onClick)
    * [.on(eventName, cb)](#user-content-cb_CheckoutButton+on)
    * [.close()](#user-content-cb_CheckoutButton+close)
    * [.onFinishInsert(selector, dataType)](#user-content-cb_CheckoutButton+onFinishInsert)
    * [.setMeta(meta)](#user-content-cb_CheckoutButton+setMeta)
    * [.setBackdropDescription(text)](#user-content-cb_CheckoutButton+setBackdropDescription)
    * [.setBackdropTitle(string)](#user-content-cb_CheckoutButton+setBackdropTitle)
    * [.turnOffBackdrop()](#user-content-cb_CheckoutButton+turnOffBackdrop)

<a name="cb_new_ZipmoneyCheckoutButton_new" id="cb_new_ZipmoneyCheckoutButton_new" href="#user-content-cb_new_ZipmoneyCheckoutButton_new">&nbsp;</a>

### new ZipmoneyCheckoutButton(selector, publicKey, [gatewayId], [gatewayId])

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| selector | <code>string</code> |  | Selector of html element. |
| publicKey | <code>string</code> |  | PayDock users public key |
| [gatewayId] | <code>string</code> | <code>&quot;default&quot;</code> | PayDock's gatewayId. By default or if put 'default', it will use the selected default gateway |
| [gatewayId] | <code>string</code> | <code>&quot;default&quot;</code> | Checkout mode, it could be set to 'contextual' or 'redirect'. By default it 'contextual' |

**Example**  

```javascript
var widget = new ZipmoneyCheckoutButton('#button', 'publicKey','gatewayId');
```
<a name="cb_ZipmoneyCheckoutButton+setSuspendedRedirectUri" id="cb_ZipmoneyCheckoutButton+setSuspendedRedirectUri" href="#user-content-cb_ZipmoneyCheckoutButton+setSuspendedRedirectUri">&nbsp;</a>

### zipmoneyCheckoutButton.setSuspendedRedirectUri(string)
Method for setting suspended redirect uri. Redirect after referred checkout

The URI is used for a redirect after the checkout is complete.
This can be provided, even if using in-context checkout (sdk). By default, the standard styled page will be used.
If using in-context (sdk) we will not automatically redirect to this URI.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>setSuspendedRedirectUri</code>](#user-content-cb_CheckoutButton+setSuspendedRedirectUri)  

| Param | Type | Description |
| --- | --- | --- |
| string | <code>uri</code> | uri for suspended redirect (by default) |

<a name="cb_ZipmoneyCheckoutButton+setRedirectUrl" id="cb_ZipmoneyCheckoutButton+setRedirectUrl" href="#user-content-cb_ZipmoneyCheckoutButton+setRedirectUrl">&nbsp;</a>

### zipmoneyCheckoutButton.setRedirectUrl(string)
Method for setting the merchant redirect URL.
The merchant's customers would be redirected to the specified URL
at the end of ZipMoney checkout flow.

Once the redirect URL would be set, the checkout flow would be immediately switched
from 'contextual' mode to the 'redirect' mode.
The merchant's customer would be automatically redirected to this URL after the checkout is complete.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>setRedirectUrl</code>](#user-content-cb_CheckoutButton+setRedirectUrl)  

| Param | Type | Description |
| --- | --- | --- |
| string | <code>url</code> | URL for redirect |

<a name="cb_ZipmoneyCheckoutButton+onClick" id="cb_ZipmoneyCheckoutButton+onClick" href="#user-content-cb_ZipmoneyCheckoutButton+onClick">&nbsp;</a>

### zipmoneyCheckoutButton.onClick(handler)
Subscribe to the click event with an async handler.
The checkout flow will wait for the async handler to complete before proceeding.
If the handler resolves to `false`, the checkout flow will be cancelled.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  

| Param | Description |
| --- | --- |
| handler | Async function to be called when the button is clicked |

**Example**  

```javascript
button.onClick(async () => {
    const isValid = await fetchDataFromServer();
    return isValid; // return false to stop checkout
});
```
<a name="cb_CheckoutButton+on" id="cb_CheckoutButton+on" href="#user-content-cb_CheckoutButton+on">&nbsp;</a>

### zipmoneyCheckoutButton.on(eventName, cb)
Listen to events of widget

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>on</code>](#user-content-cb_CheckoutButton+on)  

| Param | Type | Description |
| --- | --- | --- |
| eventName | <code>string</code> | Available event names [CHECKOUT_BUTTON_EVENT](#user-content-cb_CHECKOUT_BUTTON_EVENT) |
| cb | [<code>listener</code>](#user-content-cb_listener) |  |

**Example**  

```javascript
widget.on('click', function () {

});
```
<a name="cb_CheckoutButton+close" id="cb_CheckoutButton+close" href="#user-content-cb_CheckoutButton+close">&nbsp;</a>

### zipmoneyCheckoutButton.close()
Close popup window forcibly.
Only for 'contextual' mode.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>close</code>](#user-content-cb_CheckoutButton+close)  
<a name="cb_CheckoutButton+onFinishInsert" id="cb_CheckoutButton+onFinishInsert" href="#user-content-cb_CheckoutButton+onFinishInsert">&nbsp;</a>

### zipmoneyCheckoutButton.onFinishInsert(selector, dataType)
After finish event of checkout button, data (dataType) will be insert to input (selector)

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>onFinishInsert</code>](#user-content-cb_CheckoutButton+onFinishInsert)  

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | css selector . [] # |
| dataType | <code>string</code> | data type of IEventCheckoutFinishData [IEventCheckoutFinishData](#user-content-cb_IEventCheckoutFinishData). |

<a name="cb_CheckoutButton+setMeta" id="cb_CheckoutButton+setMeta" href="#user-content-cb_CheckoutButton+setMeta">&nbsp;</a>

### zipmoneyCheckoutButton.setMeta(meta)
Method for setting meta information for checkout page

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>setMeta</code>](#user-content-cb_CheckoutButton+setMeta)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>IPayPalMeta</code>](#user-content-cb_IPayPalMeta) \| [<code>IAfterpayMeta</code>](#user-content-cb_IAfterpayMeta) \| [<code>IZipmoneyMeta</code>](#user-content-cb_IZipmoneyMeta) | Data which can be shown on checkout page [IPayPalMeta](#user-content-cb_IPayPalMeta) [IZipmoneyMeta](#user-content-cb_IZipmoneyMeta) [IAfterpayMeta](#user-content-cb_IAfterpayMeta) |

**Example**  

```javascript
button.setMeta({
            brand_name: 'paydock',
            reference: '15',
            email: 'wault@paydock.com'
        });
```
<a name="cb_CheckoutButton+setBackdropDescription" id="cb_CheckoutButton+setBackdropDescription" href="#user-content-cb_CheckoutButton+setBackdropDescription">&nbsp;</a>

### zipmoneyCheckoutButton.setBackdropDescription(text)
Method for setting backdrop description.
Only for 'contextual' mode.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>setBackdropDescription</code>](#user-content-cb_CheckoutButton+setBackdropDescription)  

| Param | Type | Description |
| --- | --- | --- |
| text | <code>string</code> | description which can be shown in overlay of back side checkout page |

**Example**  

```javascript
button.setBackdropDescription('Custom description');
```
<a name="cb_CheckoutButton+setBackdropTitle" id="cb_CheckoutButton+setBackdropTitle" href="#user-content-cb_CheckoutButton+setBackdropTitle">&nbsp;</a>

### zipmoneyCheckoutButton.setBackdropTitle(string)
Method for setting backdrop title.
Only for 'contextual' mode.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>setBackdropTitle</code>](#user-content-cb_CheckoutButton+setBackdropTitle)  

| Param | Type | Description |
| --- | --- | --- |
| string | <code>text</code> | title which can be shown in overlay of back side checkout page |

**Example**  

```javascript
button.setBackdropTitle('Custom title');
```
<a name="cb_CheckoutButton+turnOffBackdrop" id="cb_CheckoutButton+turnOffBackdrop" href="#user-content-cb_CheckoutButton+turnOffBackdrop">&nbsp;</a>

### zipmoneyCheckoutButton.turnOffBackdrop()
Method for disable backdrop on the page.
Only for 'contextual' mode.

**Kind**: instance method of [<code>ZipmoneyCheckoutButton</code>](#user-content-cb_ZipmoneyCheckoutButton)  
**Overrides**: [<code>turnOffBackdrop</code>](#user-content-cb_CheckoutButton+turnOffBackdrop)  
**Example**  

```javascript
button.turnOffBackdrop();
```
<a name="cb_CHECKOUT_MODE" id="cb_CHECKOUT_MODE" href="#user-content-cb_CHECKOUT_MODE">&nbsp;</a>

## CHECKOUT\_MODE : <code>object</code>
**Kind**: global variable  

| Param | Type | Default |
| --- | --- | --- |
| CONTEXTUAL | <code>string</code> | <code>&quot;contextual&quot;</code> | 
| REDIRECT | <code>string</code> | <code>&quot;redirect&quot;</code> | 

<a name="cb_GATEWAY_TYPE" id="cb_GATEWAY_TYPE" href="#user-content-cb_GATEWAY_TYPE">&nbsp;</a>

## GATEWAY\_TYPE : <code>object</code>
**Kind**: global variable  

| Param | Type | Default |
| --- | --- | --- |
| ZIPMONEY | <code>string</code> | <code>&quot;Zipmoney&quot;</code> | 
| PAYPAL | <code>string</code> | <code>&quot;PaypalClassic&quot;</code> | 
| AFTERPAY | <code>string</code> | <code>&quot;Afterpay&quot;</code> | 

<a name="cb_CHECKOUT_BUTTON_EVENT" id="cb_CHECKOUT_BUTTON_EVENT" href="#user-content-cb_CHECKOUT_BUTTON_EVENT">&nbsp;</a>

## CHECKOUT\_BUTTON\_EVENT : <code>object</code>
**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| CLICK | <code>string</code> | <code>&quot;click&quot;</code> | 
| POPUP_REDIRECT | <code>string</code> | <code>&quot;popup_redirect&quot;</code> | 
| ERROR | <code>string</code> | <code>&quot;error&quot;</code> | 
| ACCEPTED | <code>string</code> | <code>&quot;accepted&quot;</code> | 
| FINISH | <code>string</code> | <code>&quot;finish&quot;</code> | 
| CLOSE | <code>string</code> | <code>&quot;close&quot;</code> | 

<a name="cb_listener" id="cb_listener" href="#user-content-cb_listener">&nbsp;</a>

## listener : <code>function</code>
This callback will be called for each event in payment source widget

**Kind**: global typedef  

## Api
You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#api)

This wrapper helps you to work with paydock api emdpoints

### Get browser details
```javascript
var browserDetails = await new paydock.Api('publicKey').setEnv('env').getBrowserDetails();
```

```javascript
// ES2015 | TypeScript

import { Api } from '@paydock/client-sdk';

var browserDetails = await new paydock.Api('publicKey').setEnv('env').getBrowserDetails();
```

### Initialization
```javascript
var response = await new paydock.Api('publicKey').setEnv('env').charge().preAuth({
      amount: 100,
      currency: 'AUD',
      token: 'token',
    });
```

```javascript
// ES2015 | TypeScript

import { Api } from '@paydock/client-sdk';

var response = await new Api('publicKey').setEnv('env').charge().preAuth({
      amount: 100,
      currency: 'AUD',
      token: 'token',
    });
```

Then write only need 2 lines of code in js to make request

### Initialization full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style></style>
</head>
<body>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
    <script>
         (async function() {
            var response = await new Api('publicKey').setEnv('env').charge().preAuth({
                amount: 100,
                currency: 'AUD',
                token: 'token',
            });
        })();
    </script>
</body>
</html>
```

## Canvas3ds
You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#canvas3d)

This widget provides you to integrate 3d Secure

## Canvas3ds simple example

### Container

```html
<div id="widget"></div>
```

You must create a container for the widget. Inside this tag, the widget will be initialized


### Initialization
```javascript
var canvas3ds = new paydock.Canvas3ds('#widget', 'token');
canvas3ds.load();
```

```javascript
// ES2015 | TypeScript

import { Canvas3ds } from '@paydock/client-sdk';

var list = new Canvas3ds('#widget', 'token');
list.load();
```

Then write only need 2 lines of code in js to initialize widget


### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 300px;}</style>
</head>
<body>
    <div id="widget"></div>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script>
    <script>
        var canvas3ds = new paydock.Canvas3ds('#widget', 'token');
        canvas3ds.load();
    </script>
</body>
</html>
```


## Canvas3ds advanced example

### Settings

```javascript

canvas3ds.setEnv('sandbox'); // set enviroment

canvas3ds.hide(); // hide widget

canvas3ds.show(); // show widget

canvas3ds.on('chargeAuthSuccess', function (data) {
  console.log(data);
});
canvas3ds.on('chargeAuthReject', function (data) {
  console.log(data);
});
canvas3ds.on('chargeAuthCancelled', function (data) {
  console.log(data);
});
canvas3ds.on('additionalDataCollectSuccess', function (data) {
  console.log(data);
});
canvas3ds.on('additionalDataCollectReject', function (data) {
  console.log(data);
});
canvas3ds.on('chargeAuth', function (data) {
  console.log(data);
});
```

This example shows how you can use a lot of other methods to settings your form

### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 450px;}</style>
</head>
<body>
    <div id="widget3ds"></div>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script>
    <script>
        var canvas3ds = new paydock.Canvas3ds('#widget3ds', 'token');
        canvas3ds.on('chargeAuthSuccess', function (data) {
            console.log('chargeAuthSuccess', data);
        });
        canvas3ds.on('chargeAuthReject', function (data) {
            console.log('chargeAuthReject', data);
        });
        canvas3ds.load();
    </script>
</body>
</html>
```

### Full example with pre authorization

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 450px;}</style>
</head>
<body>
    <div id="widget"></div>
    <div id="widget3ds"></div>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script>
    <script>
        (async function () {
            var htmlWidget = new paydock.HtmlWidget('#widget', 'publicKey', 'gatewayId');
            htmlWidget.load();
            var {payment_source} = await htmlWidget.on('finish');
            var preAuthResp = await new paydock.Api('publicKey').setEnv('sandbox').charge().preAuth({
                  amount: 100,
                  currency: 'AUD',
                  token: payment_source,
                });
            var canvas = new paydock.Canvas3ds('#widget3ds', preAuthResp._3ds.token);
            canvas.load();
            var chargeAuthEvent = await canvas.on('chargeAuth');
            console.log('chargeAuthEvent', chargeAuthEvent);
        })()
    </script>
</body>
</html>
```

## Canvas 3ds for Standalone 3ds charges

After you initialized the standalone 3ds charge via `v1/charges/standalone-3ds` API endpoint, you get a token used to initialize the Canvas3ds. All above information regarding setup, loading and initialization still apply.

### Full example

```html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Title</title>
        <style>
            iframe {
                border: 0;
                width: 40%;
                height: 450px;
            }
        </style>
    </head>
    <body>
        <div id="widget3ds"></div>
        <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script>
        <script>
            var canvas3ds = new paydock.Canvas3ds("#widget3ds", "token");
            canvas3ds.on("chargeAuthSuccess", function (data) {
                console.log(data);
            });
            canvas3ds.on("chargeAuthReject", function (data) {
                console.log(data);
            });
            canvas3ds.on("chargeAuthChallenge", function (data) {
                console.log(data);
            });
            canvas3ds.on("chargeAuthDecoupled", function (data) {
                console.log(data.result.description);
            });
            canvas3ds.on("chargeAuthInfo", function (data) {
                console.log(data.info);
            });
            canvas3ds.on("error", function ({ charge_3ds_id, error }) {
                console.log(error);
            });
            canvas3ds.load();
        </script>
    </body>
</html>
```

- The `chargeAuthSuccess` event is executed both for frictionless flow, or for challenge flow after the customer has correctly authenticated with the bank using whatever challenge imposed.
- The `chargeAuthReject` event is executed when the authorization was rejected or when a timeout was received by the underlying system:
  - A `data.status` of `AuthTimedOut` will be received for timeouts.
  - A `data.status` of `rejected` will be received when the authorization was rejected.
  - A `data.status` of `invalid_event` will be received for unhandled situations.
- The `chargeAuthChallenge` event is sent before starting a challenge flow (i.e. opening an IFrame for the customer to complete a challenge with ther bank). Once the end customer performs the challenge, the Canvas3ds will be able to identify the challenge result and will either produce a `chargeAuthSuccess` or `chargeAuthReject` event.
- The `chargeAuthDecoupled` event is sent when the flow is a decoupled challenge, alongside a `data.result.description` field that you must show to the customer, indicating the method the user must use to authenticate. For example this may happen by having the cardholder authenticating directly with their banking app through biometrics. Once the end customer does this, the Canvas3ds will be able to recognize the challenge result is ready and will either produce a `chargeAuthSuccess` or `chargeAuthReject` event.
- The `error` event is sent if an unexpected issue with the client library occurs. In such scenarios, you should consider the autentication process as interrupted:
  - When getting this event, you will get on `data.error` the full error object.

### Events and Values

| Event Value         | Type                | Description                                                    |
| ------------------- | ------------------- | -------------------------------------------------------------- |
| <code>chargeAuthSuccess</code> | <code>object</code> | Instance of [ChargeEventResponse](#cb_chargeEventResponse) |
| <code>chargeAuthReject</code> | <code>object</code> | Instance of [ChargeEventResponse](#cb_chargeEventResponse) |
| <code>chargeAuthChallenge</code> | <code>object</code> | Instance of [ChargeEventResponse](#cb_chargeEventResponse) |
| <code>chargeAuthDecoupled</code> | <code>object</code> | Instance of [ChargeEventResponse](#cb_chargeEventResponse) |
| <code>chargeAuthInfo</code> | <code>object</code> | Instance of [ChargeEventResponse](#cb_chargeEventResponse) |
| <code>error</code> | <code>object</code> | Instance of [chargeError](#cb_chargeError) |

## Response Values

<a name="cb_chargeEventResponse" id="cb_chargeEventResponse"></a>

### ChargeEventResponse

| Param                           | Type                           | Description                                                                                        |
| ------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- |
| <code>status</code> | <code>string</code> | status for the event transaction |
| <code>charge_3ds_id</code> | <code>string</code> | Universal unique transaction identifier to identify the transaction |
| <code>info</code> | <code>string</code> | info field for `chargeAuthInfo` event |
| <code>result.description</code> | <code>string</code> [Optional] | field that you must show to the customer, indicating the method the user must use to authenticate during the decoupled challenge flow. |

### ChargeError

<a name="cb_chargeError" id="cb_chargeError"></a>

| Param         | Type                | Description                                                         |
| ------------- | ------------------- | ------------------------------------------------------------------- |
| <code>error</code> | <code>object</code> | error response |
| <code>charge_3ds_id</code> | <code>string</code> | Universal unique transaction identifier to identify the transaction |

## Wallet Buttons
You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#wallet-buttons-simple-example)

Wallet Buttons allow you to easily integrate different E-Wallets into your checkout.
Currently supports ApplePay, Google Pay, Google Pay and Apple Pay via Stripe and Flypay V2 checkout, Paypal Smart Buttons Checkout and Afterpay.

If available in your client environment, you will display a simple button that upon clicking it the user will follow the standard flow for the appropriate Wallet. If not available an event will be raised and no button will be displayed.

## Wallet Buttons simple example

### Container

```html
<div id="widget"></div>
```

You must create a container for the Wallet Buttons. Inside this tag, the button will be initialized.

Before initializing the button, you must perform a POST request to `charges/wallet` from a secure environment like your server. This call will return a token that is required to load the button and securely complete the payment. You can find the documentation to this call in the PayDock API documentation.

### Initialization

For Afterpay wallet, the country code is required:
```javascript
let button = new paydock.WalletButtons(
    "#widget",
    token,
    {
        country: "AU",
    }
);
button.load();
```

```javascript
// ES2015 | TypeScript
import { WalletButtons } from '@paydock/client-sdk';

var button = new WalletButtons(
    '#widget',
    token,
    {
        country: 'AU',
    }
);
button.load();
```

For Flypay v2 wallet, the client_id is required:
```javascript
let button = new paydock.WalletButtons(
    "#widget",
    token,
    {
        client_id: "client_id",
    }
);
button.load();
```

```javascript
// ES2015 | TypeScript
import { WalletButtons } from '@paydock/client-sdk';

var button = new WalletButtons(
    '#widget',
    token,
    {
        client_id: "client_id",
    }
);
button.load();
```

### Setting environment

Current method can change environment. By default environment = sandbox.
Bear in mind that you must set an environment before calling `button.load()`.

```javascript
button.setEnv('sandbox');
```

### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
        let button = new paydock.WalletButtons(
            "#widget",
            token,
            {
                amount_label: "Total",
                country: "DE",
            }
        );
        button.load();
</script>
</html>
```

## Wallet Buttons advanced example

### Checking for button availability

If the customer's browser is not supported, or the customer does not have any card added to their Google Pay or Apple Pay wallets, the button will not load. In this case the callback onUnavailable() will be called. You can define the behavior of this function before loading the button.

```javascript
button.onUnavailable(() => console.log("No wallet buttons available"));
```

### Performing actions when the wallet button is clicked

In some situations you may want to perform some validations or actions when the user clicks on the wallet button, for which you can use this method. Currently supported by Paypal, ApplePay and GooglePay wallets.

```javascript
button.onClick(() => console.log("Perform actions on button click"));
```

### Performing actions when shipping info is updated

In Paypal, ApplePay via MPGS and GooglePay via MPGS integrations after each shipping info update the `onUpdate(data)` will be called with the selected shipping address information, plus selected shipping method when applicable for Paypal, ApplePay and GooglePay. Merchants should handle this callback, recalculate shipping costs in their server by analyzing the new data, and submit a backend to backend request to `POST charges/:id` with the new total amount and shipping amount (you can find the documentation of this call in the PayDock API documentation).

For Paypal integration specifically, if shipping is enabled for the wallet button and different shipping methods were provided in the create wallet charge call, Merchants must ensure that the posted `shipping.amount` to `POST charges/:id` matches the selected shipping option amount (value sent in when initializing the wallet charge). In other words, when providing shipping methods the shipping amount is bound to being one of the provided shipping method amount necessarily. Bear in mind that the total charge amount must include the `shipping.amount`, since it represents the full amount to be charged to the customer.

After analyzing the new shipping information, and making the post with the updated charge and shipping amounts if necessary, the `button.update({ success: true/false })` wallet button method needs to be called to resume the interactions with the customer. Not calling this will result in unexpected behavior.

```javascript
button.onUpdate((data) => {
    console.log("Updating amount via a backend to backend call to POST charges/:id");
     // call `POST charges/:id` to modify charge
     button.update({ success: true });
});
```

For ApplePay via MPGS and GooglePay via MPGS integrations, you can also return a new `amount` and new `shipping_options` in case new options are needed based on the updated shipping data. Before the user authorizes the transaction, you receive redacted address information (address_country, address_city, address_state, address_postcode), and this data can be used to recalculate the new amount and new shipping options.

```javascript
button.onUpdate((data) => {
    console.log("Updating amount via a backend to backend call to POST charges/:id");
     // call `POST charges/:id` to modify charge
     button.update({
        success: true,
        body: {
            amount: 15,
            shipping_options: [
                {
                    id: "NEW-FreeShip",
                    label: "NEW - Free Shipping",
                    detail: "Arrives in 3 to 5 days",
                    amount: "0.00"
                },
                {
                    id: "NEW-FastShip",
                    label: "NEW - Fast Shipping",
                    detail: "Arrives in less than 1 day",
                    amount: "10.00"
                }
            ]
        }
    });
});
```

### Performing actions after the payment is completed

After the payment is completed, the onPaymentSuccessful(data) will be called if the payment was successful. If the payment was not successful, the function onPaymentError(data) will be called. If fraud check is active for the gateway, a fraud body was sent in the wallet charge initialize call and the fraud service left the charge in review, then the onPaymentInReview(data) will be called.
All three callbacks return relevant data according to each one of the scenarios.

>*Note that these callbacks will not be triggered for the Afterpay wallet when Redirect mode is used, that is when the charge is initialized with the success_url and error_url parameters, since the payment completion is done through the Redirect method, and therefore this SDK will not be loaded once the payment is completed at checkout.*

```javascript
button.onPaymentSuccessful((data) => console.log("The payment was successful"));
```

```javascript
button.onPaymentInReview((data) => console.log("The payment is on fraud review"));
```

```javascript
button.onPaymentError((data) => console.log("The payment was not successful"));
```
### Events
The above events can be used in a more generic way via de `on` function, and making use
of the corresponding event names.

```javascript
button.on(EVENT.UNAVAILABLE, () => console.log("No wallet buttons available"));
button.on(EVENT.UPDATE, (data) => console.log("Updating amount via a backend to backend call to POST charges/:id"));
button.on(EVENT.PAYMENT_SUCCESSFUL, (data) => console.log("The payment was successful"));
button.on(EVENT.PAYMENT_ERROR, (data) => console.log("The payment was not successful"));
```

This example shows how to use these functions for **Paypal Smart Checkout Buttons**:
_(Required `meta` fields: - . Optional `meta` fields: `request_shipping`, `pay_later`, `standalone`, `style`)_
### Paypal Smart Checkout Buttons Full example
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.WalletButtons(
        "#widget",
        charge_token,
        {
            request_shipping: true,
            pay_later: true,
            standalone: false,
            style: {
                layout: 'horizontal',
                color: 'blue',
                shape: 'rect',
                label: 'paypal',
            },
        }
    );
    button.setEnv('sandbox');
    button.onUnavailable(() => console.log("No wallet buttons available"));
    button.onUpdate((data) => {
        console.log("Updating amount via a backend to backend call to POST charges/:id");
        // call `POST charges/:id` to modify charge
        button.update({ success: true });
    });
    button.onPaymentSuccessful((data) => console.log("The payment was successful"));
    button.onPaymentError((data) => console.log("The payment was not successful"));
    button.onPaymentInReview((data) => console.log("The payment is on fraud review"));

    // Example 1: Asynchronous onClick handler
    const asyncLogic = async () => {
        // Perform asynchronous logic. Expectation is that a Promise is returned and attached to response via `attachResult`,
        // and resolve or reject of it will dictate how wallet behaves.
    }

    button.onClick(({ data: { attachResult } }) => {
        // Promise is attached to the result. On Paypal, when promise is resolved, the user Journey will continue.
        // If no promise is attached then the Paypal journey will not depend on the promise being resolved or rejected
        attachResult(asyncLogic());
    });

    // Example 2: Synchronous onClick handler
    // button.onClick(({ data: { attachResult } }) => {
    //     // Perform synchronous logic
    //     console.log("Synchronous onClick: Button clicked");
    //     // Optionally return a boolean flag to halt the operation
    //     attachResult(false);
    // });

    button.load();
</script>
</html>
```

This example shows how to use these functions for **Flypay v2 Wallet**.
_(Required `meta` fields: - . Optional `meta` fields: -)_
### Flypay V2 Full example
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.WalletButtons(
		"#widget",
		charge_token,
		{
            access_token: 'TOKEN',
            refresh_token: 'TOKEN',
            client_id: 'CLIENT_ID',
        },
	);
    button.setEnv('sandbox');
    button.onUnavailable((data) => console.log("No wallet buttons available"));
    button.onPaymentSuccessful((data) => console.log("The payment was successful"));
    button.onPaymentError((data) => console.log("The payment was not successful"));
    button.onAuthTokensChanged((data) => console.log('Authentication tokens changed'));
    button.load();
</script>
</html>
```

This example shows how to use these functions for **ApplePay via MPGS** and **GooglePay via MPGS**:

_(Required `meta` fields: `amount_label`, `country`. Optional `meta` fields: `raw_data_initialization`, `request_shipping`, `style.button_type`, `style.button_style`)_
### ApplePay and GooglePay via MPGS Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.WalletButtons(
        "#widget",
        charge_token,
        {
            amount_label: "Total",
            country: 'DE',
            request_shipping: true,
            show_billing_address: true,
            style: {
                google: {
                    button_type: 'buy',
                    button_size_mode: 'static',
                    button_color: 'white',
                },
                apple: {
                    button_type: 'buy',
                    button_style: 'black',
                },
            },
            shipping_options: [
                {
                    id: "FreeShip",
                    label: "Free Shipping",
                    detail: "Arrives in 5 to 7 days",
                    amount: "0.00"
                },
                {
                    id: "FastShip",
                    label: "Fast Shipping",
                    detail: "Arrives in 1 day",
                    amount: "10.00"
                }
            ]
        }
    );
    button.setEnv('sandbox');
    button.onUnavailable(() => console.log("No wallet buttons available"));
    button.onPaymentSuccessful((data) => console.log("The payment was successful"));
    button.onPaymentError((data) => console.log("The payment was not successful"));
    button.onClick(() => console.log("On WalletButton Click"));
    button.onUpdate((data) => {
        console.log("Updating amount via a backend to backend call to POST charges/:id");
        // call `POST charges/:id` to modify charge
        button.update({
            success: true,
            body: {
                amount: 15,
                shipping_options: [
                    {
                        id: "NEW-FreeShip",
                        label: "NEW - Free Shipping",
                        detail: "Arrives in 3 to 5 days",
                        amount: "0.00"
                    },
                    {
                        id: "NEW-FastShip",
                        label: "NEW - Fast Shipping",
                        detail: "Arrives in less than 1 day",
                        amount: "10.00"
                    }
                ]
            }
        });
    });
    button.load();
</script>
</html>
```

Also, for **ApplePay via MPGS** you can initialize the `ApplePayPaymentRequest` with your own values instead of using the default ones. Below you can see an example on how to initialize the `ApplePayPaymentRequest` with the `raw_data_initialization` meta field.

Similarly, for **GooglePay via MPGS** you can initialize the `PaymentMethodSpecification` with your own values instead of using the default ones. Below you can see an example on how to initialize the `PaymentMethodSpecification` with the `raw_data_initialization` meta field.
### ApplePay and GooglePay via MPGS Raw data initialization example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.WalletButtons(
        "#widget",
        charge_token,
        {
            raw_data_initialization: {
                apple: {
                    countryCode: "AU",
                    currencyCode: "AUD",
                    merchantCapabilities: ["supports3DS","supportsCredit","supportsDebit"],
                    supportedNetworks: ["visa","masterCard","amex","discover"],
                    requiredBillingContactFields: ["name","postalAddress"],
                    requiredShippingContactFields:["postalAddress","name","phone","email" ],
                    total: {
                        label: "Total",
                        amount: "10",
                        type: "final",
                    }
                },
                google: {
                    type: "CARD",
                    parameters: {
                        allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
                        allowedCardNetworks: [
                            "AMEX",
                            "DISCOVER",
                            "INTERAC",
                            "JCB",
                            "MASTERCARD",
                            "VISA",
                        ],
                        billingAddressRequired: true,
                    },
                },
            },
            amount_label: "Total",
            country: 'DE',
            request_shipping: true,
            show_billing_address: true,
            style: {
                google: {
                    button_type: 'buy',
                    button_size_mode: 'static',
                    button_color: 'white',
                },
                apple: {
                    button_type: 'buy',
                    button_style: 'black',
                },
            },
            shipping_options: [
                {
                    id: "FreeShip",
                    label: "Free Shipping",
                    detail: "Arrives in 5 to 7 days",
                    amount: "0.00"
                },
                {
                    id: "FastShip",
                    label: "Fast Shipping",
                    detail: "Arrives in 1 day",
                    amount: "10.00"
                }
            ]
        }
    );
    button.setEnv('sandbox');
    button.onUnavailable(() => console.log("No wallet buttons available"));
    button.onPaymentSuccessful((data) => console.log("The payment was successful"));
    button.onPaymentError((data) => console.log("The payment was not successful"));
    button.onUpdate((data) => {
        console.log("Updating amount via a backend to backend call to POST charges/:id");
        // call `POST charges/:id` to modify charge
        button.update({
            success: true,
            body: {
                amount: 15,
                shipping_options: [
                    {
                        id: "NEW-FreeShip",
                        label: "NEW - Free Shipping",
                        detail: "Arrives in 3 to 5 days",
                        amount: "0.00"
                    },
                    {
                        id: "NEW-FastShip",
                        label: "NEW - Fast Shipping",
                        detail: "Arrives in less than 1 day",
                        amount: "10.00"
                    }
                ]
            }
        });
    });
    button.load();
</script>
</html>
```

## Classes

<dl>
<dt><a href="#WalletButtons">WalletButtons</a></dt>
<dd><p>Class WalletButtons to work with different E-Wallets within html (currently supports Apple Pay, Google Pay, Google Pay™ and Apple Pay via Stripe, Flypay V2, Paypal, Afterpay)</p>
</dd>
</dl>

## Constants

<dl>
<dt><a href="#EVENT">EVENT</a> : <code>object</code></dt>
<dd><p>List of available event&#39;s name in the wallet button lifecycle</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#IEventData">IEventData</a></dt>
<dd><p>Interface of data from events.</p>
</dd>
<dt><a href="#IWalletPaymentSuccessful">IWalletPaymentSuccessful</a></dt>
<dd><p>Interface of data from a successful payment result.</p>
</dd>
<dt><a href="#IWalletUpdate">IWalletUpdate</a></dt>
<dd><p>Interface of data from an update event.</p>
</dd>
<dt><a href="#IWalletOnClick">IWalletOnClick</a></dt>
<dd><p>Interface of data from a wallet onClick event.</p>
</dd>
<dt><a href="#IWalletUnavailable">IWalletUnavailable</a></dt>
<dd><p>Interface of data from an unavailable event.</p>
</dd>
<dt><a href="#IWalletUpdateData">IWalletUpdateData</a></dt>
<dd><p>Interface of data for wallet button <code>update</code> call.</p>
</dd>
<dt><a href="#IWalletMeta">IWalletMeta</a> : <code>object</code></dt>
<dd><p>Interface of data used by the wallet checkout and payment proccess.</p>
</dd>
<dt><a href="#IApplePayShippingOption">IApplePayShippingOption</a> : <code>object</code></dt>
<dd><p>Interface of Shipping Options for ApplePay</p>
</dd>
<dt><a href="#IGooglePayShippingOption">IGooglePayShippingOption</a> : <code>object</code></dt>
<dd><p>Interface of Shipping Options for GooglePay</p>
</dd>
<dt><a href="#IPayPalShippingOption">IPayPalShippingOption</a> : <code>object</code></dt>
<dd><p>Interface of Shipping Options for PayPal</p>
</dd>
</dl>

<a name="IEventData" id="IEventData" href="#IEventData">&nbsp;</a>

## IEventData
Interface of data from events.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| event | <code>string</code> | 
| data | <code>void</code> \| [<code>IWalletPaymentSuccessful</code>](#IWalletPaymentSuccessful) \| [<code>IWalletUpdate</code>](#IWalletUpdate) \| [<code>IWalletUnavailable</code>](#IWalletUnavailable) \| [<code>IWalletOnClick</code>](#IWalletOnClick) \| <code>any</code> | 

<a name="IWalletPaymentSuccessful" id="IWalletPaymentSuccessful" href="#IWalletPaymentSuccessful">&nbsp;</a>

## IWalletPaymentSuccessful
Interface of data from a successful payment result.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| id | <code>string</code> | 
| amount | <code>number</code> | 
| currency | <code>string</code> | 
| status | <code>string</code> | 
| [payer_name] | <code>string</code> | 
| [payer_email] | <code>string</code> | 
| [payer_phone] | <code>string</code> | 

<a name="IWalletUpdate" id="IWalletUpdate" href="#IWalletUpdate">&nbsp;</a>

## IWalletUpdate
Interface of data from an update event.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| [wallet_response_code] | <code>string</code> | 
| [wallet_session_id] | <code>string</code> | 
| [payment_source] | <code>object</code> | 
| [payment_source.wallet_payment_method_id] | <code>string</code> | 
| [payment_source.card_number_last4] | <code>string</code> | 
| [payment_source.card_scheme] | <code>string</code> | 
| [wallet_loyalty_account] | <code>object</code> | 
| [wallet_loyalty_account.id] | <code>string</code> | 
| [wallet_loyalty_account.barcode] | <code>string</code> | 
| [shipping] | <code>object</code> | 
| [shipping.address_line1] | <code>string</code> | 
| [shipping.address_line2] | <code>string</code> | 
| [shipping.address_postcode] | <code>string</code> | 
| [shipping.address_city] | <code>string</code> | 
| [shipping.address_state] | <code>string</code> | 
| [shipping.address_country] | <code>string</code> | 
| [shipping.address_company] | <code>string</code> | 
| [shipping.post_office_box_number] | <code>string</code> | 
| [shipping.wallet_address_id] | <code>string</code> | 
| [shipping.wallet_address_name] | <code>string</code> | 
| [shipping.wallet_address_created_timestamp] | <code>string</code> | 
| [shipping.wallet_address_updated_timestamp] | <code>string</code> | 

<a name="IWalletOnClick" id="IWalletOnClick" href="#IWalletOnClick">&nbsp;</a>

## IWalletOnClick
Interface of data from a wallet onClick event.

**Kind**: global interface  

| Param | Description |
| --- | --- |
| attachResult | Method to be called that attaches a result to the wallet onClick operation. When handler is synchronous, this method is optionally called with a boolean flag indicating validation result. When handler executes asynchronous operations, this method must be called with the Promise to have the wallet process wait for its completion or rejection. |

<a name="IWalletUnavailable" id="IWalletUnavailable" href="#IWalletUnavailable">&nbsp;</a>

## IWalletUnavailable
Interface of data from an unavailable event.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [wallet] | <code>string</code> | For gateways with more than one wallet button available (e.g: MPGS with ApplePay and GooglePay). Possible values for wallet are 'apple' or 'google'. |
| [type] | <code>string</code> | Event Code. Value can be 'create_order_id_error' on FlypayV2 order creation failure. Optional for [Flypay V2]. N/A for other wallets. |
| [error_code] | <code>string</code> | Event Error Code. Value can be any error code return from Paydock's API. Optional for [Flypay V2]. N/A for other wallets.  + |

<a name="IWalletUpdateData" id="IWalletUpdateData" href="#IWalletUpdateData">&nbsp;</a>

## IWalletUpdateData
Interface of data for wallet button `update` call.

**Kind**: global interface  

| Param | Type |
| --- | --- |
| success | <code>boolean</code> | 

<a name="IWalletMeta" id="IWalletMeta" href="#IWalletMeta">&nbsp;</a>

## IWalletMeta : <code>object</code>
Interface of data used by the wallet checkout and payment proccess.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [amount_label] | <code>string</code> | Label shown next to the total amount to be paid. Required for [Stripe, ApplePay, GooglePay]. N/A for [Flypay V2, PayPal, Afterpay]. |
| [country] | <code>string</code> | Country of the user. 2 letter ISO code format. Required for [Stripe, ApplePay, GooglePay, Afterpay]. N/A for [Flypay V2, PayPal]. |
| [pay_later] | <code>boolean</code> | Used to enable Pay Later feature in PayPal Smart Checkout WalletButton integration when available. Optional for [PayPal]. N/A for other wallets. |
| [hide_message] | <code>boolean</code> | Used to hide Pay Later message in PayPal Smart Checkout WalletButton integration. Optional for [PayPal]. N/A for other wallets. |
| [standalone] | <code>boolean</code> | Used to enable Standalone Buttons feature in PayPal Smart Checkout WalletButton integration. Used together with `pay_later`. Optional for [PayPal]. N/A for other wallets. |
| [show_billing_address] | <code>boolean</code> | Used to hide/show the billing address on ApplePay and GooglePay popups. Default value is false. Optional for [ApplePay, GooglePay]. N/A for other wallets. |
| [request_payer_name] | <code>boolean</code> | Used mainly for fraud purposes - recommended set to true. Optional for [Stripe]. N/A for other wallets. |
| [request_payer_email] | <code>boolean</code> | Used mainly for fraud purposes - recommended set to true. Optional for [Stripe]. N/A for other wallets. |
| [request_payer_phone] | <code>boolean</code> | Used mainly for fraud purposes - recommended set to true. Optional for [Stripe]. N/A for other wallets. |
| [access_token] | <code>string</code> | Used for Flypay V2 express flow. Optional for [Flypay V2]. N/A for other wallets. |
| [refresh_token] | <code>string</code> | Used for Flypay V2 express flow. Optional for [Flypay V2]. N/A for other wallets. |
| [request_shipping] | <code>boolean</code> | Used to request or not shipping address in the Wallet checkout, being able to handle amount changes via the `update` event. Optional for [PayPal, ApplePay, GooglePay]. N/A for [Flypay V2, Stripe, Afterpay]. |
| [shipping_options] | [<code>Array.&lt;IApplePayShippingOption&gt;</code>](#IApplePayShippingOption) \| [<code>Array.&lt;IPayPalShippingOption&gt;</code>](#IPayPalShippingOption) | Used to provide available shipping options.(To use shipping_options the request_shipping flag should be true). Optional for [ApplePay]. N/A for the other wallets. |
| [merchant_name] | <code>string</code> | Merchant Name used for GooglePay integration via MPGS. Required for [GooglePay]. N/A for other wallets. |
| [raw_data_initialization] | <code>object</code> | Used to provide values to initialize wallet with raw data. Optional for [ApplePay]. N/A for the other wallets. |
| [style] | <code>object</code> | For **Paypal**: used to style the buttons, check possible values in the [style guide](https://developer.paypal.com/docs/business/checkout/reference/style-guide). When `standalone` and `pay_later`, extra options can be provided in `style.messages` with the [messages style options](https://developer.paypal.com/docs/checkout/pay-later/us/integrate/reference/#stylelayout). Also used at **ApplePay**, **GooglePay** and **Afterpay** to select button type. Optional for [PayPal, ApplePay, GooglePay, Afterpay]. N/A for [Stripe, Flypay V2]. |
| [style.button_type] | <code>object</code> | Used to select ApplePay button type (e.g: 'buy','donate', etc), check possible values [here](https://developer.apple.com/documentation/apple_pay_on_the_web/displaying_apple_pay_buttons_using_css). Also select button type for GooglePay (check GooglePayStyles) and Afterpay (check AfterpayStyles). Optional for [ApplePay, GooglePay, Afterpay]. N/A for other wallets. |
| [style.button_style] | <code>object</code> | Used to select ApplePay button style (e.g: 'black', 'white', etc), check possible values [here](https://developer.apple.com/documentation/apple_pay_on_the_web/applepaybuttonstyle). Optional for [ApplePay]. N/A for other wallets. |
| [style.height] | <code>object</code> | Used to select Afterpay button height. Optional for [Afterpay]. N/A for other wallets. |
| [wallets] | <code>array</code> | By default if this is not sent or empty, we will try to show either Apple Pay or Google Pay buttons. This can be limited sending the following array in this field: ['apple','google]. Optional for [Stripe, ApplePay, GooglePay]. N/A for other wallets. |
| [client_id] | <code>string</code> | Client ID to be used in the provider system. Required for [Flypay V2]. N/A for [GooglePay, ApplePay, PayPal, Afterpay]. |
| [apple_pay_capabilities] | <code>Array.&lt;(&#x27;credentials\_available&#x27;\|&#x27;credentials\_status\_unknown&#x27;\|&#x27;credentials\_unavailable&#x27;)&gt;</code> | Device capabilities needed for wallet button to be available. For further information about refer to [the documentation](https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/4440085-applepaycapabilities). If the recognized value is credentials_status_unknown, the payment most possibly cannot be finished on the web, and the buyer must complete it on a compatible device, like Iphone, via QR scan. Optional parameter for [ApplePay]. N/A for [GooglePay, Flypay V2, PayPal, Afterpay]. |

<a name="IApplePayShippingOption" id="IApplePayShippingOption" href="#IApplePayShippingOption">&nbsp;</a>

## IApplePayShippingOption : <code>object</code>
Interface of Shipping Options for ApplePay

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [id] | <code>string</code> | Identifier of the Shipping Option. Required. |
| [label] | <code>string</code> | Identifier of the Shipping Option. Required. |
| [amount] | <code>string</code> | Amount of the Shipping Option. Required. |
| [detail] | <code>string</code> | Details of the Shipping Option. Required. |
| [type] | <code>string</code> | Type of the Shipping Option. Values can be 'ELECTRONIC', 'GROUND', 'NOT_SHIPPED', 'OVERNIGHT', 'PICKUP', 'PRIORITY', 'SAME_DAY'. Optional. |

<a name="IGooglePayShippingOption" id="IGooglePayShippingOption" href="#IGooglePayShippingOption">&nbsp;</a>

## IGooglePayShippingOption : <code>object</code>
Interface of Shipping Options for GooglePay

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [id] | <code>string</code> | Identifier of the Shipping Option. Required. |
| [label] | <code>string</code> | Identifier of the Shipping Option. Required. |
| [detail] | <code>string</code> | Details of the Shipping Option. Optional. |
| [type] | <code>string</code> | Type of the Shipping Option. Values can be 'ELECTRONIC', 'GROUND', 'NOT_SHIPPED', 'OVERNIGHT', 'PICKUP', 'PRIORITY', 'SAME_DAY'. Optional. |

<a name="IPayPalShippingOption" id="IPayPalShippingOption" href="#IPayPalShippingOption">&nbsp;</a>

## IPayPalShippingOption : <code>object</code>
Interface of Shipping Options for PayPal

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [id] | <code>string</code> | Identifier of the Shipping Option. Required. |
| [label] | <code>string</code> | Identifier of the Shipping Option. Required. |
| [amount] | <code>string</code> | Amount of the Shipping Option. Required. |
| [currency] | <code>string</code> | Currency of the Shipping Option. Required. |
| [type] | <code>string</code> | Type of the Shipping Option. Values can be 'SHIPPING' or 'PICKUP'. Required. |

<a name="WalletButtons" id="WalletButtons" href="#WalletButtons">&nbsp;</a>

## WalletButtons
Class WalletButtons to work with different E-Wallets within html (currently supports Apple Pay, Google Pay, Google Pay™ and Apple Pay via Stripe, Flypay V2, Paypal, Afterpay)

**Kind**: global class  

* [WalletButtons](#WalletButtons)
    * [new WalletButtons(selector, chargeToken, meta)](#new_WalletButtons_new)
    * [.load()](#WalletButtons+load)
    * [.update()](#WalletButtons+update)
    * [.setEnv(env, [alias])](#WalletButtons+setEnv)
    * [.enable()](#WalletButtons+enable)
    * [.disable()](#WalletButtons+disable)
    * [.close()](#WalletButtons+close)
    * [.on(eventName, [cb])](#WalletButtons+on) ⇒ [<code>Promise.&lt;IEventData&gt;</code>](#IEventData) \| <code>void</code>
    * [.onUnavailable([handler])](#WalletButtons+onUnavailable)
    * [.onUpdate([handler])](#WalletButtons+onUpdate)
    * [.onPaymentSuccessful([handler])](#WalletButtons+onPaymentSuccessful)
    * [.onPaymentInReview([handler])](#WalletButtons+onPaymentInReview)
    * [.onPaymentError([handler])](#WalletButtons+onPaymentError)
    * [.onAuthTokensChanged([handler])](#WalletButtons+onAuthTokensChanged)
    * [.onClick(handler)](#WalletButtons+onClick)
    * [.onCheckoutOpen(handler)](#WalletButtons+onCheckoutOpen)
    * [.onCheckoutClose(handler)](#WalletButtons+onCheckoutClose)

<a name="new_WalletButtons_new" id="new_WalletButtons_new" href="#new_WalletButtons_new">&nbsp;</a>

### new WalletButtons(selector, chargeToken, meta)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | Selector of html element. Container for the WalletButtons. |
| chargeToken | <code>string</code> | token for the wallet transaction, created with a secure call to `POST charges/wallet`. |
| meta | [<code>IWalletMeta</code>](#IWalletMeta) | data that configures the E-Wallet, which can be shown on checkout page and configures required customer information. |

**Example**  
```js
var button = new WalletButtons('#wallet-buttons', 'charge-token', { amount_label: 'Total', country: 'us' });
```
<a name="WalletButtons+load" id="WalletButtons+load" href="#WalletButtons+load">&nbsp;</a>

### walletButtons.load()
Initializes the availability checks and inserts the button if possible.
Otherwise function onUnavailable(handler: VoidFunction) will be called.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  
**Example**  
```js
var button = new WalletButtons(
     '#buttons',
     token,
     {
         amount_label: 'Total',
         country: 'DE',
     }
 );
 button.load();
```
<a name="WalletButtons+update" id="WalletButtons+update" href="#WalletButtons+update">&nbsp;</a>

### walletButtons.update()
Triggers the update process of the wallet, if available.
Currently supported by Paypal and ApplePay/GooglePay via MPGS Wallets.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  
**Example**  
```js
var button = new WalletButtons(
     '#buttons',
     token,
     {
         amount_label: 'Total',
         country: 'DE',
     }
 );
 button.on('update', (data) => {
     updateChargeAmountInBackend(data);
     button.update({ success: true });
 });
```
**Example**  
```js
// ApplePay via MPGS example:
var button = new WalletButtons(
     '#buttons',
     token,
     {
         amount_label: 'Total',
         country: 'AU',
         ...
     }
 );
 button.on('update', (data) => {
     updateChargeAmountInBackend(data);
     button.update({
        success: true,
        body: {
             amount: 15,
             shipping_options: [
                  {
                     id: "NEW-FreeShip",
                      label: "NEW - Free Shipping",
                      detail: "Arrives in 3 to 5 days",
                      amount: "0.00"
                  },
                  {
                      id: "NEW - FastShip",
                      label: "NEW - Fast Shipping",
                      detail: "Arrives in less than 1 day",
                      amount: "10.00"
                  }
              ]
         }
      });
 });
```
<a name="WalletButtons+setEnv" id="WalletButtons+setEnv" href="#WalletButtons+setEnv">&nbsp;</a>

### walletButtons.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com
Bear in mind that you must set an environment before calling `button.load()`.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  
```js
button.setEnv('production', 'paydock.com');
```
<a name="WalletButtons+enable" id="WalletButtons+enable" href="#WalletButtons+enable">&nbsp;</a>

### walletButtons.enable()
Current method can enable the payment button. This method is only supported for Flypay V2.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  
**Example**  
```js
button.enable();
```
<a name="WalletButtons+disable" id="WalletButtons+disable" href="#WalletButtons+disable">&nbsp;</a>

### walletButtons.disable()
Current method can disable the payment button. This method is only supported for Flypay V2.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  
**Example**  
```js
button.disable('production', 'paydock.com');
```
<a name="WalletButtons+close" id="WalletButtons+close" href="#WalletButtons+close">&nbsp;</a>

### walletButtons.close()
Closes the checkout forcibly. Currently supported in Flypay wallet.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  
**Example**  
```js
button.close();
```
<a name="WalletButtons+on" id="WalletButtons+on" href="#WalletButtons+on">&nbsp;</a>

### walletButtons.on(eventName, [cb]) ⇒ [<code>Promise.&lt;IEventData&gt;</code>](#IEventData) \| <code>void</code>
Listen to events of button. `unavailable` returns no data, `paymentSuccessful` returns IWalletPaymentSuccessful
for Stripe or full response for Flypay, and `paymentError` an error.

NOTE: when listening for the 'update' event, make sure to call the `button.update(result)` method on completion.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| eventName | <code>string</code> | Available event names [EVENT](#EVENT) |
| [cb] | <code>listener</code> |  |

**Example**  
```js
button.on('paymentSuccessful', function (data) {
     console.log(data);
});
// or
button.on('unavailable').then(function () {
     console.log('No button is available');
});
```
<a name="WalletButtons+onUnavailable" id="WalletButtons+onUnavailable" href="#WalletButtons+onUnavailable">&nbsp;</a>

### walletButtons.onUnavailable([handler])
User to subscribe to the no button available event. This method is used after loading when the button is not available.
For MPGS, since can have more than one wallet button configured (ApplePay/GooglePay) you will receive a body (({ wallet: WALLET_TYPE.GOOGLE }) or ({ wallet: WALLET_TYPE.APPLE })) indicating which button is unavailable
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | <code>listener</code> | Function to be called when no button is available. |

**Example**  
```js
button.onUnavailable(() => {
     console.log('No wallet buttons available');
});
```
**Example**  
```js
button.onUnavailable().then(() => console.log('No wallet buttons available'));
```
**Example**  
```js
button.onUnavailable(function (data) {console.log('data.wallet :: ', data.wallet)});
```
<a name="WalletButtons+onUpdate" id="WalletButtons+onUpdate" href="#WalletButtons+onUpdate">&nbsp;</a>

### walletButtons.onUpdate([handler])
If the wallet performs some update in the checkout process, the function passed as parameter will be called.

NOTE: make sure to call the `button.update(result)` method on handler completion.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | <code>listener</code> | Function to be called when the payment was successful. |

**Example**  
```js
button.onUpdate((data) => {
     button.update({ success: true });
});
```
**Example**  
```js
button.onUpdate().then((data) => throw new Error());
```
<a name="WalletButtons+onPaymentSuccessful" id="WalletButtons+onPaymentSuccessful" href="#WalletButtons+onPaymentSuccessful">&nbsp;</a>

### walletButtons.onPaymentSuccessful([handler])
If the payment was successful, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | <code>listener</code> | Function to be called when the payment was successful. |

**Example**  
```js
button.onPaymentSuccessful((data) => {
     console.log('Payment successful!');
});
```
**Example**  
```js
button.onPaymentSuccessful().then((data) => console.log('Payment successful!'));
```
<a name="WalletButtons+onPaymentInReview" id="WalletButtons+onPaymentInReview" href="#WalletButtons+onPaymentInReview">&nbsp;</a>

### walletButtons.onPaymentInReview([handler])
If the payment was left in fraud review, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | <code>listener</code> | Function to be called when the payment was left in fraud review status. |

**Example**  
```js
button.onPaymentInReview((data) => {
     console.log('Payment in fraud review');
});
```
**Example**  
```js
button.onPaymentInReview().then((data) => console.log('Payment in fraud review'));
```
<a name="WalletButtons+onPaymentError" id="WalletButtons+onPaymentError" href="#WalletButtons+onPaymentError">&nbsp;</a>

### walletButtons.onPaymentError([handler])
If the payment was not successful, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | <code>listener</code> | Function to be called when the payment was not successful. |

**Example**  
```js
button.onPaymentError((err) => {
     console.log('Payment not successful');
});
```
**Example**  
```js
button.onPaymentError().then((err) => console.log('Payment not successful'));
```
<a name="WalletButtons+onAuthTokensChanged" id="WalletButtons+onAuthTokensChanged" href="#WalletButtons+onAuthTokensChanged">&nbsp;</a>

### walletButtons.onAuthTokensChanged([handler])
Registers a callback function to be invoked when authentication tokens are changed.
This function allows you to respond to changes in authentication tokens, such as when a user logs in.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | <code>listener</code> | Function to be called when authentication tokens are changed. |

**Example**  
```js
button.onAuthTokensChanged((eventData) => {
    console.log('Authentication tokens changed:', eventData);
});
```
**Example**  
```js
button.onAuthTokensChanged().then((eventData) => {
    console.log('Authentication tokens changed:', eventData);
});
```
<a name="WalletButtons+onClick" id="WalletButtons+onClick" href="#WalletButtons+onClick">&nbsp;</a>

### walletButtons.onClick(handler)
Registers a callback function to be invoked when the wallet button gets clicked.
There are two operational modes supported, Synchronous and Asynchronous.
When asynchronous operations need to occur on the callback handler, attaching the Promise via `attachResult` is required to have the wallet wait for a result.
When synchronous operations occur on the callback handler, attaching a boolean result via `attachResult` is optional to control the execution flow.
Note this is supported for Paypal, GooglePay, ApplePay, Afterpay and FlypayV2 wallet buttons at the moment.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>listener</code> | Function to be called when the wallet button is clicked. |

**Example**  
```js
button.onClick((data) => {
     performValidationLogic();
});
```
<a name="WalletButtons+onCheckoutOpen" id="WalletButtons+onCheckoutOpen" href="#WalletButtons+onCheckoutOpen">&nbsp;</a>

### walletButtons.onCheckoutOpen(handler)
Registers a callback function to be invoked when the wallet checkout opens.
Note this is supported for FlypayV2 wallet button at the moment.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>listener</code> | Function to be called when the wallet checkout opens. |

**Example**  
```js
button.onCheckoutOpen((data) => {
     console.log('Checkout opens');
});
```
<a name="WalletButtons+onCheckoutClose" id="WalletButtons+onCheckoutClose" href="#WalletButtons+onCheckoutClose">&nbsp;</a>

### walletButtons.onCheckoutClose(handler)
Registers a callback function to be invoked when the wallet checkout closes.
Note this is supported for FlypayV2 wallet button at the moment.

**Kind**: instance method of [<code>WalletButtons</code>](#WalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>listener</code> | Function to be called when the wallet checkout closes. |

**Example**  
```js
button.onCheckoutClose(() => {
     console.log('Wallet checkout closes');
});
```
<a name="EVENT" id="EVENT" href="#EVENT">&nbsp;</a>

## EVENT : <code>object</code>
List of available event's name in the wallet button lifecycle

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| UNAVAILABLE | <code>string</code> | <code>&quot;unavailable&quot;</code> | 
| UPDATE | <code>string</code> | <code>&quot;update&quot;</code> | 
| PAYMENT_SUCCESSFUL | <code>string</code> | <code>&quot;paymentSuccessful&quot;</code> | 
| PAYMENT_ERROR | <code>string</code> | <code>&quot;paymentError&quot;</code> | 
| ON_CLICK | <code>string</code> | <code>&quot;onClick&quot;</code> | 
| LOADED | <code>string</code> | <code>&quot;onWalletLoaded&quot;</code> | 


## Express Wallet Buttons

Express Wallet Buttons allow to integrate with E-Wallets in an "express" operational mode, allowing to show the respective button in product or cart pages.

The general flow to use the widgets is:
1. Configure your gateway and connect it using Paydock API or Dashboard.
2. Create a container in your site
```html
<div id="widget"></div>
```
3. Initialize the specific WalletButtonExpress, providing your Access Token (preferred) or Public Key, plus required and optional meta parameters for the wallet in use. The general format is:
```js
new paydock.{Provider}WalletButtonExpress(
    "#widget",
    accessTokenOrPublicKey,
    gatewayId,
    gatewaySpecificMeta,
);
```
4. (optional) If the screen where the button is rendered allows for cart/amount changes, call `setMeta` method to update the meta information.
5. Handle the `onClick` callback, where you should call your server, initialize the wallet charge via `POST v1/charges/wallet` and return the wallet token.
6. Handle the `onPaymentSuccessful`, `onPaymentError` and `onPaymentInReview` (if fraud is applicable) for payment results.

### Supported Providers
1. [Apple Pay](#apple-pay-wallet-button-express)
2. [Paypal](#paypal-wallet-button-express)

### Apple Pay Wallet Button Express

A full description of the meta parameters for [ApplePayWalletButtonExpress](#ApplePayWalletButtonExpress) meta parameters can be found [here](#ApplePayWalletMeta). Below you will find a fully working html example.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock ApplePayWalletButtonExpress!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.ApplePayWalletButtonExpress(
        "#widget",
        accessTokenOrPublicKey,
        gatewayId,
        {
            amount_label: 'TOTAL',
            country: 'AU',
            currency: 'AUD',
            amount: 15.5,
            // merchant_capabilities: ['supports3DS', 'supportsEMV', 'supportsCredit', 'supportsDebit'],
            // supported_networks: ['visa', 'masterCard', 'amex', 'chinaUnionPay', 'discover', 'interac', 'jcb', 'privateLabel'],
            // required_billing_contact_fields: ['email', 'name', 'phone', 'postalAddress'], // phone and email do not work according to relevant testing
            // required_shipping_contact_fields: ['email', 'phone'], // Workaround to pull phone and email from shipping contact instead - does not require additional shipping address information
            // supported_countries: ["AU"],
            // style: {
            //     button_type: "buy",
            //     button_style: "black",
            // },
        }
    );

    button.setEnv('sandbox');

    button.onUnavailable(function() {
        console.log("Button not available");
    });

    button.onError(function(error) {
        console.log("On Error Callback", error);
    });

    button.onPaymentSuccessful(function(data) {
        console.log("Payment successful");
        console.log(data);
    });

    button.onPaymentError(function(err) {
        console.log("Payment error");
        console.log(err);
    });

    button.onPaymentInReview(function(data) {
        console.log("The payment is on fraud review");
        console.log(data);
    });

    button.onClick(async (data) => {
        console.log("Button clicked", data);

        const responseData = await fetch('https://your-server-url/initialize-wallet-charge');
        const parsedData = await responseData.json();
        return parsedData.resource.data.token;
    });

    button.onCheckoutClose(() => {
        console.log("Checkout closed");
    });

    button.load();
</script>
</html>
```

### Apple Pay Wallet Button Express with Shipping

A full description of the meta parameters for [ApplePayWalletButtonExpress](#ApplePayWalletButtonExpress) meta parameters can be found [here](#ApplePayWalletMeta). Below you will find a fully working html example.

```html
<html>
<head>
    <title>Apple Pay Express test page</title>
    <style>
        #inputModal {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
        }
        #inputBox {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background: white;
            border-radius: 5px;
            box-shadow: 2px 2px 10px rgba(0,0,0,0.5);
        }
    </style>
</head>
<body>
    <table id='paymentTable'>
        <tr>
            <td>Environment:</td>
            <td>
                <select id="environment" name="environment">
                    <option value="sandbox">Sandbox</option>
                    <option value="local">Local</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>Access Token / Public Key:</td>
            <td><input type="text" name="access" id="access" /></td>
        </tr>
        <tr>
            <td>Secret Key:</td>
            <td><input type="text" name="secretKey" id="secretKey" /></td>
        </tr>
        <tr>
            <td>Gateway Id:</td>
            <td><input type="text" name="gateway" id="gateway" /></td>
        </tr>
        <tr>
            <td>Wallet Charge - for apple pay we need to add it here because the apple pay popup does not allow us to
                inject it there but it will be used only on click. So is optional, if not provided it simulates an error
                when creating B2B wallet charge on click:</td>
            <td><input type="text" name="token" id="token" /></td>
        </tr>
        <tr>
            <td>Charge id - Used to update the charge with the shipping data/shipping options</td>
            <td><input type="text" name="chargeId" id="chargeId" /></td>
        </tr>
        <tr>
            <td>Meta:</td>
            <td><textarea id="meta" name="meta" rows="4" cols="50"></textarea></td>
        </tr>
    </table>
    <div id="button">
        <input type="submit" name="event" value="Send" class="button" onclick="return loadButtons()" />
    </div>
    <div id="widget"></div>
</body>

<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script>
<script type=text/javascript>
    // Environment enum with API URLs
    const ENVIRONMENTS = {
        PRODUCTION: {
            name: 'production',
            apiUrl: 'https://api.paydock.com'
        },
        SANDBOX: {
            name: 'sandbox',
            apiUrl: 'https://api-sandox.paydock.com'
        }
    };

    // Function to get API URL based on selected environment
    function getApiUrl(environmentName) {
        const env = Object.values(ENVIRONMENTS).find(env => env.name === environmentName);
        return env ? env.apiUrl : ENVIRONMENTS.SANDBOX.apiUrl;
    }

    // Function to get current base URL from selected environment
    function getBaseUrl() {
        const selectedEnvironment = document.getElementById("environment").value;
        return getApiUrl(selectedEnvironment);
    }

    async function updateCharge(secretKey, chargeId, updateData) {
        try {
            const baseUrl = getBaseUrl();
            const response = await fetch(`${baseUrl}/v1/charges/wallet/${chargeId}`, {
                method: 'PUT',
                headers: {
                    'x-user-secret-key': secretKey,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(updateData),
            });
            const data = await response.json();
            console.log('Update charge response:', data);
            return data;
        } catch (error) {
            console.error('Error updating charge:', error);
        }
    };

    const shippingOptions = [
            {
                label: "Test 1",
                detail: "This is a test 1 shipping methods",
                amount: 10,
                id: "randomId1",
                date_components_range: {
                    start_date_components: {
                        years: 0,
                        months: 0,
                        days: 5,
                        hours: 0,
                    },
                    end_date_components: {
                        years: 0,
                        months: 0,
                        days: 10,
                        hours: 0,
                    }
                }
            },
            {
                label: "Test 2",
                detail: "This is a test 2 shipping methods",
                amount: 14,
                id: "randomId2",
                date_components_range: {
                    start_date_components: {
                        years: 0,
                        months: 0,
                        days: 6,
                        hours: 0,
                    },
                    end_date_components: {
                        years: 0,
                        months: 0,
                        days: 12,
                        hours: 0,
                    },
                },
            },
        ];

    function loadButtons() {
        const secretKey = document.getElementById("secretKey").value;
        if (!secretKey) {
            alert("Please enter the secret key.");
            return false;
        }

        let button = new paydock.ApplePayWalletButtonExpress(
            "#widget",
            document.getElementById("access").value,
            document.getElementById("gateway").value,
            JSON.parse(document.getElementById("meta").value),
        );

        button.setEnv(document.getElementById("environment").value);

        let charge_id;

        button.onClick(async (data) => {
            const { token, chargeId } = await getUserInput();
            charge_id = chargeId;
            return token;
        });

        const amount = JSON.parse(document.getElementById('meta').value).amount;

        button.onUnavailable(function() {
            console.log("Button unavailable");
        });
        button.onError(function(error) {
            console.log("On Error Callback", error);
        });
        button.onPaymentSuccessful(function(data) {
            console.log("Payment successful");
            console.log(data);
        });
        button.onPaymentError(function(err) {
            console.log("Payment error");
            console.log(err);
        });
        button.onPaymentInReview(function(data) {
            console.log("The payment is on fraud review");
            console.log(data);
        });
        button.onCheckoutClose(() => {
            console.log("Checkout closed");
        });

        button.onShippingAddressChange(async function(data) {
            console.log("Shipping address has been updated", data);

            const defaultOption = shippingOptions[0];

            const updateData = {
                shipping: {
                    ...data.data,
                    amount: defaultOption.amount,
                    method: defaultOption.id,
                    options: shippingOptions,
                },
                amount: amount + defaultOption.amount
            };

            const res = await updateCharge(secretKey, charge_id, updateData);
            return { token: res.resource.data.token };
        });

        button.onShippingOptionsChange(async function(data) {
            console.log("Shipping options have been updated", JSON.stringify(data, null, 2));

            const updateData = {
                shipping: {
                    method: data.data.shipping_option_id,
                    amount: data.data.amount,
                },
                amount: amount + Number(data.data.amount)
            };

            const res = await updateCharge(secretKey, charge_id, updateData);
            return { token: res.resource.data.token };
        });

        button.load()

        document.getElementById("paymentTable").style.display = "none";
        document.getElementById("button").style.display = "none";
        return true;
    }

    function getUserInput(message) {
        return new Promise((resolve, reject) => {
            console.log("Simulating B2B call to generate token...");
            setTimeout(() => {
                const token = document.getElementById("token").value;
                const chargeId = document.getElementById("chargeId").value;
                if (token && chargeId)
                    return resolve({ token, chargeId });
                return reject("No token or Charge Id provided");
            }, 2000);
        });
    }

    document.addEventListener('DOMContentLoaded', () => {
        // Function to get the value of a query parameter by name
        function getQueryParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // Function to set input values from URL parameters
        function setInputValues() {
            const meta = {
                apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
                amount_label: 'TOTAL',
                country: 'AU',
                currency: 'AUD',
                amount: 10,
                shipping_editing_mode: 'available', // available, store_pickup
                required_shipping_contact_fields: [
                    'postalAddress',
                    'name',
                    'phone',
                    'email',
                ],
                shipping: {
                    amount: 5,
                    address_line1: "Address Line 1",
                    address_city: "Test Locality",
                    address_state: "NSW",
                    address_country: "Australia",
                    address_country_code: "AU",
                    address_postcode: "3000",
                    contact: {
                        phone: "+61400245562",
                        email: "qa.notifications+appleid@paydock.com",
                        first_name: "QA",
                        last_name: "QA",
                    },
                    options: shippingOptions,
                },
                // merchant_capabilities: ['supports3DS', 'supportsEMV', 'supportsCredit', 'supportsDebit'],
                // supported_networks: ['visa', 'masterCard', 'amex', 'chinaUnionPay', 'discover', 'interac', 'jcb', 'privateLabel'],
                // required_billing_contact_fields: ['email', 'name', 'phone', 'postalAddress', 'phoneticName'],
                // required_shipping_contact_fields: ['email', 'phone' /*, 'name', 'postalAddress', 'phoneticName'*/],
                // supported_countries: [],
                // style: {
                //     button_type: 'continue',
                //     button_style: 'white',
                // },
            };
            document.getElementById('meta').value = JSON.stringify(meta, null, 2);
        }

        setInputValues();
    });
</script>
</html>
```

When supporting shipping, the method `onShippingAddressChange` and `onShippingOptionsChange` are required to update the shipping address and options.

```javascript
button.onShippingAddressChange(async function(data) {
    console.log("Shipping address has been updated", data);

    const updateData = {
        shipping: {
            ...data.data,
            amount: defaultOption.amount,
            method: defaultOption.id,
            options: shippingOptions,
        },
        amount: amount + defaultOption.amount
    };

    const res = await updateCharge(secretKey, charge_id, updateData);
    return { token: res.resource.data.token };
});

button.onShippingOptionsChange(async function(data) {
    console.log("Shipping options have been updated", data);

    const updateData = {
        shipping: {
            method: data.data.shipping_option_id,
            amount: data.data.amount,
        },
        amount: amount + Number(data.data.amount)
    };

    const res = await updateCharge(secretKey, charge_id, updateData);
    return { token: res.resource.data.token };
});
```

The `updateCharge` method is a custom method to update the charge with the shipping data/shipping options. It is not part of the Paydock SDK and it should use the Paydock's public API to update the charge from the merchant's server.

### Supported Cases
#### Injected Shipping Address, non-editable by the customer

This is the case where the shipping address is injected by the merchant and is not editable by the customer. The customer can only select the shipping option.

The required meta parameters for this case are:
- shipping_editing_mode: 'store_pickup'
- required_shipping_contact_fields: ['postalAddress'] <-- At least one of the fields is required so the shipping address is shown at Apple Pay.

```javascript
meta: {
    apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    amount_label: 'TOTAL',
    country: 'AU',
    currency: 'AUD',
    amount: 10,
    shipping_editing_mode: 'store_pickup',
    required_shipping_contact_fields: [
        'postalAddress', // At least one of the fields is required so the shipping address is shown at Apple Pay.
        'name',
        'phone',
        'email',
    ],
    shipping: {
        amount: 5,
        address_line1: "Address Line 1",
        address_city: "Test Locality",
        address_state: "NSW",
        address_country: "Australia",
        address_country_code: "AU",
        address_postcode: "3000",
        contact: {
            phone: "+61400245562",
            email: "qa.notifications+appleid@paydock.com",
            first_name: "QA",
            last_name: "QA",
        },
        options: [
            {
                label: "Test 1",
                detail: "This is a test 1 shipping methods",
                amount: 10,
                id: "randomId1",
                date_components_range: {
                    start_date_components: {
                        years: 0,
                        months: 0,
                        days: 5,
                        hours: 0,
                    },
                    end_date_components: {
                        years: 0,
                        months: 0,
                        days: 10,
                        hours: 0,
                    }
                }
            }
        ],
    },
}
```

This is the case where the shipping address is injected by the merchant and is editable by the customer. The customer can edit the shipping address and select the shipping option.

The required meta parameters for this case are:
- shipping_editing_mode: 'available'
- required_shipping_contact_fields: ['postalAddress'] <-- At least one of the fields is required so the shipping address is shown at Apple Pay.

```javascript
meta: {
    apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    amount_label: 'TOTAL',
    country: 'AU',
    currency: 'AUD',
    amount: 10,
    shipping_editing_mode: 'available',
    required_shipping_contact_fields: [
        'postalAddress', // At least one of the fields is required so the shipping address is shown at Apple Pay.
        'name',
        'phone',
        'email',
    ],
    shipping: {
        amount: 5,
        address_line1: "Address Line 1",
        address_city: "Test Locality",
        address_state: "NSW",
        address_country: "Australia",
        address_country_code: "AU",
        address_postcode: "3000",
        contact: {
            phone: "+61400245562",
            email: "qa.notifications+appleid@paydock.com",
            first_name: "QA",
            last_name: "QA",
        },
        options: [
            {
                label: "Test 1",
                detail: "This is a test 1 shipping methods",
                amount: 10,
                id: "randomId1",
                date_components_range: {
                    start_date_components: {
                        years: 0,
                        months: 0,
                        days: 5,
                        hours: 0,
                    },
                    end_date_components: {
                        years: 0,
                        months: 0,
                        days: 10,
                        hours: 0,
                    }
                }
            }
        ],
    },
}
```

#### Shipping address editable by the customer

This is the case where the shipping address is not injected by the merchant and is editable by the customer. The customer can edit the shipping address and select the shipping option.

The required meta parameters for this case are:
- shipping_editing_mode: 'available'
- required_shipping_contact_fields: ['postalAddress'] <-- At least one of the fields is required so the shipping address is shown at Apple Pay.

```javascript
meta: {
    apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    amount_label: 'TOTAL',
    country: 'AU',
    currency: 'AUD',
    amount: 10,
    shipping_editing_mode: 'available',
    required_shipping_contact_fields: [
        'postalAddress', // At least one of the fields is required so the shipping address is shown at Apple Pay.
        'name',
        'phone',
        'email',
    ],
}
```

When the the customer selects an address, the `onShippingAddressChange` method is called with the shipping address data. If the merchant wants to update the charge with the shipping address, it should update the charge using Paydock's public API Update Charge method with the shipping address data.

It can include the shipping options in the update data, that will be used to show the shipping options in the Apple Pay popup.

```javascript
button.onShippingAddressChange(async function(data) {
    console.log("Shipping address has been updated", data);

    const updateData = {
        shipping: {
            ...data.data,
            amount: defaultOption.amount,
            method: defaultOption.id,
            options: shippingOptions,
        },
        amount: amount + defaultOption.amount
    };
});
```

#### No shipping address

This is the case where no shipping address is required at all in the popup (e.g., digital goods, services, or virtual products, or Shipping Address collected separately by the merchant). The "Send to" UI field will not be shown in the Apple Pay sheet, it will be hidden.

**Important:**
- No shipping address should be provided in the meta object.
- Shipping address could be provided in the initial POST `/v1/charges/wallet` endpoint, if collected previously.

The required meta parameters for this case are:
- `required_shipping_contact_fields`: Only include contact fields if needed (phone, email), but NOT `postalAddress`.

```javascript
meta:  {
  "amount_label": "TOTAL",
  "country": "AU",
  "currency": "AUD",
  "amount": 10,
  "shipping_editing_mode": "available",
  "required_shipping_contact_fields": ["phone", "email"],
  "apple_pay_capabilities": ["credentials_available", "credentials_status_unknown", "credentials_unavailable"]
}
```

### Paypal Wallet Button Express
A full description of the meta parameters for [PaypalWalletButtonExpress](#PaypalWalletButtonExpress) meta parameters can be found [here](#PaypalWalletMeta). Below you will find a fully working html example.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Payment using PayDock PaypalWalletButtonExpress!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.PaypalWalletButtonExpress(
        "#widget",
        accessTokenOrPublicKey,
        gatewayId,
        {
            amount: 15.5,
            currency: 'AUD',
            pay_later: false,
            standalone: false,
            capture: true,
            // style: {
            //     layout: 'horizontal', // or 'vertical'
            //     color: 'gold', // or 'blue', 'silver', 'black', 'white'
            //     shape: 'rect', // or 'pill', 'sharp'
            //     borderRadius: 5,
            //     height: 40,
            //     disableMaxWidth: false,
            //     label: 'paypal', // or 'checkout', 'buynow', 'pay', 'installment'
            //     tagline: true,
            //     messages: {
            //         layout: 'text', // or 'flex'
            //         logo: {
            //             type: 'primary', // or 'alternative', 'inline', 'none'
            //             position: 'left', // or 'right', 'top'
            //         },
            //         text: {
            //             color: 'black', // or 'white', 'monochrome', 'grayscale'
            //             size: 10, // or 11, 12, 13, 14, 15, 16
            //             align: 'left', // or 'center', 'right'
            //         },
            //         color: 'blue', // or 'black', 'white', 'white-no-border', 'gray', 'monochrome', 'grayscale'
            //         ratio: '1x1', // or '1x4', '8x1', '20x1'
            //     },
            // }
        }
    );

    button.setEnv('sandbox');

    button.onUnavailable(function() {
        console.log("Button not available");
    });

    button.onError(function(error) {
        console.log("On Error Callback", error);
    });

    button.onPaymentSuccessful(function(data) {
        console.log("Payment successful");
        console.log(data);
    });

    button.onPaymentError(function(err) {
        console.log("Payment error");
        console.log(err);
    });

    button.onPaymentInReview(function(data) {
        console.log("The payment is on fraud review");
        console.log(data);
    });

    button.onClick(async (data) => {
        console.log("Button clicked", data);

        const responseData = await fetch('https://your-server-url/initialize-wallet-charge');
        const parsedData = await responseData.json();
        return parsedData.resource.data.token;
    });

    button.onCheckoutClose(() => {
        console.log("Checkout closed");
    });

    button.load();
</script>
</html>
```

## Classes

<dl>
<dt><a href="#ApplePayWalletButtonExpress">ApplePayWalletButtonExpress</a> ⇐ <code>BaseWalletButton</code></dt>
<dd><p>Class ApplePayWalletButtonExpress to work with Apple Pay Wallet.</p>
</dd>
<dt><a href="#PaypalWalletButtonExpress">PaypalWalletButtonExpress</a> ⇐ <code>BaseWalletButton</code></dt>
<dd><p>Class PaypalWalletButtonExpress to work with Paypal Wallet.</p>
</dd>
</dl>

## Constants

<dl>
<dt><a href="#EVENT">EVENT</a> : <code>object</code></dt>
<dd><p>List of available event&#39;s name in the wallet button lifecycle</p>
</dd>
<dt><a href="#ContactFieldType">ContactFieldType</a> : <code>object</code></dt>
<dd><p>List of available contact fields for ContactFieldType</p>
</dd>
</dl>

## Typedefs

<dl>
<dt><a href="#OnClickCallback">OnClickCallback</a> ⇒ <code>Promise.&lt;string&gt;</code></dt>
<dd><p>Callback for onClick method.</p>
</dd>
<dt><a href="#OnPaymentSuccessfulCallback">OnPaymentSuccessfulCallback</a> : <code>function</code></dt>
<dd><p>Callback for onPaymentSuccessful method.</p>
</dd>
<dt><a href="#OnPaymentInReviewCallback">OnPaymentInReviewCallback</a> : <code>function</code></dt>
<dd><p>Callback for onPaymentInReview method.</p>
</dd>
<dt><a href="#OnPaymentErrorCallback">OnPaymentErrorCallback</a> : <code>function</code></dt>
<dd><p>Callback for onPaymentError method.</p>
</dd>
<dt><a href="#OnCheckoutCloseCallback">OnCheckoutCloseCallback</a> : <code>function</code></dt>
<dd><p>Callback for onCheckoutClose method.</p>
</dd>
<dt><a href="#OnShippingAddressChangeCallback">OnShippingAddressChangeCallback</a> ⇒ <code><a href="#OnShippingAddressChangeEventResponse">Promise.&lt;OnShippingAddressChangeEventResponse&gt;</a></code></dt>
<dd><p>Callback for onShippingAddressChange method.</p>
</dd>
<dt><a href="#OnShippingOptionsChangeCallback">OnShippingOptionsChangeCallback</a> ⇒ <code><a href="#OnShippingOptionChangeEventResponse">Promise.&lt;OnShippingOptionChangeEventResponse&gt;</a></code></dt>
<dd><p>Callback for onShippingOptionsChange method.</p>
</dd>
<dt><a href="#OnUnavailableCallback">OnUnavailableCallback</a> : <code>function</code></dt>
<dd><p>Callback for onUnavailable method.</p>
</dd>
<dt><a href="#OnErrorCallback">OnErrorCallback</a> : <code>function</code></dt>
<dd><p>Callback for onError method.</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#ApplePayWalletMeta">ApplePayWalletMeta</a> : <code>object</code></dt>
<dd><p>Interface for configuration metadata specific to ApplePay integration in the wallet checkout and payment process.
For further information about ApplePay Capabilities refer to <a href="https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/4440085-applepaycapabilities">the documentation</a>.
Apple will determinate if the device has an ApplePay wallet available and at least one active payment.
If the determinated value is credentials_status_unknown, the payment possbily should might be not able to be finished on the web, and the buyer must complete it on a compatible device, like Iphone or Ipad.</p>
</dd>
<dt><a href="#PaypalWalletMeta">PaypalWalletMeta</a> : <code>object</code></dt>
<dd><p>Interface for configuration metadata specific to PayPal integration in the wallet checkout and payment process.
For in-depth information, please refer to the <a href="https://developer.paypal.com/docs/multiparty/checkout/standard/customize/buttons-style-guide/">Paypal documentation</a>.</p>
</dd>
<dt><a href="#OnClickEventData">OnClickEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnClickEventData</p>
</dd>
<dt><a href="#OnCloseEventData">OnCloseEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnCloseEventData</p>
</dd>
<dt><a href="#OnPaymentSuccessfulEventData">OnPaymentSuccessfulEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnPaymentSuccessfulEventData. For final secure results, fetch backend to backend data.</p>
</dd>
<dt><a href="#OnPaymentInReviewEventData">OnPaymentInReviewEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnPaymentInReviewEventData. For final secure results, fetch backend to backend data.</p>
</dd>
<dt><a href="#OnPaymentErrorEventData">OnPaymentErrorEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnPaymentErrorEventData. For final secure results, fetch backend to backend data.</p>
</dd>
<dt><a href="#OnUnavailableEventData">OnUnavailableEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnUnavailableEventData</p>
</dd>
<dt><a href="#OnErrorEventData">OnErrorEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnErrorEventData</p>
</dd>
<dt><a href="#OnShippingAddressChangeEventData">OnShippingAddressChangeEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingAddressChangeEventData.</p>
</dd>
<dt><a href="#OnShippingAddressChangeEventResponse">OnShippingAddressChangeEventResponse</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingAddressChangeEventResponse.</p>
</dd>
<dt><a href="#IApplePayShippingOption">IApplePayShippingOption</a> : <code>object</code></dt>
<dd><p>Interface for IApplePayShippingOption.
Used for adding new shippings options when customer updates the shipping address.</p>
</dd>
<dt><a href="#OnShippingOptionChangeEventData">OnShippingOptionChangeEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingOptionChangeEventData.</p>
</dd>
<dt><a href="#OnShippingOptionChangeEventResponse">OnShippingOptionChangeEventResponse</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingOptionChangeEventResponse.</p>
</dd>
<dt><a href="#IApplePayError">IApplePayError</a> : <code>object</code></dt>
<dd><p>Interface for IApplePayError.</p>
</dd>
</dl>

<a name="ApplePayWalletMeta" id="ApplePayWalletMeta" href="#ApplePayWalletMeta">&nbsp;</a>

## ApplePayWalletMeta : <code>object</code>
Interface for configuration metadata specific to ApplePay integration in the wallet checkout and payment process.
For further information about ApplePay Capabilities refer to [the documentation](https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/4440085-applepaycapabilities).
Apple will determinate if the device has an ApplePay wallet available and at least one active payment.
If the determinated value is credentials_status_unknown, the payment possbily should might be not able to be finished on the web, and the buyer must complete it on a compatible device, like Iphone or Ipad.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| amount_label | <code>string</code> | Label shown next to the total amount to be paid, used in ApplePay popups. |
| country | <code>string</code> | Country of the user in 2 letter ISO code format, required for ApplePay. |
| currency | <code>string</code> | Currency of the transaction. ISO 4217 currency code format. |
| amount | <code>number</code> | Total transaction amount number. **Note:** this amount will be presented in the payment sheet regardless of amount sent in the Wallet Initialization Backend to Backend call. Use `setMeta` method to keep it up to date. |
| [merchant_capabilities] | <code>Array.&lt;(&#x27;supports3DS&#x27;\|&#x27;supportsEMV&#x27;\|&#x27;supportsCredit&#x27;\|&#x27;supportsDebit&#x27;)&gt;</code> | Array of capabilities that the merchant supports, influencing the transaction processing features available. |
| [supported_networks] | <code>Array.&lt;(&#x27;visa&#x27;\|&#x27;masterCard&#x27;\|&#x27;amex&#x27;\|&#x27;chinaUnionPay&#x27;\|&#x27;discover&#x27;\|&#x27;interac&#x27;\|&#x27;jcb&#x27;\|&#x27;privateLabel&#x27;)&gt;</code> | List of payment networks supported by the merchant for ApplePay transactions. |
| [required_billing_contact_fields] | <code>Array.&lt;(&#x27;email&#x27;\|&#x27;name&#x27;\|&#x27;phone&#x27;\|&#x27;postalAddress&#x27;)&gt;</code> | Contact fields required from the user for billing purposes, improving transaction verification and fraud prevention. Phone and email are currently not returned by Apple. |
| [required_shipping_contact_fields] | <code>Array.&lt;(&#x27;email&#x27;\|&#x27;phone&#x27;\|&#x27;postalAddress&#x27;)&gt;</code> | Shipping contact fields that are mandatory to complete the transaction. Use email and phone to collect from customer wallet in the abscense of billing one. Include 'postalAddress' to show shipping address fields collection in the Apple Pay sheet. Required handling of onShippingAddressChange callback. |
| [supported_countries] | <code>Array.&lt;string&gt;</code> | List of countries where ApplePay is supported by the merchant, restricting usage to specified regions. |
| [style] | <code>object</code> | Styling configuration for ApplePay buttons displayed during checkout. |
| [style.button_type] | <code>ApplePayButtonType</code> | Enum type to select the type of ApplePay button (e.g., 'buy', 'donate', etc.), providing user interface customization. |
| [style.button_style] | <code>ApplePayButtonStyle</code> | Style applied to the ApplePay button, which can include color and form factor adjustments according to the brand's visual guidelines. |
| [shipping_editing_mode] | <code>&#x27;available&#x27;</code> \| <code>&#x27;store\_pickup&#x27;</code> | ApplePay - available for allowing editing shipping, store_pickup for not allowing editing shipping. |
| [shipping_data] | <code>object</code> | ApplePay - Preloaded data used for populate shipping address information |
| [shipping_data.email_address] | <code>string</code> | ApplePay - The shipping address email |
| [apple_pay_capabilities] | <code>Array.&lt;(&#x27;credentials\_available&#x27;\|&#x27;credentials\_status\_unknown&#x27;\|&#x27;credentials\_unavailable&#x27;)&gt;</code> | Device capabilities needed for wallet button to be available. |

<a name="PaypalWalletMeta" id="PaypalWalletMeta" href="#PaypalWalletMeta">&nbsp;</a>

## PaypalWalletMeta : <code>object</code>
Interface for configuration metadata specific to PayPal integration in the wallet checkout and payment process.
For in-depth information, please refer to the [Paypal documentation](https://developer.paypal.com/docs/multiparty/checkout/standard/customize/buttons-style-guide/).

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| amount | <code>number</code> | Total amount of the transaction. Represents the money to be charged. |
| currency | <code>string</code> | Currency of the transaction in ISO 4217 currency code format. |
| [pay_later] | <code>boolean</code> | Flag to enable Pay Later feature of PayPal, allowing Pay in 4. Default false. |
| [hide_message] | <code>boolean</code> | Used to hide Pay Later message in PayPal Smart Checkout WalletButton integration. Optional for [PayPal]. N/A for other wallets. |
| [standalone] | <code>boolean</code> | Flag to specify if the PayPal standalone button should be used. Default false. |
| [capture] | <code>boolean</code> | Flag to specify if the transaction amount should be captured immediately or authorized for later capture. Default false. |
| [style] | <code>object</code> | Styling configurations for the PayPal widget. |
| [style.layout] | <code>&#x27;vertical&#x27;</code> \| <code>&#x27;horizontal&#x27;</code> | Layout orientation of the PayPal button. |
| [style.color] | <code>&#x27;gold&#x27;</code> \| <code>&#x27;blue&#x27;</code> \| <code>&#x27;silver&#x27;</code> \| <code>&#x27;black&#x27;</code> \| <code>&#x27;white&#x27;</code> | Color theme of the PayPal button. |
| [style.shape] | <code>&#x27;rect&#x27;</code> \| <code>&#x27;pill&#x27;</code> \| <code>&#x27;sharp&#x27;</code> | Shape of the PayPal button. |
| [style.borderRadius] | <code>number</code> | Border radius for the button, allowing customization of corner roundness. |
| [style.height] | <code>number</code> | Height of the PayPal button, allowing for size customization. |
| [style.disableMaxWidth] | <code>boolean</code> | Flag to disable the maximum width constraint of the button. |
| [style.label] | <code>&#x27;paypal&#x27;</code> \| <code>&#x27;checkout&#x27;</code> \| <code>&#x27;buynow&#x27;</code> \| <code>&#x27;pay&#x27;</code> \| <code>&#x27;installment&#x27;</code> | Label text displayed on the PayPal button. |
| [style.tagline] | <code>boolean</code> | Flag to include or exclude a tagline beneath the button text. |
| [style.messages] | <code>object</code> | Messaging options related to the PayPal button to enhance user interaction. |
| [style.messages.layout] | <code>&#x27;text&#x27;</code> \| <code>&#x27;flex&#x27;</code> | Layout type for the messages displayed near the PayPal button. |
| [style.messages.logo] | <code>object</code> | Configuration for the logo to be displayed with the PayPal button. |
| [style.messages.logo.type] | <code>&#x27;primary&#x27;</code> \| <code>&#x27;alternative&#x27;</code> \| <code>&#x27;inline&#x27;</code> \| <code>&#x27;none&#x27;</code> | Type of logo to display. |
| [style.messages.logo.position] | <code>&#x27;left&#x27;</code> \| <code>&#x27;right&#x27;</code> \| <code>&#x27;top&#x27;</code> | Position of the logo relative to the button or message. |
| [style.messages.text] | <code>object</code> | Text styling within the message component. |
| [style.messages.text.color] | <code>&#x27;black&#x27;</code> \| <code>&#x27;white&#x27;</code> \| <code>&#x27;monochrome&#x27;</code> \| <code>&#x27;grayscale&#x27;</code> | Color of the message text. |
| [style.messages.text.size] | <code>10</code> \| <code>11</code> \| <code>12</code> \| <code>13</code> \| <code>14</code> \| <code>15</code> \| <code>16</code> | Font size of the message text. |
| [style.messages.text.align] | <code>&#x27;left&#x27;</code> \| <code>&#x27;center&#x27;</code> \| <code>&#x27;right&#x27;</code> | Text alignment within the message area. |
| [style.messages.color] | <code>&#x27;blue&#x27;</code> \| <code>&#x27;black&#x27;</code> \| <code>&#x27;white&#x27;</code> \| <code>&#x27;white-no-border&#x27;</code> \| <code>&#x27;gray&#x27;</code> \| <code>&#x27;monochrome&#x27;</code> \| <code>&#x27;grayscale&#x27;</code> | Background color of the message area. |
| [style.messages.ratio] | <code>&#x27;1x1&#x27;</code> \| <code>&#x27;1x4&#x27;</code> \| <code>&#x27;8x1&#x27;</code> \| <code>&#x27;20x1&#x27;</code> | Aspect ratio of the message area, affecting its layout and display. |

<a name="OnClickEventData" id="OnClickEventData" href="#OnClickEventData">&nbsp;</a>

## OnClickEventData : <code>object</code>
Interface for OnClickEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'onClick' |

<a name="OnCloseEventData" id="OnCloseEventData" href="#OnCloseEventData">&nbsp;</a>

## OnCloseEventData : <code>object</code>
Interface for OnCloseEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'onCheckoutClose' |
| [chargeId] | <code>string</code> | chargeId in case it's already set after onClick event |

<a name="OnPaymentSuccessfulEventData" id="OnPaymentSuccessfulEventData" href="#OnPaymentSuccessfulEventData">&nbsp;</a>

## OnPaymentSuccessfulEventData : <code>object</code>
Interface for OnPaymentSuccessfulEventData. For final secure results, fetch backend to backend data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'paymentSuccessful' |
| chargeId | <code>string</code> | chargeId set after onClick event |
| data.id | <code>string</code> | Charge ID returned by server |
| data.amount | <code>string</code> | Charge amount returned by server |
| data.currency | <code>string</code> | Charge currency returned by server |
| data.status | <code>string</code> | Charge status returned by server |

<a name="OnPaymentInReviewEventData" id="OnPaymentInReviewEventData" href="#OnPaymentInReviewEventData">&nbsp;</a>

## OnPaymentInReviewEventData : <code>object</code>
Interface for OnPaymentInReviewEventData. For final secure results, fetch backend to backend data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'paymentInReview' |
| chargeId | <code>string</code> | chargeId set after onClick event |
| data.id | <code>string</code> | Charge ID returned by server |
| data.amount | <code>string</code> | Charge amount returned by server |
| data.currency | <code>string</code> | Charge currency returned by server |
| data.status | <code>string</code> | Charge status returned by server |

<a name="OnPaymentErrorEventData" id="OnPaymentErrorEventData" href="#OnPaymentErrorEventData">&nbsp;</a>

## OnPaymentErrorEventData : <code>object</code>
Interface for OnPaymentErrorEventData. For final secure results, fetch backend to backend data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'paymentError' |
| chargeId | <code>string</code> | chargeId set after onClick event |
| [data.message] | <code>string</code> | Error message |
| [data.code] | <code>string</code> | Error code |

<a name="OnUnavailableEventData" id="OnUnavailableEventData" href="#OnUnavailableEventData">&nbsp;</a>

## OnUnavailableEventData : <code>object</code>
Interface for OnUnavailableEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'unavailable' |

<a name="OnErrorEventData" id="OnErrorEventData" href="#OnErrorEventData">&nbsp;</a>

## OnErrorEventData : <code>object</code>
Interface for OnErrorEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'error' |
| [chargeId] | <code>string</code> | chargeId in case it's already set after onClick event |
| [data] | <code>Error</code> | Error object if present |

<a name="OnShippingAddressChangeEventData" id="OnShippingAddressChangeEventData" href="#OnShippingAddressChangeEventData">&nbsp;</a>

## OnShippingAddressChangeEventData : <code>object</code>
Interface for OnShippingAddressChangeEventData.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'onShippingAddressChange' |
| chargeId | <code>string</code> | chargeId set after onClick event |
| data.address_city | <code>string</code> | PayPal and ApplePay - Shipping address city |
| data.address_state | <code>string</code> | PayPal and ApplePay - Shipping address state |
| data.address_postcode | <code>string</code> | PayPal and ApplePay - Shipping address postcode |
| data.address_country | <code>string</code> | PayPal and ApplePay - Shipping address country code |
| [data.address_line1] | <code>string</code> | ApplePay - Shipping address line 1 |
| [data.address_line2] | <code>string</code> | ApplePay - Shipping address line 2 |
| [data.contact.phone] | <code>string</code> | ApplePay - Shipping contact phone |
| [data.contact.email] | <code>string</code> | ApplePay - Shipping contact email |
| [data.contact.first_name] | <code>string</code> | ApplePay - Shipping contact first name |
| [data.contact.last_name] | <code>string</code> | ApplePay - Shipping contact last name |

<a name="OnShippingAddressChangeEventResponse" id="OnShippingAddressChangeEventResponse" href="#OnShippingAddressChangeEventResponse">&nbsp;</a>

## OnShippingAddressChangeEventResponse : <code>object</code>
Interface for OnShippingAddressChangeEventResponse.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [token] | <code>string</code> | Updated Wallet Token if any |
| [label] | <code>string</code> | ApplePay - Required. Label to show to the customer. |
| [amount] | <code>string</code> | ApplePay - Required. New amount for shipping option. |
| [error] | <code>string</code> | PayPal and ApplePay - Error object in case of error when processing shipping address in if new address unsupported or any other possible error. |
| error.code | <code>string</code> | PayPal and ApplePay - Error code, mandatory in case of error. Possible values for Paypal are 'address_error', 'country_error', 'state_error', 'zip_error' or any other string if none applies. For ApplePay values are 'address_error', 'shipping_contact_invalid' and 'billing_contact_invalid'. |
| [error.field] | <code>string</code> | ApplePay - Error field in case of specifically showing it. Possible values for Apple Pay are 'phone', 'email', 'name', 'phonetic_name', 'address_lines', 'locality', 'postal_code', 'administrative_area', 'country', 'country_code'. |
| [error.message] | <code>string</code> | ApplePay - Custom user facing error message. |

<a name="IApplePayShippingOption" id="IApplePayShippingOption" href="#IApplePayShippingOption">&nbsp;</a>

## IApplePayShippingOption : <code>object</code>
Interface for IApplePayShippingOption.
Used for adding new shippings options when customer updates the shipping address.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [id] | <code>string</code> | Updated Wallet Token if any |
| [label] | <code>string</code> | ApplePay - Required. Label to show to the customer. |
| [amount] | <code>string</code> | ApplePay - Required. New amount for shipping option. |
| [detail] | <code>string</code> | ApplePay - Optional detail for shipping option. |
| [date_components_range] | <code>object</code> | ApplePay - Object that contains the dates for shipping |
| [date_components_range.start_date_components] | <code>object</code> | ApplePay - Contains the start date object |
| [date_components_range.start_date_components.years] | <code>string</code> | ApplePay - Contains the start date year |
| [date_components_range.start_date_components.months] | <code>string</code> | ApplePay - Contains the start date month |
| [date_components_range.start_date_components.days] | <code>string</code> | ApplePay - Contains the start date day |
| [date_components_range.start_date_components.hours] | <code>string</code> | ApplePay - Contains the start date hour |
| [date_components_range.end_date_components] | <code>object</code> | ApplePay - Contains the end date year |
| [date_components_range.end_date_components.years] | <code>string</code> | ApplePay - Contains the end date year |
| [date_components_range.end_date_components.months] | <code>string</code> | ApplePay - Contains the end date month |
| [date_components_range.end_date_components.days] | <code>string</code> | ApplePay - Contains the end date day |
| [date_components_range.end_date_components.hours] | <code>string</code> | ApplePay - Contains the end date hour |

<a name="OnShippingOptionChangeEventData" id="OnShippingOptionChangeEventData" href="#OnShippingOptionChangeEventData">&nbsp;</a>

## OnShippingOptionChangeEventData : <code>object</code>
Interface for OnShippingOptionChangeEventData.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Event Name is 'onShippingOptionsChange' |
| chargeId | <code>string</code> | chargeId set after onClick event |
| [data.shipping_option_id] | <code>string</code> | PayPal and ApplePay - Selected shipping option id |
| [data.amount] | <code>string</code> | Paypal and ApplePay - Selected shipping option amount |
| [data.label] | <code>string</code> | ApplePay - Selected shipping option label |
| [data.detail] | <code>string</code> | ApplePay - Selected shipping option detail |

<a name="OnShippingOptionChangeEventResponse" id="OnShippingOptionChangeEventResponse" href="#OnShippingOptionChangeEventResponse">&nbsp;</a>

## OnShippingOptionChangeEventResponse : <code>object</code>
Interface for OnShippingOptionChangeEventResponse.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [token] | <code>string</code> | Updated Wallet Token if any |
| [label] | <code>string</code> | ApplePay - Required. Label to show to the customer. |
| [amount] | <code>string</code> | ApplePay - Required. New amount for shipping option. |
| [error] | <code>string</code> | PayPal - Error object in case of error when processing shipping option selection. |
| error.code | <code>string</code> | Possible values for Paypal are 'method_unavailable', 'store_unavailable' or any other string if none applies. |

<a name="IApplePayError" id="IApplePayError" href="#IApplePayError">&nbsp;</a>

## IApplePayError : <code>object</code>
Interface for IApplePayError.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| code | <code>&#x27;shipping\_contact\_invalid&#x27;</code> \| <code>&#x27;billing\_contact\_invalid&#x27;</code> \| <code>&#x27;address\_unserviceable&#x27;</code> \| <code>&#x27;coupon\_code\_invalid&#x27;</code> \| <code>&#x27;coupon\_code\_expired&#x27;</code> \| <code>&#x27;unknown&#x27;</code> | The error code for this instance. |
| contact_field | [<code>ContactFieldType</code>](#ContactFieldType) | The error code for this instance. |
| message | <code>string</code> \| <code>undefined</code> | TA localized, user-facing string that describes the error. |

<a name="ApplePayWalletButtonExpress" id="ApplePayWalletButtonExpress" href="#ApplePayWalletButtonExpress">&nbsp;</a>

## ApplePayWalletButtonExpress ⇐ <code>BaseWalletButton</code>
Class ApplePayWalletButtonExpress to work with Apple Pay Wallet.

**Kind**: global class  
**Extends**: <code>BaseWalletButton</code>  

* [ApplePayWalletButtonExpress](#ApplePayWalletButtonExpress) ⇐ <code>BaseWalletButton</code>
    * [new ApplePayWalletButtonExpress(selector, publicKeyOrAccessToken, gatewayId, meta)](#new_ApplePayWalletButtonExpress_new)
    * [.load()](#ApplePayWalletButtonExpress+load)
    * [.setMeta(meta)](#ApplePayWalletButtonExpress+setMeta)
    * [.setEnv(env, [alias])](#BaseWalletButton+setEnv)
    * [.onClick(handler)](#BaseWalletButton+onClick)
    * [.onPaymentSuccessful([handler])](#BaseWalletButton+onPaymentSuccessful)
    * [.onPaymentInReview([handler])](#BaseWalletButton+onPaymentInReview)
    * [.onPaymentError([handler])](#BaseWalletButton+onPaymentError)
    * [.onCheckoutClose(handler)](#BaseWalletButton+onCheckoutClose)
    * [.onShippingAddressChange([handler])](#BaseWalletButton+onShippingAddressChange)
    * [.onShippingOptionsChange([handler])](#BaseWalletButton+onShippingOptionsChange)
    * [.onUnavailable(handler)](#BaseWalletButton+onUnavailable)
    * [.onError(handler)](#BaseWalletButton+onError)

<a name="new_ApplePayWalletButtonExpress_new" id="new_ApplePayWalletButtonExpress_new" href="#new_ApplePayWalletButtonExpress_new">&nbsp;</a>

### new ApplePayWalletButtonExpress(selector, publicKeyOrAccessToken, gatewayId, meta)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | Selector of html element. Container for the ApplePayWalletButtonExpress. |
| publicKeyOrAccessToken | <code>string</code> | Public key or Access token for the ApplePayWalletButtonExpress. |
| gatewayId | <code>string</code> | Gateway ID for the ApplePayWalletButtonExpress. |
| meta | [<code>ApplePayWalletMeta</code>](#ApplePayWalletMeta) | data that configures the Apple Pay Wallet. |

**Example**  
```js
var button = new ApplePayWalletButtonExpress('#wallet-buttons', 'publicKeyOrAccessToken', 'gatewayId', meta);
```
<a name="ApplePayWalletButtonExpress+load" id="ApplePayWalletButtonExpress+load" href="#ApplePayWalletButtonExpress+load">&nbsp;</a>

### applePayWalletButtonExpress.load()
Initializes the availability checks and inserts the button if possible.
Otherwise function onUnavailable(handler: VoidFunction) will be called.
**Important**: Is required to invoke this method to render the wallet button.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Example**  
```js
button.load();
```
<a name="ApplePayWalletButtonExpress+setMeta" id="ApplePayWalletButtonExpress+setMeta" href="#ApplePayWalletButtonExpress+setMeta">&nbsp;</a>

### applePayWalletButtonExpress.setMeta(meta)
Call this method if updating the originally-provided meta object after order information changed.
For example, if the order amount has changed from the time where the button was originally rendered.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>ApplePayWalletMeta</code>](#ApplePayWalletMeta) | // data that configures the Apple Pay Wallet. |

**Example**  
```js
button.setMeta(meta);
```
<a name="BaseWalletButton+setEnv" id="BaseWalletButton+setEnv" href="#BaseWalletButton+setEnv">&nbsp;</a>

### applePayWalletButtonExpress.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com
Bear in mind that you must set an environment before calling `button.load()`.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>setEnv</code>](#BaseWalletButton+setEnv)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  
```js
button.setEnv('production', 'paydock.com');
```
<a name="BaseWalletButton+onClick" id="BaseWalletButton+onClick" href="#BaseWalletButton+onClick">&nbsp;</a>

### applePayWalletButtonExpress.onClick(handler)
Registers a callback function to be invoked when the wallet button gets clicked.
**Note:** is mandatory to handle this event to perform the wallet initialization (and optionally any validation logic).
The event handler needs to return the wallet token string in order for the Wallet charge processing to proceed, or throw an error in case of failure or validation errors.
**Note:** this callback may be called multiple times as the customer closes the payment checkout and re-clicks the button.
It's the merchant's responsibility to handle this situation and evaluate in each case if generating a new WalletCharge Token is required or the previous one can be used in each case, depending on order data and updates.
In case a new one needs to be generated, remember it will need to be preceded by a `setMeta` call.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onClick</code>](#BaseWalletButton+onClick)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnClickCallback</code>](#OnClickCallback) | Function to be called when the wallet button is clicked. |

**Example**  
```js
button.onClick(async (data) => {
     const responseData = await fetch('https://your-server.com/init-wallet-charge');
     return responseData.walletToken;
});
```
<a name="BaseWalletButton+onPaymentSuccessful" id="BaseWalletButton+onPaymentSuccessful" href="#BaseWalletButton+onPaymentSuccessful">&nbsp;</a>

### applePayWalletButtonExpress.onPaymentSuccessful([handler])
If the payment was successful, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onPaymentSuccessful</code>](#BaseWalletButton+onPaymentSuccessful)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnPaymentSuccessfulCallback</code>](#OnPaymentSuccessfulCallback) | Function to be called when the payment was successful. |

**Example**  
```js
button.onPaymentSuccessful((data) => {
     console.log('Payment successful!');
});
```
**Example**  
```js
button.onPaymentSuccessful().then((data) => console.log('Payment successful!'));
```
<a name="BaseWalletButton+onPaymentInReview" id="BaseWalletButton+onPaymentInReview" href="#BaseWalletButton+onPaymentInReview">&nbsp;</a>

### applePayWalletButtonExpress.onPaymentInReview([handler])
If the payment was left in fraud review, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onPaymentInReview</code>](#BaseWalletButton+onPaymentInReview)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnPaymentInReviewCallback</code>](#OnPaymentInReviewCallback) | Function to be called when the payment was left in fraud review status. |

**Example**  
```js
button.onPaymentInReview((data) => {
     console.log('Payment in fraud review');
});
```
**Example**  
```js
button.onPaymentInReview().then((data) => console.log('Payment in fraud review'));
```
<a name="BaseWalletButton+onPaymentError" id="BaseWalletButton+onPaymentError" href="#BaseWalletButton+onPaymentError">&nbsp;</a>

### applePayWalletButtonExpress.onPaymentError([handler])
If the payment was not successful, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onPaymentError</code>](#BaseWalletButton+onPaymentError)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnPaymentErrorCallback</code>](#OnPaymentErrorCallback) | Function to be called when the payment was not successful. |

**Example**  
```js
button.onPaymentError((err) => {
     console.log('Payment not successful');
});
```
**Example**  
```js
button.onPaymentError().then((err) => console.log('Payment not successful'));
```
<a name="BaseWalletButton+onCheckoutClose" id="BaseWalletButton+onCheckoutClose" href="#BaseWalletButton+onCheckoutClose">&nbsp;</a>

### applePayWalletButtonExpress.onCheckoutClose(handler)
Registers a callback function to be invoked when the wallet checkout closes.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onCheckoutClose</code>](#BaseWalletButton+onCheckoutClose)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnCheckoutCloseCallback</code>](#OnCheckoutCloseCallback) | Function to be called when the wallet checkout closes. |

**Example**  
```js
button.onCheckoutClose(() => {
     console.log('Wallet checkout closes');
});
```
<a name="BaseWalletButton+onShippingAddressChange" id="BaseWalletButton+onShippingAddressChange" href="#BaseWalletButton+onShippingAddressChange">&nbsp;</a>

### applePayWalletButtonExpress.onShippingAddressChange([handler])
If shipping address data is updated, the function passed as parameter will be called.
Use this method to listen for shipping address selection or input from customer when shipping is enabled.
The event handler needs to return a new token in case a backend to backend wallet update call was executed.
In addition, if any error occured, an error string must be supplied.
By default, the event handler will be processed successfuly if neither token nor error is returned.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onShippingAddressChange</code>](#BaseWalletButton+onShippingAddressChange)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnShippingAddressChangeCallback</code>](#OnShippingAddressChangeCallback) | Function to be called when the shipping address data is updated. |

**Example**  
```js
button.onShippingAddressChange((data) => {
    const responseData = await fetch('https://your-server.com/update-shipping-info');
    return { error: null, token: responseData.walletToken };
});
```
<a name="BaseWalletButton+onShippingOptionsChange" id="BaseWalletButton+onShippingOptionsChange" href="#BaseWalletButton+onShippingOptionsChange">&nbsp;</a>

### applePayWalletButtonExpress.onShippingOptionsChange([handler])
If shipping options data is updated, the function passed as parameter will be called.
Use this method to listen for shipping option selection from customer when shipping is enabled.
The event handler needs to return a new token in case a backend to backend wallet update call was executed.
In addition, if any error occured, an error string must be supplied.
By default, the event handler will be processed successfuly if neither token nor error is returned.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onShippingOptionsChange</code>](#BaseWalletButton+onShippingOptionsChange)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnShippingOptionsChangeCallback</code>](#OnShippingOptionsChangeCallback) | Function to be called when the shipping options data is updated. |

**Example**  
```js
button.onShippingOptionsChange((data) => {
    const responseData = await fetch('https://your-server.com/update-shipping-info');
    return { error: null, token: responseData.walletToken };
});
```
<a name="BaseWalletButton+onUnavailable" id="BaseWalletButton+onUnavailable" href="#BaseWalletButton+onUnavailable">&nbsp;</a>

### applePayWalletButtonExpress.onUnavailable(handler)
Registers a callback function to be invoked when the wallet is not available in the current context.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onUnavailable</code>](#BaseWalletButton+onUnavailable)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnUnavailableCallback</code>](#OnUnavailableCallback) | Function to be called when the wallet is not available in the current context. |

**Example**  
```js
button.onUnavailable(() => {
     console.log('Wallet not available');
});
```
<a name="BaseWalletButton+onError" id="BaseWalletButton+onError" href="#BaseWalletButton+onError">&nbsp;</a>

### applePayWalletButtonExpress.onError(handler)
Registers a callback function to be invoked when an error that is not related to payment execution occurs.
For example, if the amount of the wallet token injected via the `onClick` event handler does not match the amount provided via the initial `meta` or `setMeta` method.

**Kind**: instance method of [<code>ApplePayWalletButtonExpress</code>](#ApplePayWalletButtonExpress)  
**Overrides**: [<code>onError</code>](#BaseWalletButton+onError)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when the WalletButton has an error. |

**Example**  
```js
button.onError((error) => {
     console.log('WalletButtonExpress error', error);
});
```
<a name="PaypalWalletButtonExpress" id="PaypalWalletButtonExpress" href="#PaypalWalletButtonExpress">&nbsp;</a>

## PaypalWalletButtonExpress ⇐ <code>BaseWalletButton</code>
Class PaypalWalletButtonExpress to work with Paypal Wallet.

**Kind**: global class  
**Extends**: <code>BaseWalletButton</code>  

* [PaypalWalletButtonExpress](#PaypalWalletButtonExpress) ⇐ <code>BaseWalletButton</code>
    * [new PaypalWalletButtonExpress(selector, publicKeyOrAccessToken, gatewayId, meta)](#new_PaypalWalletButtonExpress_new)
    * [.load()](#PaypalWalletButtonExpress+load)
    * [.setMeta(meta)](#PaypalWalletButtonExpress+setMeta)
    * [.setEnv(env, [alias])](#BaseWalletButton+setEnv)
    * [.onClick(handler)](#BaseWalletButton+onClick)
    * [.onPaymentSuccessful([handler])](#BaseWalletButton+onPaymentSuccessful)
    * [.onPaymentInReview([handler])](#BaseWalletButton+onPaymentInReview)
    * [.onPaymentError([handler])](#BaseWalletButton+onPaymentError)
    * [.onCheckoutClose(handler)](#BaseWalletButton+onCheckoutClose)
    * [.onShippingAddressChange([handler])](#BaseWalletButton+onShippingAddressChange)
    * [.onShippingOptionsChange([handler])](#BaseWalletButton+onShippingOptionsChange)
    * [.onUnavailable(handler)](#BaseWalletButton+onUnavailable)
    * [.onError(handler)](#BaseWalletButton+onError)

<a name="new_PaypalWalletButtonExpress_new" id="new_PaypalWalletButtonExpress_new" href="#new_PaypalWalletButtonExpress_new">&nbsp;</a>

### new PaypalWalletButtonExpress(selector, publicKeyOrAccessToken, gatewayId, meta)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | Selector of html element. Container for the PaypalWalletButtonExpress. |
| publicKeyOrAccessToken | <code>string</code> | Public key or Access token for the PaypalWalletButtonExpress. |
| gatewayId | <code>string</code> | Gateway ID for the PaypalWalletButtonExpress. |
| meta | [<code>PaypalWalletMeta</code>](#PaypalWalletMeta) | data that configures the Paypal Wallet. |

**Example**  
```js
var button = new PaypalWalletButtonExpress('#wallet-buttons', 'publicKeyOrAccessToken', 'gatewayId', meta);
```
<a name="PaypalWalletButtonExpress+load" id="PaypalWalletButtonExpress+load" href="#PaypalWalletButtonExpress+load">&nbsp;</a>

### paypalWalletButtonExpress.load()
Initializes the availability checks and inserts the button if possible.
Otherwise function onUnavailable(handler: VoidFunction) will be called.
**Important**: Is required to invoke this method to render the wallet button.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Example**  
```js
button.load();
```
<a name="PaypalWalletButtonExpress+setMeta" id="PaypalWalletButtonExpress+setMeta" href="#PaypalWalletButtonExpress+setMeta">&nbsp;</a>

### paypalWalletButtonExpress.setMeta(meta)
Call this method if updating the originally-provided meta object after order information changed.
For example, if the order amount has changed from the time where the button was originally rendered.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>PaypalWalletMeta</code>](#PaypalWalletMeta) | // data that configures the Paypal Wallet. |

**Example**  
```js
button.setMeta(meta);
```
<a name="BaseWalletButton+setEnv" id="BaseWalletButton+setEnv" href="#BaseWalletButton+setEnv">&nbsp;</a>

### paypalWalletButtonExpress.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com
Bear in mind that you must set an environment before calling `button.load()`.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>setEnv</code>](#BaseWalletButton+setEnv)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  
```js
button.setEnv('production', 'paydock.com');
```
<a name="BaseWalletButton+onClick" id="BaseWalletButton+onClick" href="#BaseWalletButton+onClick">&nbsp;</a>

### paypalWalletButtonExpress.onClick(handler)
Registers a callback function to be invoked when the wallet button gets clicked.
**Note:** is mandatory to handle this event to perform the wallet initialization (and optionally any validation logic).
The event handler needs to return the wallet token string in order for the Wallet charge processing to proceed, or throw an error in case of failure or validation errors.
**Note:** this callback may be called multiple times as the customer closes the payment checkout and re-clicks the button.
It's the merchant's responsibility to handle this situation and evaluate in each case if generating a new WalletCharge Token is required or the previous one can be used in each case, depending on order data and updates.
In case a new one needs to be generated, remember it will need to be preceded by a `setMeta` call.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onClick</code>](#BaseWalletButton+onClick)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnClickCallback</code>](#OnClickCallback) | Function to be called when the wallet button is clicked. |

**Example**  
```js
button.onClick(async (data) => {
     const responseData = await fetch('https://your-server.com/init-wallet-charge');
     return responseData.walletToken;
});
```
<a name="BaseWalletButton+onPaymentSuccessful" id="BaseWalletButton+onPaymentSuccessful" href="#BaseWalletButton+onPaymentSuccessful">&nbsp;</a>

### paypalWalletButtonExpress.onPaymentSuccessful([handler])
If the payment was successful, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onPaymentSuccessful</code>](#BaseWalletButton+onPaymentSuccessful)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnPaymentSuccessfulCallback</code>](#OnPaymentSuccessfulCallback) | Function to be called when the payment was successful. |

**Example**  
```js
button.onPaymentSuccessful((data) => {
     console.log('Payment successful!');
});
```
**Example**  
```js
button.onPaymentSuccessful().then((data) => console.log('Payment successful!'));
```
<a name="BaseWalletButton+onPaymentInReview" id="BaseWalletButton+onPaymentInReview" href="#BaseWalletButton+onPaymentInReview">&nbsp;</a>

### paypalWalletButtonExpress.onPaymentInReview([handler])
If the payment was left in fraud review, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onPaymentInReview</code>](#BaseWalletButton+onPaymentInReview)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnPaymentInReviewCallback</code>](#OnPaymentInReviewCallback) | Function to be called when the payment was left in fraud review status. |

**Example**  
```js
button.onPaymentInReview((data) => {
     console.log('Payment in fraud review');
});
```
**Example**  
```js
button.onPaymentInReview().then((data) => console.log('Payment in fraud review'));
```
<a name="BaseWalletButton+onPaymentError" id="BaseWalletButton+onPaymentError" href="#BaseWalletButton+onPaymentError">&nbsp;</a>

### paypalWalletButtonExpress.onPaymentError([handler])
If the payment was not successful, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onPaymentError</code>](#BaseWalletButton+onPaymentError)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnPaymentErrorCallback</code>](#OnPaymentErrorCallback) | Function to be called when the payment was not successful. |

**Example**  
```js
button.onPaymentError((err) => {
     console.log('Payment not successful');
});
```
**Example**  
```js
button.onPaymentError().then((err) => console.log('Payment not successful'));
```
<a name="BaseWalletButton+onCheckoutClose" id="BaseWalletButton+onCheckoutClose" href="#BaseWalletButton+onCheckoutClose">&nbsp;</a>

### paypalWalletButtonExpress.onCheckoutClose(handler)
Registers a callback function to be invoked when the wallet checkout closes.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onCheckoutClose</code>](#BaseWalletButton+onCheckoutClose)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnCheckoutCloseCallback</code>](#OnCheckoutCloseCallback) | Function to be called when the wallet checkout closes. |

**Example**  
```js
button.onCheckoutClose(() => {
     console.log('Wallet checkout closes');
});
```
<a name="BaseWalletButton+onShippingAddressChange" id="BaseWalletButton+onShippingAddressChange" href="#BaseWalletButton+onShippingAddressChange">&nbsp;</a>

### paypalWalletButtonExpress.onShippingAddressChange([handler])
If shipping address data is updated, the function passed as parameter will be called.
Use this method to listen for shipping address selection or input from customer when shipping is enabled.
The event handler needs to return a new token in case a backend to backend wallet update call was executed.
In addition, if any error occured, an error string must be supplied.
By default, the event handler will be processed successfuly if neither token nor error is returned.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onShippingAddressChange</code>](#BaseWalletButton+onShippingAddressChange)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnShippingAddressChangeCallback</code>](#OnShippingAddressChangeCallback) | Function to be called when the shipping address data is updated. |

**Example**  
```js
button.onShippingAddressChange((data) => {
    const responseData = await fetch('https://your-server.com/update-shipping-info');
    return { error: null, token: responseData.walletToken };
});
```
<a name="BaseWalletButton+onShippingOptionsChange" id="BaseWalletButton+onShippingOptionsChange" href="#BaseWalletButton+onShippingOptionsChange">&nbsp;</a>

### paypalWalletButtonExpress.onShippingOptionsChange([handler])
If shipping options data is updated, the function passed as parameter will be called.
Use this method to listen for shipping option selection from customer when shipping is enabled.
The event handler needs to return a new token in case a backend to backend wallet update call was executed.
In addition, if any error occured, an error string must be supplied.
By default, the event handler will be processed successfuly if neither token nor error is returned.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onShippingOptionsChange</code>](#BaseWalletButton+onShippingOptionsChange)  

| Param | Type | Description |
| --- | --- | --- |
| [handler] | [<code>OnShippingOptionsChangeCallback</code>](#OnShippingOptionsChangeCallback) | Function to be called when the shipping options data is updated. |

**Example**  
```js
button.onShippingOptionsChange((data) => {
    const responseData = await fetch('https://your-server.com/update-shipping-info');
    return { error: null, token: responseData.walletToken };
});
```
<a name="BaseWalletButton+onUnavailable" id="BaseWalletButton+onUnavailable" href="#BaseWalletButton+onUnavailable">&nbsp;</a>

### paypalWalletButtonExpress.onUnavailable(handler)
Registers a callback function to be invoked when the wallet is not available in the current context.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onUnavailable</code>](#BaseWalletButton+onUnavailable)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnUnavailableCallback</code>](#OnUnavailableCallback) | Function to be called when the wallet is not available in the current context. |

**Example**  
```js
button.onUnavailable(() => {
     console.log('Wallet not available');
});
```
<a name="BaseWalletButton+onError" id="BaseWalletButton+onError" href="#BaseWalletButton+onError">&nbsp;</a>

### paypalWalletButtonExpress.onError(handler)
Registers a callback function to be invoked when an error that is not related to payment execution occurs.
For example, if the amount of the wallet token injected via the `onClick` event handler does not match the amount provided via the initial `meta` or `setMeta` method.

**Kind**: instance method of [<code>PaypalWalletButtonExpress</code>](#PaypalWalletButtonExpress)  
**Overrides**: [<code>onError</code>](#BaseWalletButton+onError)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when the WalletButton has an error. |

**Example**  
```js
button.onError((error) => {
     console.log('WalletButtonExpress error', error);
});
```
<a name="EVENT" id="EVENT" href="#EVENT">&nbsp;</a>

## EVENT : <code>object</code>
List of available event's name in the wallet button lifecycle

**Kind**: global constant  

| Param | Type | Default |
| --- | --- | --- |
| UNAVAILABLE | <code>string</code> | <code>&quot;unavailable&quot;</code> | 
| ERROR | <code>string</code> | <code>&quot;error&quot;</code> | 
| PAYMENT_SUCCESSFUL | <code>string</code> | <code>&quot;paymentSuccessful&quot;</code> | 
| PAYMENT_ERROR | <code>string</code> | <code>&quot;paymentError&quot;</code> | 
| PAYMENT_IN_REVIEW | <code>string</code> | <code>&quot;paymentInReview&quot;</code> | 
| ON_CLICK | <code>string</code> | <code>&quot;onClick&quot;</code> | 
| ON_CHECKOUT_CLOSE | <code>string</code> | <code>&quot;onCheckoutClose&quot;</code> | 
| ON_SHIPPING_ADDRESS_CHANGE | <code>string</code> | <code>&quot;onShippingAddressChange&quot;</code> | 
| ON_SHIPPING_OPTIONS_CHANGE | <code>string</code> | <code>&quot;onShippingOptionsChange&quot;</code> | 

<a name="ContactFieldType" id="ContactFieldType" href="#ContactFieldType">&nbsp;</a>

## ContactFieldType : <code>object</code>
List of available contact fields for ContactFieldType

**Kind**: global constant  

| Param | Type |
| --- | --- |
| phone | <code>string</code> | 
| email | <code>string</code> | 
| name | <code>string</code> | 
| phonetic_name | <code>string</code> | 
| address_lines | <code>string</code> | 
| address_city | <code>string</code> | 
| address_postcode | <code>string</code> | 
| address_state | <code>string</code> | 
| address_country | <code>string</code> | 
| address_country_code | <code>string</code> | 

<a name="OnClickCallback" id="OnClickCallback" href="#OnClickCallback">&nbsp;</a>

## OnClickCallback ⇒ <code>Promise.&lt;string&gt;</code>
Callback for onClick method.

**Kind**: global typedef  
**Returns**: <code>Promise.&lt;string&gt;</code> - walletToken string result  

| Param | Type |
| --- | --- |
| data | [<code>OnClickEventData</code>](#OnClickEventData) | 

<a name="OnPaymentSuccessfulCallback" id="OnPaymentSuccessfulCallback" href="#OnPaymentSuccessfulCallback">&nbsp;</a>

## OnPaymentSuccessfulCallback : <code>function</code>
Callback for onPaymentSuccessful method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>OnPaymentSuccessfulEventData</code>](#OnPaymentSuccessfulEventData) | 

<a name="OnPaymentInReviewCallback" id="OnPaymentInReviewCallback" href="#OnPaymentInReviewCallback">&nbsp;</a>

## OnPaymentInReviewCallback : <code>function</code>
Callback for onPaymentInReview method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>OnPaymentInReviewEventData</code>](#OnPaymentInReviewEventData) | 

<a name="OnPaymentErrorCallback" id="OnPaymentErrorCallback" href="#OnPaymentErrorCallback">&nbsp;</a>

## OnPaymentErrorCallback : <code>function</code>
Callback for onPaymentError method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>OnPaymentErrorEventData</code>](#OnPaymentErrorEventData) | 

<a name="OnCheckoutCloseCallback" id="OnCheckoutCloseCallback" href="#OnCheckoutCloseCallback">&nbsp;</a>

## OnCheckoutCloseCallback : <code>function</code>
Callback for onCheckoutClose method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>OnCloseEventData</code>](#OnCloseEventData) | 

<a name="OnShippingAddressChangeCallback" id="OnShippingAddressChangeCallback" href="#OnShippingAddressChangeCallback">&nbsp;</a>

## OnShippingAddressChangeCallback ⇒ [<code>Promise.&lt;OnShippingAddressChangeEventResponse&gt;</code>](#OnShippingAddressChangeEventResponse)
Callback for onShippingAddressChange method.

**Kind**: global typedef  
**Returns**: [<code>Promise.&lt;OnShippingAddressChangeEventResponse&gt;</code>](#OnShippingAddressChangeEventResponse) - Address update result  

| Param | Type |
| --- | --- |
| data | [<code>OnShippingAddressChangeEventData</code>](#OnShippingAddressChangeEventData) | 

<a name="OnShippingOptionsChangeCallback" id="OnShippingOptionsChangeCallback" href="#OnShippingOptionsChangeCallback">&nbsp;</a>

## OnShippingOptionsChangeCallback ⇒ [<code>Promise.&lt;OnShippingOptionChangeEventResponse&gt;</code>](#OnShippingOptionChangeEventResponse)
Callback for onShippingOptionsChange method.

**Kind**: global typedef  
**Returns**: [<code>Promise.&lt;OnShippingOptionChangeEventResponse&gt;</code>](#OnShippingOptionChangeEventResponse) - Address update result  

| Param | Type |
| --- | --- |
| data | [<code>OnShippingOptionChangeEventData</code>](#OnShippingOptionChangeEventData) | 

<a name="OnUnavailableCallback" id="OnUnavailableCallback" href="#OnUnavailableCallback">&nbsp;</a>

## OnUnavailableCallback : <code>function</code>
Callback for onUnavailable method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>OnUnavailableEventData</code>](#OnUnavailableEventData) | 

<a name="OnErrorCallback" id="OnErrorCallback" href="#OnErrorCallback">&nbsp;</a>

## OnErrorCallback : <code>function</code>
Callback for onError method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>OnErrorEventData</code>](#OnErrorEventData) | 


## Open Wallet Buttons
You can find description of all methods and parameters [here](https://www.npmjs.com/package/@paydock/client-sdk#open-wallet-buttons-simple-example)

Open Wallet Buttons provide a next-generation approach to integrating E-Wallets into your checkout with improved event handling and more granular control over wallet interactions.

Each wallet type has its own dedicated class with fully typed metadata:
- [ApplePayOpenWalletButton](#ApplePayOpenWalletButton) - for Apple Pay integration
- [GooglePayOpenWalletButton](#GooglePayOpenWalletButton) - for Google Pay integration

On `load()`, each button fetches the service configuration from PayDock and validates that the service type matches the expected wallet. If there is a mismatch (e.g. using an Apple Pay service ID with `GooglePayOpenWalletButton`), an error will be raised via the `onError` callback.

If available in your client environment, you will display a simple button that upon clicking it the user will follow the standard flow for the appropriate Wallet. If not available an event will be raised and no button will be displayed.

## Apple Pay Open Wallet Button

### Container

```html
<div id="widget"></div>
```

You must create a container for the Open Wallet Button. Inside this tag, the button will be initialized.

Before initializing the button, you must configure your Apple Pay wallet service through the PayDock dashboard and obtain the service ID that will be used to load the button configuration.

### Initialization

```javascript
let button = new paydock.ApplePayOpenWalletButton(
    "#widget",
    publicKeyOrAccessToken,
    serviceId,
    {
        amount: 100,
        currency: "AUD",
        country: "AU",
        amount_label: "TOTAL",
        store_name: "My Store",
        apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    }
);
button.load();
```

```javascript
// ES2015 | TypeScript
import { ApplePayOpenWalletButton } from '@paydock/client-sdk';

var button = new ApplePayOpenWalletButton(
    '#widget',
    publicKeyOrAccessToken,
    serviceId,
    {
        amount: 100,
        currency: 'AUD',
        country: 'AU',
        amount_label: 'TOTAL',
        store_name: 'My Store',
    }
);
button.load();
```

### Constructor Parameters

The ApplePayOpenWalletButton constructor accepts the following parameters:

1. **selector** (string): CSS selector for the container element
2. **publicKeyOrAccessToken** (string): Your PayDock public key or access token
3. **serviceId** (string): The Apple Pay service ID configured in PayDock dashboard
4. **meta** (ApplePayOpenWalletMeta): Apple Pay-specific configuration object

> **Note:** Required meta fields (`amount`, `currency`, `country`, `amount_label`, `store_name`) are validated automatically by the `ApplePayOpenWalletButton` class. You do not need to specify them manually.

### Setting environment

Current method can change environment. By default environment = sandbox.
Bear in mind that you must set an environment before calling `button.load()`.

```javascript
button.setEnv('sandbox');
```

### Full Apple Pay example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Apple Pay with Open Wallets</title>
</head>
<body>
    <h2>Payment using PayDock Apple Pay Open Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.ApplePayOpenWalletButton(
        "#widget",
        publicKeyOrAccessToken,
        serviceId,
        {
            amount: 100,
            currency: "AUD",
            country: "AU",
            amount_label: "TOTAL",
            store_name: "My Store",
            request_shipping: true,
            request_payer_name: true,
            request_payer_email: true,
            request_payer_phone: true,
            show_billing_address: true,
            style: {
                button_type: 'buy',
                button_style: 'black'
            },
            shipping_options: [
                {
                    id: "standard",
                    label: "Standard Shipping",
                    detail: "Arrives in 5 to 7 days",
                    amount: 5.00,
                    date_components_range: {
                        start_date_components: {
                            years: 0,
                            months: 0,
                            days: 5,
                            hours: 0,
                        },
                        end_date_components: {
                            years: 0,
                            months: 0,
                            days: 7,
                            hours: 0,
                        }
                    }
                },
                {
                    id: "express",
                    label: "Express Shipping",
                    detail: "Arrives in 1 to 2 days",
                    amount: 15.00,
                    date_components_range: {
                        start_date_components: {
                            years: 0,
                            months: 0,
                            days: 1,
                            hours: 0,
                        },
                        end_date_components: {
                            years: 0,
                            months: 0,
                            days: 2,
                            hours: 0,
                        }
                    }
                }
            ],
            apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable']
        }
    );

    button.setEnv('sandbox');

    button.onUnavailable(({ data }) => {
        console.log("Apple Pay not available:", data);
    });

    button.onClick(() => {
        console.log("Apple Pay button clicked");
    });

    button.onSuccess(({ data }) => {
        console.log("Payment successful:", data);
        processPayment(data.token);
    });

    button.onError(({ data }) => {
        console.error("Payment error:", data);
    });

    button.onCancel(() => {
        console.log("Payment cancelled");
    });

    button.onShippingAddressChange(async ({ data }) => {
        const response = await updateShippingCosts(data);
        return {
            amount: response.newAmount,
            shipping_options: response.shippingOptions
        };
    });

    button.onShippingOptionsChange(async ({ data }) => {
        const response = await updateTotal(data);
        return {
            amount: response.newAmount
        };
    });

    button.load();

    async function updateShippingCosts(addressData) {
        // Your shipping calculation logic based on address
        const baseAmount = 100;
        const updatedShippingOptions = [
            {
                id: "updated-standard",
                label: "Updated Standard Shipping",
                detail: "Based on your location",
                amount: 8.00
            },
            {
                id: "updated-express",
                label: "Updated Express Shipping",
                detail: "Fast delivery to your area",
                amount: 18.00
            }
        ];

        return {
            newAmount: baseAmount + updatedShippingOptions[0].amount,
            shippingOptions: updatedShippingOptions
        };
    }

    async function updateTotal(shippingOption) {
        const baseAmount = 100;
        const shippingAmount = shippingOption.amount;
        return {
            newAmount: baseAmount + shippingAmount
        };
    }

    function processPayment(ottToken) {
        fetch('/api/process-payment', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ott_token: ottToken })
        });
    }
</script>
</html>
```

### Apple Pay with Shipping

For Apple Pay with shipping enabled:
```javascript
let button = new paydock.ApplePayOpenWalletButton(
    "#widget",
    publicKeyOrAccessToken,
    serviceId,
    {
        amount: 100,
        currency: "AUD",
        country: "AU",
        amount_label: "TOTAL",
        store_name: "My Store",
        request_shipping: true,
        shipping_editing_mode: 'available',
        required_shipping_contact_fields: [
            'postalAddress',
            'name',
            'phone',
            'email',
        ],
        shipping_options: [
            {
                id: "standard",
                label: "Standard Shipping",
                detail: "5-7 business days",
                amount: 5.00
            },
            {
                id: "express",
                label: "Express Shipping",
                detail: "1-2 business days",
                amount: 15.00
            }
        ],
        apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable']
    }
);
button.load();
```

When supporting shipping, registering `onShippingAddressChange` and `onShippingOptionsChange` handlers lets you recalculate totals and update shipping options dynamically. If no handler is registered (or the handler throws), the SDK auto-accepts with the current amount and options.

```javascript
button.onShippingAddressChange(async function({ data }) {
    console.log("Shipping address has been updated", data);
    return {
        amount: newAmount,
        shipping_options: updatedShippingOptions
    };
});

button.onShippingOptionsChange(async function({ data }) {
    console.log("Shipping option selected", data);
    return {
        amount: newTotalAmount
    };
});
```

### Supported Shipping Cases

#### Injected Shipping Address, non-editable by the customer

This is the case where the shipping address is injected by the merchant and is not editable by the customer. The customer can only select the shipping option.

The required meta parameters for this case are:
- shipping_editing_mode: 'store_pickup'
- required_shipping_contact_fields: ['postalAddress'] <-- At least one of the fields is required so the shipping address is shown at Apple Pay.

```javascript
meta: {
    apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    amount_label: 'TOTAL',
    country: 'AU',
    currency: 'AUD',
    amount: 10,
    shipping_editing_mode: 'store_pickup',
    required_shipping_contact_fields: [
        'postalAddress',
        'name',
        'phone',
        'email',
    ],
    shipping: {
        amount: 5,
        address_line1: "Address Line 1",
        address_city: "Test Locality",
        address_state: "NSW",
        address_country: "Australia",
        address_country_code: "AU",
        address_postcode: "3000",
        contact: {
            phone: "+61400245562",
            email: "test@example.com",
            first_name: "QA",
            last_name: "QA",
        },
        options: [
            {
                label: "Test 1",
                detail: "This is a test 1 shipping methods",
                amount: 10,
                id: "randomId1",
            }
        ],
    },
}
```

#### Injected Shipping Address, editable by the customer

This is the case where the shipping address is injected by the merchant and is editable by the customer. The customer can edit the shipping address and select the shipping option.

The required meta parameters for this case are:
- shipping_editing_mode: 'available'
- required_shipping_contact_fields: ['postalAddress'] <-- At least one of the fields is required so the shipping address is shown at Apple Pay.

```javascript
meta: {
    apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    amount_label: 'TOTAL',
    country: 'AU',
    currency: 'AUD',
    amount: 10,
    shipping_editing_mode: 'available',
    required_shipping_contact_fields: [
        'postalAddress',
        'name',
        'phone',
        'email',
    ],
    shipping: {
        amount: 5,
        address_line1: "Address Line 1",
        address_city: "Test Locality",
        address_state: "NSW",
        address_country: "Australia",
        address_country_code: "AU",
        address_postcode: "3000",
        contact: {
            phone: "+61400245562",
            email: "test@example.com",
            first_name: "QA",
            last_name: "QA",
        },
        options: [
            {
                label: "Test 1",
                detail: "This is a test 1 shipping methods",
                amount: 10,
                id: "randomId1",
            }
        ],
    },
}
```

#### Shipping address editable by the customer (no pre-filled address)

This is the case where the shipping address is not injected by the merchant and is editable by the customer. The customer can edit the shipping address and select the shipping option.

The required meta parameters for this case are:
- shipping_editing_mode: 'available'
- required_shipping_contact_fields: ['postalAddress'] <-- At least one of the fields is required so the shipping address is shown at Apple Pay.

```javascript
meta: {
    apple_pay_capabilities: ['credentials_available', 'credentials_status_unknown', 'credentials_unavailable'],
    amount_label: 'TOTAL',
    country: 'AU',
    currency: 'AUD',
    amount: 10,
    shipping_editing_mode: 'available',
    required_shipping_contact_fields: [
        'postalAddress',
        'name',
        'phone',
        'email',
    ],
}
```

#### No shipping address

This is the case where no shipping address is required at all in the popup (e.g., digital goods, services, or virtual products, or Shipping Address collected separately by the merchant). The "Send to" UI field will not be shown in the Apple Pay sheet, it will be hidden.

**Important:**
- No shipping address should be provided in the meta object.
- Shipping address could be provided in the initial POST `/v1/charges/wallet` endpoint, if collected previously.

The required meta parameters for this case are:
- `required_shipping_contact_fields`: Only include contact fields if needed (phone, email), but NOT `postalAddress`.

```javascript
meta: {
    amount_label: "TOTAL",
    country: "AU",
    currency: "AUD",
    amount: 10,
    shipping_editing_mode: "available",
    required_shipping_contact_fields: ["phone", "email"],
    apple_pay_capabilities: ["credentials_available", "credentials_status_unknown", "credentials_unavailable"]
}
```

## Google Pay Open Wallet Button

### Initialization

```javascript
let button = new paydock.GooglePayOpenWalletButton(
    "#widget",
    publicKeyOrAccessToken,
    serviceId,
    {
        amount: 100,
        currency: "AUD",
        country: "AU",
        merchant_name: "Your Store",
    }
);
button.load();
```

```javascript
// ES2015 | TypeScript
import { GooglePayOpenWalletButton } from '@paydock/client-sdk';

var button = new GooglePayOpenWalletButton(
    '#widget',
    publicKeyOrAccessToken,
    serviceId,
    {
        amount: 100,
        currency: 'AUD',
        country: 'AU',
        merchant_name: 'Your Store',
    }
);
button.load();
```

### Constructor Parameters

The GooglePayOpenWalletButton constructor accepts the following parameters:

1. **selector** (string): CSS selector for the container element
2. **publicKeyOrAccessToken** (string): Your PayDock public key or access token
3. **serviceId** (string): The Google Pay service ID configured in PayDock dashboard
4. **meta** (GooglePayOpenWalletMeta): Google Pay-specific configuration object

> **Note:** Required meta fields (`amount`, `currency`, `country`) are validated automatically by the `GooglePayOpenWalletButton` class. You do not need to specify them manually.

### Full Google Pay Example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Google Pay with Open Wallets</title>
</head>
<body>
    <h2>Payment using PayDock Google Pay Open Wallet Button!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.GooglePayOpenWalletButton(
        "#widget",
        publicKeyOrAccessToken,
        serviceId,
        {
            amount: 100,
            currency: "AUD",
            country: "AU",
            amount_label: "Total",
            request_shipping: true,
            show_billing_address: true,
            merchant_name: 'Test Merchant',
            style: {
                button_type: 'buy',
                button_color: 'default',
                button_size_mode: 'fill'
            },
            shipping_options: [
                {
                    id: "standard",
                    label: "Standard Shipping",
                    detail: "Arrives in 5 to 7 days",
                    amount: 5.00,
                    type: "ELECTRONIC"
                },
                {
                    id: "express",
                    label: "Express Shipping",
                    detail: "Arrives in 1 to 2 days",
                    amount: 15.00,
                    type: "PICKUP"
                }
            ]
        }
    );

    button.setEnv('sandbox');

    button.onSuccess(({ data }) => {
        console.log("Payment successful:", data);
        processPayment(data.token);
    });

    button.onShippingAddressChange(async ({ data }) => {
        const response = await updateShippingCosts(data);
        return {
            amount: response.newAmount,
            shipping_options: response.shippingOptions
        };
    });

    button.onShippingOptionsChange(async ({ data }) => {
        const response = await updateTotal(data);
        return {
            amount: response.newAmount
        };
    });

    button.onUnavailable(({ data }) => {
        console.log("Google Pay not available:", data);
    });

    button.onError(({ data }) => {
        console.error("Payment error:", data);
    });

    button.onCancel(() => {
        console.log("Payment cancelled");
    });

    button.onClick(() => {
        console.log("Google Pay button clicked");
    });

    button.load();

    // Helper functions
    async function updateShippingCosts(addressData) {
        const baseAmount = 100;
        const updatedShippingOptions = [
            {
                id: "updated-standard",
                label: "Updated Standard Shipping",
                detail: "Based on your location",
                amount: 8.00,
                type: "ELECTRONIC"
            },
            {
                id: "updated-express",
                label: "Updated Express Shipping",
                detail: "Fast delivery to your area",
                amount: 18.00,
                type: "PICKUP"
            }
        ];

        return {
            newAmount: baseAmount + updatedShippingOptions[0].amount,
            shippingOptions: updatedShippingOptions
        };
    }

    async function updateTotal(shippingOption) {
        const baseAmount = 100;
        const shippingAmount = shippingOption.amount;
        return {
            newAmount: baseAmount + shippingAmount
        };
    }

    function processPayment(ottToken) {
        fetch('/api/process-payment', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ott_token: ottToken })
        });
    }
</script>
</html>
```

## Common API

Both `ApplePayOpenWalletButton` and `GooglePayOpenWalletButton` share the same event handler API inherited from the base class.

### Checking for button availability

If the customer's browser is not supported, or the customer does not have any card added to their wallet, the button will not load. In this case the callback onUnavailable() will be called. You can define the behavior of this function before loading the button.

```javascript
button.onUnavailable(({ data }) => console.log("No wallet button available", data));
```

### Service type validation

Each button validates that the service configuration matches its expected wallet type. If you use an Apple Pay service ID with `GooglePayOpenWalletButton` (or vice versa), an error will be emitted via `onError`:

```javascript
// This will raise an error if the service ID does not correspond to a Google Pay service
let button = new paydock.GooglePayOpenWalletButton(
    "#widget",
    publicKeyOrAccessToken,
    applePayServiceId, // Wrong! This is an Apple Pay service ID
    meta
);

button.onError(({ data }) => {
    // Error: Service configuration type 'ApplePay' does not match expected wallet type 'google'.
    console.error(data.error.message);
});

button.load();
```

### Performing actions when the wallet button is clicked

You can perform validations or actions when the user clicks on the wallet button. The callback supports both synchronous and asynchronous operations using its return value: return `false` to abort, return a `Promise` to defer the wallet sheet, or throw an error to abort.

```javascript
// Synchronous — continue normally
button.onClick(() => {
    console.log("Perform actions on button click");
});

// Synchronous — return false to abort the payment flow
button.onClick(() => {
    if (!isOrderValid()) return false;
});

// Asynchronous — defer the wallet sheet until the promise resolves
button.onClick(async () => {
    const response = await fetch('/api/validate-order');
    const result = await response.json();
    if (!result.valid) {
        throw new Error('Order validation failed');
    }
});
```

### Handling successful OTT creation

When the One Time Token (OTT) is successfully created, the onSuccess callback will be called with the token data. **This callback is required** - if no handler is provided, an error will be thrown.

```javascript
button.onSuccess(({ data }) => {
    console.log("OTT created successfully:", data.token);
    console.log("Amount:", data.amount);
    console.log("Shipping:", data.shipping);
    console.log("Billing:", data.billing);

    fetch('/api/process-payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ott_token: data.token })
    });
});
```

**Important**: The `onSuccess` event handler is mandatory. Not providing one will result in an error.

### Updating meta after initialization

If the screen where the button is rendered allows for cart/amount changes, call `setMeta` method to update the meta information. The `setMeta` method is fully typed for each wallet:

```javascript
// For Apple Pay - accepts ApplePayOpenWalletMeta
applePayButton.setMeta({ ...meta, amount: 29.99, amount_label: 'NEW TOTAL' });

// For Google Pay - accepts GooglePayOpenWalletMeta
googlePayButton.setMeta({ ...meta, amount: 29.99, merchant_name: 'Updated Store' });
```

### Handling errors

Register a callback function to handle errors that occur during wallet operations, including service type mismatches.

```javascript
button.onError(({ data }) => {
    console.error("Open Wallet error:", data.error);
    console.log("Error context:", data.context);

    showErrorMessage("Payment initialization failed. Please try again.");
});
```

### Handling checkout cancellation

When the user cancels or closes the wallet payment interface, you can perform cleanup operations.

```javascript
button.onCancel(() => {
    console.log("Wallet checkout cancelled");
    window.location.href = '/checkout';
});
```

### Cleaning up

Remove the wallet button from the DOM when it is no longer needed:

```javascript
button.destroy();
```

### Events
The above events can be used in a more generic way via the `eventEmitter.subscribe` method internally, but the recommended approach is to use the dedicated event handler methods provided by the button classes.

**Available Event Handler Methods:**
- `onClick(handler)` - Button click events (return `false` to abort, `Promise` to defer)
- `onSuccess(handler)` - **Required** - OTT creation success events
- `onUnavailable(handler)` - Wallet unavailable events (supports Promise pattern)
- `onError(handler)` - Error events (supports Promise pattern)
- `onCancel(handler)` - Checkout cancellation events (supports Promise pattern)
- `onLoaded(handler)` - Button loaded/rendered events
- `onShippingAddressChange(handler)` - **Recommended for shipping** - Address change events (auto-accepted if not registered)
- `onShippingOptionsChange(handler)` - **Recommended for shipping options** - Option change events (auto-accepted if not registered)

**Event Handler Patterns:**

```javascript
// Required handler
button.onSuccess(handler);  // Always required

// Recommended when shipping is enabled (auto-accepted if not registered)
button.onShippingAddressChange(handler);
button.onShippingOptionsChange(handler);

// Optional handlers with Promise support
button.onUnavailable(handler);  // or await button.onUnavailable()
button.onError(handler);        // or await button.onError()
button.onCancel(handler);       // or await button.onCancel()

// Click handler with flow control
button.onClick(handler);  // Return false to abort, or a Promise to defer

// Loaded handler
button.onLoaded(handler);  // Notified when button renders
```

### Apple Pay-Specific Meta Properties

A full description of the [ApplePayOpenWalletMeta](#ApplePayOpenWalletMeta) properties:

**Required:**
- `amount`: The payment amount (number)
- `currency`: The currency code (string, e.g., "AUD")
- `country`: The country code (string, e.g., "AU")
- `amount_label`: Label for the total amount (string)
- `store_name`: Merchant store name (string)

**Optional:**
- `request_shipping?: boolean`: Enable shipping address collection
- `shipping_options?: IApplePayShippingOption[]`: Array of shipping options
- `show_billing_address?: boolean`: Show billing address fields
- `apple_pay_capabilities?: string[]`: Device capabilities
- `merchant_capabilities?: string[]`: Merchant capabilities
- `supported_networks?: string[]`: Supported payment networks
- `required_billing_contact_fields?: string[]`: Required billing contact fields
- `required_shipping_contact_fields?: string[]`: Required shipping contact fields
- `supported_countries?: string[]`: Supported countries
- `shipping_editing_mode?: 'available' | 'store_pickup'`: Shipping address editing mode
- `style?: { button_type?: ApplePayButtonType, button_style?: ApplePayButtonStyle }`: Button styling

### Google Pay-Specific Meta Properties

A full description of the [GooglePayOpenWalletMeta](#GooglePayOpenWalletMeta) properties:

**Required:**
- `amount`: The payment amount (number)
- `currency`: The currency code (string, e.g., "AUD")
- `country`: The country code (string, e.g., "AU")

**Optional:**
- `amount_label?: string`: Label for the total amount
- `merchant_name?: string`: Display name for the merchant
- `request_shipping?: boolean`: Enable shipping address collection
- `shipping_options?: IGooglePayShippingOption[]`: Array of shipping options
- `show_billing_address?: boolean`: Show billing address fields
- `card_config?: GooglePayCardConfig`: Card configuration (auth methods, networks, tokenization)
- `style?: { button_type?: GooglePayButtonType, button_color?: GooglePayButtonColor, button_size_mode?: GooglePayButtonSizeMode }`: Button styling

### Shipping Options Format
```javascript
shipping_options: [
    {
        id: "option_id",           // Unique identifier (string)
        label: "Option Name",      // Display name (string)
        detail: "Description",     // Optional description (string)
        amount: 10.00,            // Shipping cost as number
        date_components_range: {   // Optional: delivery date range (Apple Pay only)
            start_date_components: {
                years: 0,
                months: 0,
                days: 5,
                hours: 0,
            },
            end_date_components: {
                years: 0,
                months: 0,
                days: 10,
                hours: 0,
            }
        }
    }
]
```

**Important**:
- `amount` should be a **number**, not a string
- `date_components_range` is optional but provides delivery estimates (Apple Pay only)
- Updated shipping options returned from event handlers don't require `date_components_range`

### Environment Setup
```javascript
// Always set environment before loading
button.setEnv('sandbox');
button.load();
```

### Error Handling Best Practices
```javascript
button.onError(function({ data }) {
    console.error('Full error object:', data);

    const errorMessage = data.error?.message || 'Unknown error occurred';

    if (data.context?.operation === 'wallet_operation') {
        showWalletError(errorMessage);
    } else {
        showGeneralError(errorMessage);
    }
});
```

## Classes

<dl>
<dt><a href="#ApplePayOpenWalletButton">ApplePayOpenWalletButton</a> ⇐ <code><a href="#OpenWalletButtons">OpenWalletButtons</a></code></dt>
<dd><p>Apple Pay wallet button that creates One-Time Tokens (OTT) via Apple Pay.</p>
<p>Provides a fully typed Apple Pay integration with Apple Pay-specific metadata
and validates that the service configuration corresponds to an Apple Pay service.
On <code>load()</code>, the button fetches the service configuration and raises an error via <code>onError</code>
if the service type does not match Apple Pay.</p>
</dd>
<dt><a href="#GooglePayOpenWalletButton">GooglePayOpenWalletButton</a> ⇐ <code><a href="#OpenWalletButtons">OpenWalletButtons</a></code></dt>
<dd><p>Google Pay wallet button that creates One-Time Tokens (OTT) via Google Pay.</p>
<p>Provides a fully typed Google Pay integration with Google Pay-specific metadata
and validates that the service configuration corresponds to a Google Pay service.
On <code>load()</code>, the button fetches the service configuration and raises an error via <code>onError</code>
if the service type does not match Google Pay.</p>
</dd>
<dt><a href="#OpenWalletButtons">OpenWalletButtons</a></dt>
<dd><p>Abstract base class for Open Wallet buttons. <strong>Do not instantiate directly.</strong>
Use <a href="#ApplePayOpenWalletButton">ApplePayOpenWalletButton</a> or <a href="#GooglePayOpenWalletButton">GooglePayOpenWalletButton</a> instead.</p>
<p>Use one of the concrete implementations instead:</p>
<ul>
<li><a href="#ApplePayOpenWalletButton">ApplePayOpenWalletButton</a> for Apple Pay integration</li>
<li><a href="#GooglePayOpenWalletButton">GooglePayOpenWalletButton</a> for Google Pay integration</li>
</ul>
<p>These subclasses inherit all event handlers and lifecycle methods documented below.</p>
</dd>
</dl>

## Constants

<dl>
<dt><a href="#EVENT">EVENT</a> : <code>object</code></dt>
<dd><p>List of available event names in the Open Wallet button lifecycle.</p>
</dd>
<dt><a href="#WALLET_TYPES">WALLET_TYPES</a> : <code>object</code></dt>
<dd><p>Enum of available wallet types.</p>
</dd>
<dt><a href="#TOKEN_TYPE">TOKEN_TYPE</a> : <code>object</code></dt>
<dd><p>Token types returned in the OTT (One-Time Token) creation response.</p>
</dd>
<dt><a href="#ERROR_OPERATION">ERROR_OPERATION</a> : <code>object</code></dt>
<dd><p>Operations that can fail during the wallet lifecycle.
Used in the <code>context.operation</code> field of <a href="#OnErrorEventData">OnErrorEventData</a>.</p>
</dd>
</dl>

## Typedefs

<dl>
<dt><a href="#OnClickCallback">OnClickCallback</a> ⇒ <code>boolean</code> | <code>void</code> | <code>Promise.&lt;(boolean|void)&gt;</code></dt>
<dd><p>Callback for onClick method.</p>
</dd>
<dt><a href="#OnSuccessCallback">OnSuccessCallback</a> : <code>function</code></dt>
<dd><p>Callback for onSuccess method.</p>
</dd>
<dt><a href="#OnUnavailableCallback">OnUnavailableCallback</a> : <code>function</code></dt>
<dd><p>Callback for onUnavailable method.</p>
</dd>
<dt><a href="#OnErrorCallback">OnErrorCallback</a> : <code>function</code></dt>
<dd><p>Callback for onError method.</p>
</dd>
<dt><a href="#OnCancelCallback">OnCancelCallback</a> : <code>function</code></dt>
<dd><p>Callback for onCancel method.</p>
</dd>
<dt><a href="#OnShippingAddressChangeCallback">OnShippingAddressChangeCallback</a> ⇒ <code><a href="#OnShippingAddressChangeEventResponse">OnShippingAddressChangeEventResponse</a></code> | <code><a href="#OnShippingAddressChangeEventResponse">Promise.&lt;OnShippingAddressChangeEventResponse&gt;</a></code></dt>
<dd><p>Callback for onShippingAddressChange method.</p>
</dd>
<dt><a href="#OnShippingOptionsChangeCallback">OnShippingOptionsChangeCallback</a> ⇒ <code><a href="#OnShippingOptionChangeEventResponse">OnShippingOptionChangeEventResponse</a></code> | <code><a href="#OnShippingOptionChangeEventResponse">Promise.&lt;OnShippingOptionChangeEventResponse&gt;</a></code></dt>
<dd><p>Callback for onShippingOptionsChange method.</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#ApplePayOpenWalletMeta">ApplePayOpenWalletMeta</a> : <code>object</code></dt>
<dd><p>Interface for Apple Pay-specific metadata.</p>
<p>For further information about ApplePay Capabilities refer to <a href="https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/4440085-applepaycapabilities">the documentation</a>.
Apple will determine if the device has an ApplePay wallet available and at least one active payment.</p>
</dd>
<dt><a href="#GooglePayOpenWalletMeta">GooglePayOpenWalletMeta</a> : <code>object</code></dt>
<dd><p>Interface for Google Pay-specific metadata.</p>
</dd>
<dt><a href="#OnClickEventData">OnClickEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnClickEventData.
Emitted when the wallet button is clicked.</p>
<p>The merchant&#39;s <code>onClick</code> handler controls the payment flow via its return value:</p>
<ul>
<li>Return <code>void</code> / <code>undefined</code> to continue normally.</li>
<li>Return <code>false</code> to abort the payment flow.</li>
<li>Return a <code>Promise&lt;void&gt;</code> to defer the wallet sheet until the promise resolves.</li>
<li>Return a <code>Promise&lt;boolean&gt;</code> — if it resolves to <code>false</code>, the flow is aborted.</li>
<li>Throwing an error (sync or async) also aborts the flow.</li>
</ul>
</dd>
<dt><a href="#OnCreateOTTSuccessfulEventData">OnCreateOTTSuccessfulEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnCreateOTTSuccessfulEventData.
Emitted when the One-Time Token is successfully created.</p>
</dd>
<dt><a href="#OnCreateOTTErrorEventData">OnCreateOTTErrorEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnCreateOTTErrorEventData.
Emitted when OTT creation fails. The error details are in the <code>data</code> payload.</p>
</dd>
<dt><a href="#OnUnavailableEventData">OnUnavailableEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnUnavailableEventData.
Emitted when the wallet is not available on the current device or browser.</p>
</dd>
<dt><a href="#OnErrorEventData">OnErrorEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnErrorEventData.
Emitted when an error occurs during wallet operation, including configuration issues, service type mismatches, and OTT creation failures.</p>
</dd>
<dt><a href="#OnLoadedEventData">OnLoadedEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnLoadedEventData.
Emitted when the wallet button has been loaded and rendered in the DOM.
No payload — the specific wallet type is determined by the concrete button class
(<a href="#ApplePayOpenWalletButton">ApplePayOpenWalletButton</a> or <a href="#GooglePayOpenWalletButton">GooglePayOpenWalletButton</a>).</p>
</dd>
<dt><a href="#OnCancelEventData">OnCancelEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnCancelEventData.
Emitted when the wallet checkout is cancelled or closed by the user. No payload data.</p>
</dd>
<dt><a href="#OnShippingAddressChangeEventData">OnShippingAddressChangeEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingAddressChangeEventData.
Emitted when the customer selects or updates their shipping address in the wallet payment sheet.
This event is also emitted when the payment sheet first opens (INITIALIZE) with the initial shipping address, if present in the User&#39;s wallet.</p>
<p>If no handler is registered for this event, the SDK auto-accepts with the current transaction data.</p>
</dd>
<dt><a href="#OnShippingAddressChangeEventResponse">OnShippingAddressChangeEventResponse</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingAddressChangeEventResponse.
Returned by the merchant&#39;s <code>onShippingAddressChange</code> handler.</p>
</dd>
<dt><a href="#OnShippingOptionChangeEventData">OnShippingOptionChangeEventData</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingOptionChangeEventData.
Emitted when the customer selects a shipping option in the wallet payment sheet.</p>
<p>If no handler is registered for this event, the SDK auto-accepts with the current transaction data.</p>
</dd>
<dt><a href="#OnShippingOptionChangeEventResponse">OnShippingOptionChangeEventResponse</a> : <code>object</code></dt>
<dd><p>Interface for OnShippingOptionChangeEventResponse.
Returned by the merchant&#39;s <code>onShippingOptionsChange</code> handler.</p>
</dd>
<dt><a href="#IApplePayShippingOption">IApplePayShippingOption</a> : <code>object</code></dt>
<dd><p>Interface for IApplePayShippingOption.
Used for shipping options in Apple Pay wallets.</p>
</dd>
<dt><a href="#IGooglePayShippingOption">IGooglePayShippingOption</a> : <code>object</code></dt>
<dd><p>Interface for IGooglePayShippingOption.
Used for shipping options in Google Pay wallets.</p>
</dd>
</dl>

<a name="ApplePayOpenWalletMeta" id="ApplePayOpenWalletMeta" href="#ApplePayOpenWalletMeta">&nbsp;</a>

## ApplePayOpenWalletMeta : <code>object</code>
Interface for Apple Pay-specific metadata.

For further information about ApplePay Capabilities refer to [the documentation](https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/4440085-applepaycapabilities).
Apple will determine if the device has an ApplePay wallet available and at least one active payment.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| amount | <code>number</code> | The payment amount. |
| currency | <code>string</code> | The ISO 4217 currency code. |
| country | <code>string</code> | The ISO 3166-1 alpha-2 country code. |
| amount_label | <code>string</code> | Label shown next to the total amount (e.g. `'TOTAL'`). Used in the Apple Pay payment sheet. |
| [request_shipping] | <code>boolean</code> | Enable shipping address collection in the Apple Pay sheet. |
| [shipping_options] | [<code>Array.&lt;IApplePayShippingOption&gt;</code>](#IApplePayShippingOption) | Array of available shipping options. The first item is used as the default selected option. Requires `request_shipping` to be `true`. |
| [show_billing_address] | <code>boolean</code> | Show billing address fields in the Apple Pay sheet. |
| store_name | <code>string</code> | The merchant's store name displayed during payment. |
| [apple_pay_capabilities] | <code>Array.&lt;(&#x27;credentials\_available&#x27;\|&#x27;credentials\_status\_unknown&#x27;\|&#x27;credentials\_unavailable&#x27;)&gt;</code> | Device capabilities needed for the wallet button to be available. |
| [merchant_capabilities] | <code>Array.&lt;(&#x27;supports3DS&#x27;\|&#x27;supportsEMV&#x27;\|&#x27;supportsCredit&#x27;\|&#x27;supportsDebit&#x27;)&gt;</code> | Array of merchant capabilities influencing the transaction processing features available. |
| [supported_networks] | <code>Array.&lt;(&#x27;visa&#x27;\|&#x27;masterCard&#x27;\|&#x27;amex&#x27;\|&#x27;chinaUnionPay&#x27;\|&#x27;discover&#x27;\|&#x27;interac&#x27;\|&#x27;jcb&#x27;\|&#x27;privateLabel&#x27;)&gt;</code> | List of payment networks supported for Apple Pay transactions. |
| [required_billing_contact_fields] | <code>Array.&lt;(&#x27;email&#x27;\|&#x27;name&#x27;\|&#x27;phone&#x27;\|&#x27;postalAddress&#x27;)&gt;</code> | Contact fields required from the user for billing purposes. Phone and email are currently not returned by Apple. |
| [required_shipping_contact_fields] | <code>Array.&lt;(&#x27;email&#x27;\|&#x27;phone&#x27;\|&#x27;postalAddress&#x27;\|&#x27;name&#x27;)&gt;</code> | Shipping contact fields required to complete the transaction. Include `'postalAddress'` to show address fields in the Apple Pay sheet. Required handling of onShippingAddressChange callback. |
| [supported_countries] | <code>Array.&lt;string&gt;</code> | List of countries where Apple Pay is supported by the merchant. |
| [shipping_editing_mode] | <code>&#x27;available&#x27;</code> \| <code>&#x27;store\_pickup&#x27;</code> | `'available'` for editable shipping, `'store_pickup'` for non-editable. |
| [style] | <code>object</code> | Styling configuration for the Apple Pay button. |
| [style.button_type] | <code>ApplePayButtonType</code> | The type of Apple Pay button (e.g. `'buy'`, `'donate'`, `'plain'`). |
| [style.button_style] | <code>ApplePayButtonStyle</code> | The style of the Apple Pay button (`'black'`, `'white'`, `'white-outline'`). |

<a name="GooglePayOpenWalletMeta" id="GooglePayOpenWalletMeta" href="#GooglePayOpenWalletMeta">&nbsp;</a>

## GooglePayOpenWalletMeta : <code>object</code>
Interface for Google Pay-specific metadata.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| amount | <code>number</code> | The payment amount. |
| currency | <code>string</code> | The ISO 4217 currency code. |
| country | <code>string</code> | The ISO 3166-1 alpha-2 country code. |
| [amount_label] | <code>string</code> | Label shown next to the total amount. |
| [merchant_name] | <code>string</code> | Display name for the merchant in the Google Pay sheet. |
| [request_shipping] | <code>boolean</code> | Enable shipping address collection. |
| [shipping_options] | [<code>Array.&lt;IGooglePayShippingOption&gt;</code>](#IGooglePayShippingOption) | Array of available shipping options. The first item is used as the default selected option. Requires `request_shipping` to be `true`. |
| [show_billing_address] | <code>boolean</code> | Show billing address fields. |
| [card_config] | <code>object</code> | Google Pay card configuration for custom auth methods, card networks, and tokenization. |
| [style] | <code>object</code> | Styling configuration for the Google Pay button. |
| [style.button_type] | <code>GooglePayButtonType</code> | The type of Google Pay button (`'book'`, `'buy'`, `'checkout'`, `'donate'`, `'order'`, `'pay'`, `'plain'`, `'subscribe'`). |
| [style.button_color] | <code>GooglePayButtonColor</code> | The color of the Google Pay button (`'default'`, `'black'`, `'white'`). |
| [style.button_size_mode] | <code>GooglePayButtonSizeMode</code> | The size mode (`'static'`, `'fill'`). |

<a name="OnClickEventData" id="OnClickEventData" href="#OnClickEventData">&nbsp;</a>

## OnClickEventData : <code>object</code>
Interface for OnClickEventData.
Emitted when the wallet button is clicked.

The merchant's `onClick` handler controls the payment flow via its return value:
- Return `void` / `undefined` to continue normally.
- Return `false` to abort the payment flow.
- Return a `Promise<void>` to defer the wallet sheet until the promise resolves.
- Return a `Promise<boolean>` — if it resolves to `false`, the flow is aborted.
- Throwing an error (sync or async) also aborts the flow.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'onClick'`. |

<a name="OnCreateOTTSuccessfulEventData" id="OnCreateOTTSuccessfulEventData" href="#OnCreateOTTSuccessfulEventData">&nbsp;</a>

## OnCreateOTTSuccessfulEventData : <code>object</code>
Interface for OnCreateOTTSuccessfulEventData.
Emitted when the One-Time Token is successfully created.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'success'`. |
| [data] | <code>object</code> | OTT success payload. |
| data.token | <code>object</code> | The created OTT response. |
| data.token.temp_token | <code>string</code> | The temporary one-time token string. |
| data.token.token_type | [<code>TOKEN\_TYPE</code>](#TOKEN_TYPE) | The type of the token. `TOKEN_TYPE.CARD` for FPAN (Google Pay only), `TOKEN_TYPE.CARD_SCHEME_TOKEN` for DPAN (Apple Pay & Google Pay). |
| data.amount | <code>number</code> | The payment amount. |
| [data.shipping] | <code>object</code> | The shipping address and contact information, if provided. |
| [data.shipping.method] | <code>string</code> | The shipping method. |
| [data.shipping.options] | <code>Array.&lt;(IApplePayShippingOption\|IGooglePayShippingOption)&gt;</code> | The selected shipping options. |
| [data.shipping.address_line1] | <code>string</code> | Shipping address line 1. |
| [data.shipping.address_line2] | <code>string</code> | Shipping address line 2. |
| [data.shipping.address_city] | <code>string</code> | Shipping address city. |
| [data.shipping.address_postcode] | <code>string</code> | Shipping address postal code. |
| [data.shipping.address_state] | <code>string</code> | Shipping address state or province. |
| [data.shipping.address_country] | <code>string</code> | Shipping address country code. |
| [data.shipping.address_company] | <code>string</code> | Shipping company name. |
| [data.shipping.address_origin_postcode] | <code>string</code> | Origin postal code. |
| [data.shipping.contact] | <code>object</code> | Shipping contact information. |
| [data.shipping.contact.first_name] | <code>string</code> | Contact first name. |
| [data.shipping.contact.last_name] | <code>string</code> | Contact last name. |
| [data.shipping.contact.email] | <code>string</code> | Contact email address. |
| [data.shipping.contact.phone] | <code>string</code> | Contact phone number. |
| [data.shipping.contact.phone2] | <code>string</code> | Contact secondary phone number. |
| [data.billing] | <code>object</code> | The billing address, if provided. |
| data.billing.address_line1 | <code>string</code> | Billing address line 1. |
| data.billing.address_line2 | <code>string</code> | Billing address line 2. |
| data.billing.address_country | <code>string</code> | Billing address country code. |
| data.billing.address_city | <code>string</code> | Billing address city. |
| data.billing.address_postcode | <code>string</code> | Billing address postal code. |
| data.billing.address_state | <code>string</code> | Billing address state or province. |

<a name="OnCreateOTTErrorEventData" id="OnCreateOTTErrorEventData" href="#OnCreateOTTErrorEventData">&nbsp;</a>

## OnCreateOTTErrorEventData : <code>object</code>
Interface for OnCreateOTTErrorEventData.
Emitted when OTT creation fails. The error details are in the `data` payload.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'error'`. |
| [data] | <code>object</code> | Error details payload. |
| [data.message] | <code>string</code> | Error message. |
| [data.code] | <code>string</code> | Error code. |

<a name="OnUnavailableEventData" id="OnUnavailableEventData" href="#OnUnavailableEventData">&nbsp;</a>

## OnUnavailableEventData : <code>object</code>
Interface for OnUnavailableEventData.
Emitted when the wallet is not available on the current device or browser.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'unavailable'`. |
| [data] | <code>object</code> | Unavailability details payload. |
| data.reason | <code>string</code> | A human-readable reason why the wallet is unavailable. |
| [data.details] | <code>object</code> | Additional details about the unavailability. |
| data.details.service_id | <code>string</code> | The service ID that was checked. |

<a name="OnErrorEventData" id="OnErrorEventData" href="#OnErrorEventData">&nbsp;</a>

## OnErrorEventData : <code>object</code>
Interface for OnErrorEventData.
Emitted when an error occurs during wallet operation, including configuration issues, service type mismatches, and OTT creation failures.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'error'`. |
| [data] | <code>object</code> | Error payload. |
| data.error | <code>Error</code> | The Error object describing what went wrong. |
| [data.context] | <code>object</code> | Context about the error. |
| [data.context.operation] | [<code>ERROR\_OPERATION</code>](#ERROR_OPERATION) | The operation that failed. See [ERROR_OPERATION](#ERROR_OPERATION) enum for possible values. |

<a name="OnLoadedEventData" id="OnLoadedEventData" href="#OnLoadedEventData">&nbsp;</a>

## OnLoadedEventData : <code>object</code>
Interface for OnLoadedEventData.
Emitted when the wallet button has been loaded and rendered in the DOM.
No payload — the specific wallet type is determined by the concrete button class
([ApplePayOpenWalletButton](#ApplePayOpenWalletButton) or [GooglePayOpenWalletButton](#GooglePayOpenWalletButton)).

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'loaded'`. |

<a name="OnCancelEventData" id="OnCancelEventData" href="#OnCancelEventData">&nbsp;</a>

## OnCancelEventData : <code>object</code>
Interface for OnCancelEventData.
Emitted when the wallet checkout is cancelled or closed by the user. No payload data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'checkoutClose'`. |

<a name="OnShippingAddressChangeEventData" id="OnShippingAddressChangeEventData" href="#OnShippingAddressChangeEventData">&nbsp;</a>

## OnShippingAddressChangeEventData : <code>object</code>
Interface for OnShippingAddressChangeEventData.
Emitted when the customer selects or updates their shipping address in the wallet payment sheet.
This event is also emitted when the payment sheet first opens (INITIALIZE) with the initial shipping address, if present in the User's wallet.

If no handler is registered for this event, the SDK auto-accepts with the current transaction data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'onShippingAddressChange'`. |
| [data] | <code>object</code> | Shipping address data. |
| [data.address_city] | <code>string</code> | Shipping address city. |
| [data.address_state] | <code>string</code> | Shipping address state. |
| [data.address_postcode] | <code>string</code> | Shipping address postal code. |
| [data.address_country] | <code>string</code> | Shipping address country code. |
| [data.address_line1] | <code>string</code> | Apple Pay only - Shipping address line 1. |
| [data.address_line2] | <code>string</code> | Apple Pay only - Shipping address line 2. |
| [data.contact.phone] | <code>string</code> | Apple Pay only - Shipping contact phone. |
| [data.contact.email] | <code>string</code> | Apple Pay only - Shipping contact email. |
| [data.contact.first_name] | <code>string</code> | Apple Pay only - Shipping contact first name. |
| [data.contact.last_name] | <code>string</code> | Apple Pay only - Shipping contact last name. |

<a name="OnShippingAddressChangeEventResponse" id="OnShippingAddressChangeEventResponse" href="#OnShippingAddressChangeEventResponse">&nbsp;</a>

## OnShippingAddressChangeEventResponse : <code>object</code>
Interface for OnShippingAddressChangeEventResponse.
Returned by the merchant's `onShippingAddressChange` handler.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [amount] | <code>number</code> | Updated payment amount based on the new shipping address. |
| [shipping_options] | <code>Array.&lt;(IApplePayShippingOption\|IGooglePayShippingOption)&gt;</code> | Updated list of available shipping options. The first item is used as the default selected option. |
| [error] | <code>object</code> | Error object to display in the wallet payment sheet if the address is invalid. |
| error.code | <code>string</code> | Error code. Possible values: `'address_error'`, `'country_error'`, `'state_error'`, `'zip_error'`, `'shipping_contact_invalid'`, `'billing_contact_invalid'`. |
| [error.field] | <code>string</code> | Apple Pay only - The specific field that caused the error. Possible values: `'phone'`, `'email'`, `'name'`, `'phonetic_name'`, `'address_lines'`, `'locality'`, `'postal_code'`, `'administrative_area'`, `'country'`, `'country_code'`. |
| [error.message] | <code>string</code> | A human-readable error message to display to the customer. |

<a name="OnShippingOptionChangeEventData" id="OnShippingOptionChangeEventData" href="#OnShippingOptionChangeEventData">&nbsp;</a>

## OnShippingOptionChangeEventData : <code>object</code>
Interface for OnShippingOptionChangeEventData.
Emitted when the customer selects a shipping option in the wallet payment sheet.

If no handler is registered for this event, the SDK auto-accepts with the current transaction data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>string</code> | Always `'onShippingOptionsChange'`. |
| [data] | <code>object</code> | Shipping option data. |
| [data.shipping_option_id] | <code>string</code> | Selected shipping option ID. |
| [data.label] | <code>string</code> | Selected shipping option label. |
| [data.detail] | <code>string</code> | Selected shipping option detail. |
| [data.amount] | <code>string</code> | Apple Pay only - Selected shipping option amount. |

<a name="OnShippingOptionChangeEventResponse" id="OnShippingOptionChangeEventResponse" href="#OnShippingOptionChangeEventResponse">&nbsp;</a>

## OnShippingOptionChangeEventResponse : <code>object</code>
Interface for OnShippingOptionChangeEventResponse.
Returned by the merchant's `onShippingOptionsChange` handler.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [amount] | <code>number</code> | Updated total payment amount based on the selected shipping option. |
| [error] | <code>object</code> | Error object to display if the shipping option is invalid. |
| error.code | <code>string</code> | Error code. Possible values: `'method_unavailable'`, `'store_unavailable'`. |
| [error.message] | <code>string</code> | A human-readable error message. |

<a name="IApplePayShippingOption" id="IApplePayShippingOption" href="#IApplePayShippingOption">&nbsp;</a>

## IApplePayShippingOption : <code>object</code>
Interface for IApplePayShippingOption.
Used for shipping options in Apple Pay wallets.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| id | <code>string</code> | Unique identifier for the shipping option. |
| label | <code>string</code> | Display name for the shipping option. |
| amount | <code>number</code> | Shipping cost amount. |
| [detail] | <code>string</code> | Optional description or detail text. |
| [date_components_range] | <code>object</code> | Apple Pay only - Delivery date range estimate. |
| [date_components_range.start_date_components] | <code>object</code> | Start date for the delivery estimate. |
| [date_components_range.start_date_components.years] | <code>number</code> | Years from now. |
| [date_components_range.start_date_components.months] | <code>number</code> | Months from now. |
| [date_components_range.start_date_components.days] | <code>number</code> | Days from now. |
| [date_components_range.start_date_components.hours] | <code>number</code> | Hours from now. |
| [date_components_range.end_date_components] | <code>object</code> | End date for the delivery estimate. |
| [date_components_range.end_date_components.years] | <code>number</code> | Years from now. |
| [date_components_range.end_date_components.months] | <code>number</code> | Months from now. |
| [date_components_range.end_date_components.days] | <code>number</code> | Days from now. |
| [date_components_range.end_date_components.hours] | <code>number</code> | Hours from now. |

<a name="IGooglePayShippingOption" id="IGooglePayShippingOption" href="#IGooglePayShippingOption">&nbsp;</a>

## IGooglePayShippingOption : <code>object</code>
Interface for IGooglePayShippingOption.
Used for shipping options in Google Pay wallets.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| id | <code>string</code> | Unique identifier for the shipping option. |
| label | <code>string</code> | Display name for the shipping option. |
| [detail] | <code>string</code> | Optional description or detail text. |
| [type] | <code>&#x27;ELECTRONIC&#x27;</code> \| <code>&#x27;GROUND&#x27;</code> \| <code>&#x27;NOT\_SHIPPED&#x27;</code> \| <code>&#x27;OVERNIGHT&#x27;</code> \| <code>&#x27;PICKUP&#x27;</code> \| <code>&#x27;PRIORITY&#x27;</code> \| <code>&#x27;SAME\_DAY&#x27;</code> | The shipping type. |

<a name="ApplePayOpenWalletButton" id="ApplePayOpenWalletButton" href="#ApplePayOpenWalletButton">&nbsp;</a>

## ApplePayOpenWalletButton ⇐ [<code>OpenWalletButtons</code>](#OpenWalletButtons)
Apple Pay wallet button that creates One-Time Tokens (OTT) via Apple Pay.

Provides a fully typed Apple Pay integration with Apple Pay-specific metadata
and validates that the service configuration corresponds to an Apple Pay service.
On `load()`, the button fetches the service configuration and raises an error via `onError`
if the service type does not match Apple Pay.

**Kind**: global class  
**Extends**: [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

* [ApplePayOpenWalletButton](#ApplePayOpenWalletButton) ⇐ [<code>OpenWalletButtons</code>](#OpenWalletButtons)
    * [new ApplePayOpenWalletButton(selector, publicKeyOrAccessToken, serviceId, meta)](#new_ApplePayOpenWalletButton_new)
    * [.load()](#OpenWalletButtons+load)
    * [.setEnv(env, [alias])](#OpenWalletButtons+setEnv)
    * [.setMeta(meta)](#OpenWalletButtons+setMeta)
    * [.destroy()](#OpenWalletButtons+destroy)
    * [.onClick(handler)](#OpenWalletButtons+onClick)
    * [.onSuccess(handler)](#OpenWalletButtons+onSuccess)
    * [.onUnavailable(handler)](#OpenWalletButtons+onUnavailable)
    * [.onError(handler)](#OpenWalletButtons+onError)
    * [.onCancel(handler)](#OpenWalletButtons+onCancel)
    * [.onLoaded(handler)](#OpenWalletButtons+onLoaded)
    * [.onShippingAddressChange(handler)](#OpenWalletButtons+onShippingAddressChange)
    * [.onShippingOptionsChange(handler)](#OpenWalletButtons+onShippingOptionsChange)

<a name="new_ApplePayOpenWalletButton_new" id="new_ApplePayOpenWalletButton_new" href="#new_ApplePayOpenWalletButton_new">&nbsp;</a>

### new ApplePayOpenWalletButton(selector, publicKeyOrAccessToken, serviceId, meta)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | CSS selector of the HTML element that will contain the Apple Pay button. |
| publicKeyOrAccessToken | <code>string</code> | Public key or access token for API authentication. |
| serviceId | <code>string</code> | The Apple Pay service ID configured in PayDock dashboard. |
| meta | [<code>ApplePayOpenWalletMeta</code>](#ApplePayOpenWalletMeta) | Apple Pay-specific metadata (amount, currency, country, amount_label, store_name, style, apple_pay_capabilities, etc.). |

**Example**  
```js
const button = new ApplePayOpenWalletButton(
  '#wallet-container',
  publicKeyOrAccessToken,
  serviceId,
  {
    amount: 100,
    currency: 'AUD',
    country: 'AU',
    amount_label: 'TOTAL',
    store_name: 'My Store',
    apple_pay_capabilities: ['credentials_available'],
  },
);
button.setEnv('sandbox');
button.onSuccess((data) => console.log('OTT:', data.token));
button.onError((error) => console.error('Error:', error));
button.load();
```
<a name="OpenWalletButtons+load" id="OpenWalletButtons+load" href="#OpenWalletButtons+load">&nbsp;</a>

### applePayOpenWalletButton.load()
Loads and initializes the wallet button based on the service configuration.
This method fetches the wallet service configuration, validates that the service
type matches the expected wallet, and creates the appropriate wallet service instance.
Bear in mind that you must call this method after setting up all event handlers.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  
**Example**  
```js
button.onClick((data) => { ... });
button.onSuccess((data) => { ... });
button.onError((error) => { ... });
button.load();
```
<a name="OpenWalletButtons+setEnv" id="OpenWalletButtons+setEnv" href="#OpenWalletButtons+setEnv">&nbsp;</a>

### applePayOpenWalletButton.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com
Bear in mind that you must set an environment before calling `button.load()`.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | The target environment: `'sandbox'` or `'production'`. |
| [alias] | <code>string</code> | Own domain alias. |

**Example**  
```js
button.setEnv('production', 'paydock.com');
```
<a name="OpenWalletButtons+setMeta" id="OpenWalletButtons+setMeta" href="#OpenWalletButtons+setMeta">&nbsp;</a>

### applePayOpenWalletButton.setMeta(meta)
Updates the wallet metadata after initialization.
Use this when order information changes (e.g. amount, currency) after the button has been rendered.
Bear in mind that this must be called before the next payment attempt takes effect.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>ApplePayOpenWalletMeta</code>](#ApplePayOpenWalletMeta) \| [<code>GooglePayOpenWalletMeta</code>](#GooglePayOpenWalletMeta) | The updated metadata object. The concrete type depends on the button class. |

**Example**  
```js
button.setMeta({ ...meta, amount: 29.99 });
```
<a name="OpenWalletButtons+destroy" id="OpenWalletButtons+destroy" href="#OpenWalletButtons+destroy">&nbsp;</a>

### applePayOpenWalletButton.destroy()
Removes the wallet button from the DOM and cleans up resources.
Call this method when the wallet button is no longer needed (e.g. navigating away from the payment page).

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  
**Example**  
```js
button.destroy();
```
<a name="OpenWalletButtons+onClick" id="OpenWalletButtons+onClick" href="#OpenWalletButtons+onClick">&nbsp;</a>

### applePayOpenWalletButton.onClick(handler)
Registers a callback function to be invoked when the wallet button gets clicked.
The handler controls the wallet payment flow via its return value:

- Return `void` (or nothing) to continue the payment flow normally.
- Return `false` to abort the payment flow.
- Return a `Promise<void>` to defer the wallet sheet until the promise resolves.
- Return a `Promise<boolean>` — if it resolves to `false`, the flow is aborted.
- Throwing an error (sync or async) also aborts the flow.

Both synchronous and asynchronous (async) handlers are supported.

**Note:** this callback may be called multiple times as the customer closes the payment
checkout and re-clicks the button.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnClickCallback</code>](#OnClickCallback) | Function to be called when the wallet button is clicked. |

**Example**  
```js
// Synchronous usage — continue normally
button.onClick((event) => {
  performValidationLogic();
});
```
**Example**  
```js
// Synchronous abort — return false to cancel the payment
button.onClick((event) => {
  if (!isOrderValid()) return false;
});
```
**Example**  
```js
// Asynchronous usage — defer wallet sheet until the promise resolves
button.onClick(async (event) => {
  await fetch('/validate-order').then(res => res.json());
});
```
<a name="OpenWalletButtons+onSuccess" id="OpenWalletButtons+onSuccess" href="#OpenWalletButtons+onSuccess">&nbsp;</a>

### applePayOpenWalletButton.onSuccess(handler)
Registers a callback function to be invoked when the OTT (One-Time Token) creation was successful.
Both synchronous and asynchronous (async) handlers are supported.

**Important:** A handler is required. Do not perform thread blocking operations in callback such as `window.alert()` calls.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnSuccessCallback</code>](#OnSuccessCallback) | Function to be called when the OTT creation was successful. |

**Example**  
```js
button.onSuccess((event) => {
  console.log('OTT created:', event.data.token.temp_token);
  console.log('Amount:', event.data.amount);
});
```
**Example**  
```js
// Async handler
button.onSuccess(async (event) => {
  await submitTokenToServer(event.data.token.temp_token);
});
```
<a name="OpenWalletButtons+onUnavailable" id="OpenWalletButtons+onUnavailable" href="#OpenWalletButtons+onUnavailable">&nbsp;</a>

### applePayOpenWalletButton.onUnavailable(handler)
Registers a callback function to be invoked when the wallet is not available in the current context.
This can happen when the wallet service is not supported on the current device or browser.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnUnavailableCallback</code>](#OnUnavailableCallback) | Function to be called when the wallet is not available in the current context. |

**Example**  
```js
button.onUnavailable((event) => {
  console.log('Wallet not available:', event.data.reason);
});
```
<a name="OpenWalletButtons+onError" id="OpenWalletButtons+onError" href="#OpenWalletButtons+onError">&nbsp;</a>

### applePayOpenWalletButton.onError(handler)
Registers a callback function to be invoked when an error occurs during wallet operation.
This includes configuration issues, validation errors, and OTT creation failures.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when the wallet has an error. |

**Example**  
```js
button.onError((event) => {
  console.error('Wallet error:', event.data.error.message);
  console.log('Context:', event.data.context);
});
```
<a name="OpenWalletButtons+onCancel" id="OpenWalletButtons+onCancel" href="#OpenWalletButtons+onCancel">&nbsp;</a>

### applePayOpenWalletButton.onCancel(handler)
Registers a callback function to be invoked when the wallet checkout is cancelled or closed by the user.
This event is triggered when the user dismisses the wallet payment interface without completing the transaction.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnCancelCallback</code>](#OnCancelCallback) | Function to be called when the wallet checkout is cancelled. |

**Example**  
```js
button.onCancel((event) => {
  console.log('Wallet checkout cancelled', event);
});
```
<a name="OpenWalletButtons+onLoaded" id="OpenWalletButtons+onLoaded" href="#OpenWalletButtons+onLoaded">&nbsp;</a>

### applePayOpenWalletButton.onLoaded(handler)
Registers a callback function to be invoked when the wallet button has been loaded and rendered in the DOM.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>function</code> | Function to be called when the wallet button is loaded. |

**Example**  
```js
button.onLoaded((event) => {
  console.log('Wallet button loaded');
});
```
<a name="OpenWalletButtons+onShippingAddressChange" id="OpenWalletButtons+onShippingAddressChange" href="#OpenWalletButtons+onShippingAddressChange">&nbsp;</a>

### applePayOpenWalletButton.onShippingAddressChange(handler)
Registers a callback for when the customer selects or updates their shipping address.
Use this method to listen for shipping address selection or input from customer when shipping is enabled.
The event handler should return updated payment information including the new amount and
available shipping options based on the selected address.
Both synchronous and asynchronous (async) handlers are supported.

In case of an address validation error, include the `error` field in the response
to display an appropriate error in the wallet payment sheet.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnShippingAddressChangeCallback</code>](#OnShippingAddressChangeCallback) | Function to be called when the shipping address data is updated. |

**Example**  
```js
// Async handler
button.onShippingAddressChange(async (data) => {
  const response = await fetch('https://your-server.com/update-shipping-address', {
    method: 'POST',
    body: JSON.stringify(data),
  });
  const result = await response.json();
  return {
    amount: result.newAmount,
    shipping_options: result.availableShippingOptions,
  };
});
```
**Example**  
```js
// Sync handler
button.onShippingAddressChange((data) => {
  return {
    amount: calculateShipping(data.data.address_country),
    shipping_options: getOptionsForCountry(data.data.address_country),
  };
});
```
<a name="OpenWalletButtons+onShippingOptionsChange" id="OpenWalletButtons+onShippingOptionsChange" href="#OpenWalletButtons+onShippingOptionsChange">&nbsp;</a>

### applePayOpenWalletButton.onShippingOptionsChange(handler)
Registers a callback for when the customer selects a shipping option.
Use this method to listen for shipping option selection from customer when shipping is enabled.
The event handler should return the updated payment amount based on the selected shipping option.
Both synchronous and asynchronous (async) handlers are supported.

**Kind**: instance method of [<code>ApplePayOpenWalletButton</code>](#ApplePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnShippingOptionsChangeCallback</code>](#OnShippingOptionsChangeCallback) | Function to be called when the shipping options data is updated. |

**Example**  
```js
// Async handler
button.onShippingOptionsChange(async (data) => {
  const response = await fetch('https://your-server.com/update-shipping-option', {
    method: 'POST',
    body: JSON.stringify({ shipping_option_id: data.data.shipping_option_id }),
  });
  const result = await response.json();
  return {
    amount: result.newTotalAmount,
  };
});
```
**Example**  
```js
// Sync handler
button.onShippingOptionsChange((data) => {
  return {
    amount: lookupShippingCost(data.data.shipping_option_id),
  };
});
```
<a name="GooglePayOpenWalletButton" id="GooglePayOpenWalletButton" href="#GooglePayOpenWalletButton">&nbsp;</a>

## GooglePayOpenWalletButton ⇐ [<code>OpenWalletButtons</code>](#OpenWalletButtons)
Google Pay wallet button that creates One-Time Tokens (OTT) via Google Pay.

Provides a fully typed Google Pay integration with Google Pay-specific metadata
and validates that the service configuration corresponds to a Google Pay service.
On `load()`, the button fetches the service configuration and raises an error via `onError`
if the service type does not match Google Pay.

**Kind**: global class  
**Extends**: [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

* [GooglePayOpenWalletButton](#GooglePayOpenWalletButton) ⇐ [<code>OpenWalletButtons</code>](#OpenWalletButtons)
    * [new GooglePayOpenWalletButton(selector, publicKeyOrAccessToken, serviceId, meta)](#new_GooglePayOpenWalletButton_new)
    * [.load()](#OpenWalletButtons+load)
    * [.setEnv(env, [alias])](#OpenWalletButtons+setEnv)
    * [.setMeta(meta)](#OpenWalletButtons+setMeta)
    * [.destroy()](#OpenWalletButtons+destroy)
    * [.onClick(handler)](#OpenWalletButtons+onClick)
    * [.onSuccess(handler)](#OpenWalletButtons+onSuccess)
    * [.onUnavailable(handler)](#OpenWalletButtons+onUnavailable)
    * [.onError(handler)](#OpenWalletButtons+onError)
    * [.onCancel(handler)](#OpenWalletButtons+onCancel)
    * [.onLoaded(handler)](#OpenWalletButtons+onLoaded)
    * [.onShippingAddressChange(handler)](#OpenWalletButtons+onShippingAddressChange)
    * [.onShippingOptionsChange(handler)](#OpenWalletButtons+onShippingOptionsChange)

<a name="new_GooglePayOpenWalletButton_new" id="new_GooglePayOpenWalletButton_new" href="#new_GooglePayOpenWalletButton_new">&nbsp;</a>

### new GooglePayOpenWalletButton(selector, publicKeyOrAccessToken, serviceId, meta)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | CSS selector of the HTML element that will contain the Google Pay button. |
| publicKeyOrAccessToken | <code>string</code> | Public key or access token for API authentication. |
| serviceId | <code>string</code> | The Google Pay service ID configured in PayDock dashboard. |
| meta | [<code>GooglePayOpenWalletMeta</code>](#GooglePayOpenWalletMeta) | Google Pay-specific metadata (amount, currency, country, card_config, merchant_name, style, etc.). |

**Example**  
```js
const button = new GooglePayOpenWalletButton(
  '#wallet-container',
  publicKeyOrAccessToken,
  serviceId,
  {
    amount: 100,
    currency: 'AUD',
    country: 'AU',
    merchant_name: 'Your Store',
  },
);
button.setEnv('sandbox');
button.onSuccess((data) => console.log('OTT:', data.token));
button.onError((error) => console.error('Error:', error));
button.load();
```
<a name="OpenWalletButtons+load" id="OpenWalletButtons+load" href="#OpenWalletButtons+load">&nbsp;</a>

### googlePayOpenWalletButton.load()
Loads and initializes the wallet button based on the service configuration.
This method fetches the wallet service configuration, validates that the service
type matches the expected wallet, and creates the appropriate wallet service instance.
Bear in mind that you must call this method after setting up all event handlers.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  
**Example**  
```js
button.onClick((data) => { ... });
button.onSuccess((data) => { ... });
button.onError((error) => { ... });
button.load();
```
<a name="OpenWalletButtons+setEnv" id="OpenWalletButtons+setEnv" href="#OpenWalletButtons+setEnv">&nbsp;</a>

### googlePayOpenWalletButton.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com
Bear in mind that you must set an environment before calling `button.load()`.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | The target environment: `'sandbox'` or `'production'`. |
| [alias] | <code>string</code> | Own domain alias. |

**Example**  
```js
button.setEnv('production', 'paydock.com');
```
<a name="OpenWalletButtons+setMeta" id="OpenWalletButtons+setMeta" href="#OpenWalletButtons+setMeta">&nbsp;</a>

### googlePayOpenWalletButton.setMeta(meta)
Updates the wallet metadata after initialization.
Use this when order information changes (e.g. amount, currency) after the button has been rendered.
Bear in mind that this must be called before the next payment attempt takes effect.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>ApplePayOpenWalletMeta</code>](#ApplePayOpenWalletMeta) \| [<code>GooglePayOpenWalletMeta</code>](#GooglePayOpenWalletMeta) | The updated metadata object. The concrete type depends on the button class. |

**Example**  
```js
button.setMeta({ ...meta, amount: 29.99 });
```
<a name="OpenWalletButtons+destroy" id="OpenWalletButtons+destroy" href="#OpenWalletButtons+destroy">&nbsp;</a>

### googlePayOpenWalletButton.destroy()
Removes the wallet button from the DOM and cleans up resources.
Call this method when the wallet button is no longer needed (e.g. navigating away from the payment page).

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  
**Example**  
```js
button.destroy();
```
<a name="OpenWalletButtons+onClick" id="OpenWalletButtons+onClick" href="#OpenWalletButtons+onClick">&nbsp;</a>

### googlePayOpenWalletButton.onClick(handler)
Registers a callback function to be invoked when the wallet button gets clicked.
The handler controls the wallet payment flow via its return value:

- Return `void` (or nothing) to continue the payment flow normally.
- Return `false` to abort the payment flow.
- Return a `Promise<void>` to defer the wallet sheet until the promise resolves.
- Return a `Promise<boolean>` — if it resolves to `false`, the flow is aborted.
- Throwing an error (sync or async) also aborts the flow.

Both synchronous and asynchronous (async) handlers are supported.

**Note:** this callback may be called multiple times as the customer closes the payment
checkout and re-clicks the button.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnClickCallback</code>](#OnClickCallback) | Function to be called when the wallet button is clicked. |

**Example**  
```js
// Synchronous usage — continue normally
button.onClick((event) => {
  performValidationLogic();
});
```
**Example**  
```js
// Synchronous abort — return false to cancel the payment
button.onClick((event) => {
  if (!isOrderValid()) return false;
});
```
**Example**  
```js
// Asynchronous usage — defer wallet sheet until the promise resolves
button.onClick(async (event) => {
  await fetch('/validate-order').then(res => res.json());
});
```
<a name="OpenWalletButtons+onSuccess" id="OpenWalletButtons+onSuccess" href="#OpenWalletButtons+onSuccess">&nbsp;</a>

### googlePayOpenWalletButton.onSuccess(handler)
Registers a callback function to be invoked when the OTT (One-Time Token) creation was successful.
Both synchronous and asynchronous (async) handlers are supported.

**Important:** A handler is required. Do not perform thread blocking operations in callback such as `window.alert()` calls.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnSuccessCallback</code>](#OnSuccessCallback) | Function to be called when the OTT creation was successful. |

**Example**  
```js
button.onSuccess((event) => {
  console.log('OTT created:', event.data.token.temp_token);
  console.log('Amount:', event.data.amount);
});
```
**Example**  
```js
// Async handler
button.onSuccess(async (event) => {
  await submitTokenToServer(event.data.token.temp_token);
});
```
<a name="OpenWalletButtons+onUnavailable" id="OpenWalletButtons+onUnavailable" href="#OpenWalletButtons+onUnavailable">&nbsp;</a>

### googlePayOpenWalletButton.onUnavailable(handler)
Registers a callback function to be invoked when the wallet is not available in the current context.
This can happen when the wallet service is not supported on the current device or browser.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnUnavailableCallback</code>](#OnUnavailableCallback) | Function to be called when the wallet is not available in the current context. |

**Example**  
```js
button.onUnavailable((event) => {
  console.log('Wallet not available:', event.data.reason);
});
```
<a name="OpenWalletButtons+onError" id="OpenWalletButtons+onError" href="#OpenWalletButtons+onError">&nbsp;</a>

### googlePayOpenWalletButton.onError(handler)
Registers a callback function to be invoked when an error occurs during wallet operation.
This includes configuration issues, validation errors, and OTT creation failures.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when the wallet has an error. |

**Example**  
```js
button.onError((event) => {
  console.error('Wallet error:', event.data.error.message);
  console.log('Context:', event.data.context);
});
```
<a name="OpenWalletButtons+onCancel" id="OpenWalletButtons+onCancel" href="#OpenWalletButtons+onCancel">&nbsp;</a>

### googlePayOpenWalletButton.onCancel(handler)
Registers a callback function to be invoked when the wallet checkout is cancelled or closed by the user.
This event is triggered when the user dismisses the wallet payment interface without completing the transaction.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnCancelCallback</code>](#OnCancelCallback) | Function to be called when the wallet checkout is cancelled. |

**Example**  
```js
button.onCancel((event) => {
  console.log('Wallet checkout cancelled', event);
});
```
<a name="OpenWalletButtons+onLoaded" id="OpenWalletButtons+onLoaded" href="#OpenWalletButtons+onLoaded">&nbsp;</a>

### googlePayOpenWalletButton.onLoaded(handler)
Registers a callback function to be invoked when the wallet button has been loaded and rendered in the DOM.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>function</code> | Function to be called when the wallet button is loaded. |

**Example**  
```js
button.onLoaded((event) => {
  console.log('Wallet button loaded');
});
```
<a name="OpenWalletButtons+onShippingAddressChange" id="OpenWalletButtons+onShippingAddressChange" href="#OpenWalletButtons+onShippingAddressChange">&nbsp;</a>

### googlePayOpenWalletButton.onShippingAddressChange(handler)
Registers a callback for when the customer selects or updates their shipping address.
Use this method to listen for shipping address selection or input from customer when shipping is enabled.
The event handler should return updated payment information including the new amount and
available shipping options based on the selected address.
Both synchronous and asynchronous (async) handlers are supported.

In case of an address validation error, include the `error` field in the response
to display an appropriate error in the wallet payment sheet.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnShippingAddressChangeCallback</code>](#OnShippingAddressChangeCallback) | Function to be called when the shipping address data is updated. |

**Example**  
```js
// Async handler
button.onShippingAddressChange(async (data) => {
  const response = await fetch('https://your-server.com/update-shipping-address', {
    method: 'POST',
    body: JSON.stringify(data),
  });
  const result = await response.json();
  return {
    amount: result.newAmount,
    shipping_options: result.availableShippingOptions,
  };
});
```
**Example**  
```js
// Sync handler
button.onShippingAddressChange((data) => {
  return {
    amount: calculateShipping(data.data.address_country),
    shipping_options: getOptionsForCountry(data.data.address_country),
  };
});
```
<a name="OpenWalletButtons+onShippingOptionsChange" id="OpenWalletButtons+onShippingOptionsChange" href="#OpenWalletButtons+onShippingOptionsChange">&nbsp;</a>

### googlePayOpenWalletButton.onShippingOptionsChange(handler)
Registers a callback for when the customer selects a shipping option.
Use this method to listen for shipping option selection from customer when shipping is enabled.
The event handler should return the updated payment amount based on the selected shipping option.
Both synchronous and asynchronous (async) handlers are supported.

**Kind**: instance method of [<code>GooglePayOpenWalletButton</code>](#GooglePayOpenWalletButton)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnShippingOptionsChangeCallback</code>](#OnShippingOptionsChangeCallback) | Function to be called when the shipping options data is updated. |

**Example**  
```js
// Async handler
button.onShippingOptionsChange(async (data) => {
  const response = await fetch('https://your-server.com/update-shipping-option', {
    method: 'POST',
    body: JSON.stringify({ shipping_option_id: data.data.shipping_option_id }),
  });
  const result = await response.json();
  return {
    amount: result.newTotalAmount,
  };
});
```
**Example**  
```js
// Sync handler
button.onShippingOptionsChange((data) => {
  return {
    amount: lookupShippingCost(data.data.shipping_option_id),
  };
});
```
<a name="OpenWalletButtons" id="OpenWalletButtons" href="#OpenWalletButtons">&nbsp;</a>

## *OpenWalletButtons*
Abstract base class for Open Wallet buttons. **Do not instantiate directly.**
Use [ApplePayOpenWalletButton](#ApplePayOpenWalletButton) or [GooglePayOpenWalletButton](#GooglePayOpenWalletButton) instead.

Use one of the concrete implementations instead:
- [ApplePayOpenWalletButton](#ApplePayOpenWalletButton) for Apple Pay integration
- [GooglePayOpenWalletButton](#GooglePayOpenWalletButton) for Google Pay integration

These subclasses inherit all event handlers and lifecycle methods documented below.

**Kind**: global abstract class  

* *[OpenWalletButtons](#OpenWalletButtons)*
    * *[.load()](#OpenWalletButtons+load)*
    * *[.setEnv(env, [alias])](#OpenWalletButtons+setEnv)*
    * *[.setMeta(meta)](#OpenWalletButtons+setMeta)*
    * *[.destroy()](#OpenWalletButtons+destroy)*
    * *[.onClick(handler)](#OpenWalletButtons+onClick)*
    * *[.onSuccess(handler)](#OpenWalletButtons+onSuccess)*
    * *[.onUnavailable(handler)](#OpenWalletButtons+onUnavailable)*
    * *[.onError(handler)](#OpenWalletButtons+onError)*
    * *[.onCancel(handler)](#OpenWalletButtons+onCancel)*
    * *[.onLoaded(handler)](#OpenWalletButtons+onLoaded)*
    * *[.onShippingAddressChange(handler)](#OpenWalletButtons+onShippingAddressChange)*
    * *[.onShippingOptionsChange(handler)](#OpenWalletButtons+onShippingOptionsChange)*

<a name="OpenWalletButtons+load" id="OpenWalletButtons+load" href="#OpenWalletButtons+load">&nbsp;</a>

### *openWalletButtons.load()*
Loads and initializes the wallet button based on the service configuration.
This method fetches the wallet service configuration, validates that the service
type matches the expected wallet, and creates the appropriate wallet service instance.
Bear in mind that you must call this method after setting up all event handlers.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  
**Example**  
```js
button.onClick((data) => { ... });
button.onSuccess((data) => { ... });
button.onError((error) => { ... });
button.load();
```
<a name="OpenWalletButtons+setEnv" id="OpenWalletButtons+setEnv" href="#OpenWalletButtons+setEnv">&nbsp;</a>

### *openWalletButtons.setEnv(env, [alias])*
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com
Bear in mind that you must set an environment before calling `button.load()`.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | The target environment: `'sandbox'` or `'production'`. |
| [alias] | <code>string</code> | Own domain alias. |

**Example**  
```js
button.setEnv('production', 'paydock.com');
```
<a name="OpenWalletButtons+setMeta" id="OpenWalletButtons+setMeta" href="#OpenWalletButtons+setMeta">&nbsp;</a>

### *openWalletButtons.setMeta(meta)*
Updates the wallet metadata after initialization.
Use this when order information changes (e.g. amount, currency) after the button has been rendered.
Bear in mind that this must be called before the next payment attempt takes effect.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| meta | [<code>ApplePayOpenWalletMeta</code>](#ApplePayOpenWalletMeta) \| [<code>GooglePayOpenWalletMeta</code>](#GooglePayOpenWalletMeta) | The updated metadata object. The concrete type depends on the button class. |

**Example**  
```js
button.setMeta({ ...meta, amount: 29.99 });
```
<a name="OpenWalletButtons+destroy" id="OpenWalletButtons+destroy" href="#OpenWalletButtons+destroy">&nbsp;</a>

### *openWalletButtons.destroy()*
Removes the wallet button from the DOM and cleans up resources.
Call this method when the wallet button is no longer needed (e.g. navigating away from the payment page).

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  
**Example**  
```js
button.destroy();
```
<a name="OpenWalletButtons+onClick" id="OpenWalletButtons+onClick" href="#OpenWalletButtons+onClick">&nbsp;</a>

### *openWalletButtons.onClick(handler)*
Registers a callback function to be invoked when the wallet button gets clicked.
The handler controls the wallet payment flow via its return value:

- Return `void` (or nothing) to continue the payment flow normally.
- Return `false` to abort the payment flow.
- Return a `Promise<void>` to defer the wallet sheet until the promise resolves.
- Return a `Promise<boolean>` — if it resolves to `false`, the flow is aborted.
- Throwing an error (sync or async) also aborts the flow.

Both synchronous and asynchronous (async) handlers are supported.

**Note:** this callback may be called multiple times as the customer closes the payment
checkout and re-clicks the button.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnClickCallback</code>](#OnClickCallback) | Function to be called when the wallet button is clicked. |

**Example**  
```js
// Synchronous usage — continue normally
button.onClick((event) => {
  performValidationLogic();
});
```
**Example**  
```js
// Synchronous abort — return false to cancel the payment
button.onClick((event) => {
  if (!isOrderValid()) return false;
});
```
**Example**  
```js
// Asynchronous usage — defer wallet sheet until the promise resolves
button.onClick(async (event) => {
  await fetch('/validate-order').then(res => res.json());
});
```
<a name="OpenWalletButtons+onSuccess" id="OpenWalletButtons+onSuccess" href="#OpenWalletButtons+onSuccess">&nbsp;</a>

### *openWalletButtons.onSuccess(handler)*
Registers a callback function to be invoked when the OTT (One-Time Token) creation was successful.
Both synchronous and asynchronous (async) handlers are supported.

**Important:** A handler is required. Do not perform thread blocking operations in callback such as `window.alert()` calls.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnSuccessCallback</code>](#OnSuccessCallback) | Function to be called when the OTT creation was successful. |

**Example**  
```js
button.onSuccess((event) => {
  console.log('OTT created:', event.data.token.temp_token);
  console.log('Amount:', event.data.amount);
});
```
**Example**  
```js
// Async handler
button.onSuccess(async (event) => {
  await submitTokenToServer(event.data.token.temp_token);
});
```
<a name="OpenWalletButtons+onUnavailable" id="OpenWalletButtons+onUnavailable" href="#OpenWalletButtons+onUnavailable">&nbsp;</a>

### *openWalletButtons.onUnavailable(handler)*
Registers a callback function to be invoked when the wallet is not available in the current context.
This can happen when the wallet service is not supported on the current device or browser.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnUnavailableCallback</code>](#OnUnavailableCallback) | Function to be called when the wallet is not available in the current context. |

**Example**  
```js
button.onUnavailable((event) => {
  console.log('Wallet not available:', event.data.reason);
});
```
<a name="OpenWalletButtons+onError" id="OpenWalletButtons+onError" href="#OpenWalletButtons+onError">&nbsp;</a>

### *openWalletButtons.onError(handler)*
Registers a callback function to be invoked when an error occurs during wallet operation.
This includes configuration issues, validation errors, and OTT creation failures.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when the wallet has an error. |

**Example**  
```js
button.onError((event) => {
  console.error('Wallet error:', event.data.error.message);
  console.log('Context:', event.data.context);
});
```
<a name="OpenWalletButtons+onCancel" id="OpenWalletButtons+onCancel" href="#OpenWalletButtons+onCancel">&nbsp;</a>

### *openWalletButtons.onCancel(handler)*
Registers a callback function to be invoked when the wallet checkout is cancelled or closed by the user.
This event is triggered when the user dismisses the wallet payment interface without completing the transaction.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnCancelCallback</code>](#OnCancelCallback) | Function to be called when the wallet checkout is cancelled. |

**Example**  
```js
button.onCancel((event) => {
  console.log('Wallet checkout cancelled', event);
});
```
<a name="OpenWalletButtons+onLoaded" id="OpenWalletButtons+onLoaded" href="#OpenWalletButtons+onLoaded">&nbsp;</a>

### *openWalletButtons.onLoaded(handler)*
Registers a callback function to be invoked when the wallet button has been loaded and rendered in the DOM.
Both synchronous and asynchronous (async) handlers are supported.

**Error handling:** If the handler throws (sync or async), the error is logged and swallowed
so that internal processing continues uninterrupted.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>function</code> | Function to be called when the wallet button is loaded. |

**Example**  
```js
button.onLoaded((event) => {
  console.log('Wallet button loaded');
});
```
<a name="OpenWalletButtons+onShippingAddressChange" id="OpenWalletButtons+onShippingAddressChange" href="#OpenWalletButtons+onShippingAddressChange">&nbsp;</a>

### *openWalletButtons.onShippingAddressChange(handler)*
Registers a callback for when the customer selects or updates their shipping address.
Use this method to listen for shipping address selection or input from customer when shipping is enabled.
The event handler should return updated payment information including the new amount and
available shipping options based on the selected address.
Both synchronous and asynchronous (async) handlers are supported.

In case of an address validation error, include the `error` field in the response
to display an appropriate error in the wallet payment sheet.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnShippingAddressChangeCallback</code>](#OnShippingAddressChangeCallback) | Function to be called when the shipping address data is updated. |

**Example**  
```js
// Async handler
button.onShippingAddressChange(async (data) => {
  const response = await fetch('https://your-server.com/update-shipping-address', {
    method: 'POST',
    body: JSON.stringify(data),
  });
  const result = await response.json();
  return {
    amount: result.newAmount,
    shipping_options: result.availableShippingOptions,
  };
});
```
**Example**  
```js
// Sync handler
button.onShippingAddressChange((data) => {
  return {
    amount: calculateShipping(data.data.address_country),
    shipping_options: getOptionsForCountry(data.data.address_country),
  };
});
```
<a name="OpenWalletButtons+onShippingOptionsChange" id="OpenWalletButtons+onShippingOptionsChange" href="#OpenWalletButtons+onShippingOptionsChange">&nbsp;</a>

### *openWalletButtons.onShippingOptionsChange(handler)*
Registers a callback for when the customer selects a shipping option.
Use this method to listen for shipping option selection from customer when shipping is enabled.
The event handler should return the updated payment amount based on the selected shipping option.
Both synchronous and asynchronous (async) handlers are supported.

**Kind**: instance method of [<code>OpenWalletButtons</code>](#OpenWalletButtons)  

| Param | Type | Description |
| --- | --- | --- |
| handler | [<code>OnShippingOptionsChangeCallback</code>](#OnShippingOptionsChangeCallback) | Function to be called when the shipping options data is updated. |

**Example**  
```js
// Async handler
button.onShippingOptionsChange(async (data) => {
  const response = await fetch('https://your-server.com/update-shipping-option', {
    method: 'POST',
    body: JSON.stringify({ shipping_option_id: data.data.shipping_option_id }),
  });
  const result = await response.json();
  return {
    amount: result.newTotalAmount,
  };
});
```
**Example**  
```js
// Sync handler
button.onShippingOptionsChange((data) => {
  return {
    amount: lookupShippingCost(data.data.shipping_option_id),
  };
});
```
<a name="EVENT" id="EVENT" href="#EVENT">&nbsp;</a>

## EVENT : <code>object</code>
List of available event names in the Open Wallet button lifecycle.

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| ON_CLICK | <code>string</code> | <code>&quot;onClick&quot;</code> | Emitted when the wallet button is clicked. |
| SUCCESS | <code>string</code> | <code>&quot;success&quot;</code> | Emitted when OTT creation succeeds. |
| UNAVAILABLE | <code>string</code> | <code>&quot;unavailable&quot;</code> | Emitted when the wallet is not available. |
| ERROR | <code>string</code> | <code>&quot;error&quot;</code> | Emitted when an error occurs. |
| LOADED | <code>string</code> | <code>&quot;loaded&quot;</code> | Emitted when the button is rendered. |
| CHECKOUT_CLOSE | <code>string</code> | <code>&quot;checkoutClose&quot;</code> | Emitted when the wallet checkout is cancelled. |
| ON_SHIPPING_ADDRESS_CHANGE | <code>string</code> | <code>&quot;onShippingAddressChange&quot;</code> | Emitted when shipping address changes. |
| ON_SHIPPING_OPTIONS_CHANGE | <code>string</code> | <code>&quot;onShippingOptionsChange&quot;</code> | Emitted when shipping option changes. |

<a name="WALLET_TYPES" id="WALLET_TYPES" href="#WALLET_TYPES">&nbsp;</a>

## WALLET\_TYPES : <code>object</code>
Enum of available wallet types.

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| APPLE_PAY | <code>string</code> | <code>&quot;apple&quot;</code> | Apple Pay wallet. |
| GOOGLE_PAY | <code>string</code> | <code>&quot;google&quot;</code> | Google Pay wallet. |

<a name="TOKEN_TYPE" id="TOKEN_TYPE" href="#TOKEN_TYPE">&nbsp;</a>

## TOKEN\_TYPE : <code>object</code>
Token types returned in the OTT (One-Time Token) creation response.

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| CARD | <code>string</code> | <code>&quot;card&quot;</code> | FPAN (Funding Primary Account Number). Available for Google Pay only. |
| CARD_SCHEME_TOKEN | <code>string</code> | <code>&quot;card_scheme_token&quot;</code> | DPAN (Device Primary Account Number). Available for both Apple Pay and Google Pay. |

<a name="ERROR_OPERATION" id="ERROR_OPERATION" href="#ERROR_OPERATION">&nbsp;</a>

## ERROR\_OPERATION : <code>object</code>
Operations that can fail during the wallet lifecycle.
Used in the `context.operation` field of [OnErrorEventData](#OnErrorEventData).

**Kind**: global constant  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| WALLET_OPERATION | <code>string</code> | <code>&quot;wallet_operation&quot;</code> | General wallet lifecycle operation (default). |
| CONFIGURATION | <code>string</code> | <code>&quot;configuration&quot;</code> | Loading or validating the wallet service configuration (e.g. network fetch failure, card config validation). |
| HANDLER_REGISTRATION | <code>string</code> | <code>&quot;handler_registration&quot;</code> | A required event handler was not registered before calling load(). |
| SHIPPING_UPDATE | <code>string</code> | <code>&quot;shipping_update&quot;</code> | Processing a shipping address or shipping option update failed. |

<a name="OnClickCallback" id="OnClickCallback" href="#OnClickCallback">&nbsp;</a>

## OnClickCallback ⇒ <code>boolean</code> \| <code>void</code> \| <code>Promise.&lt;(boolean\|void)&gt;</code>
Callback for onClick method.

**Kind**: global typedef  
**Returns**: <code>boolean</code> \| <code>void</code> \| <code>Promise.&lt;(boolean\|void)&gt;</code> - Return `false` to abort, or a Promise to defer.  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnClickEventData</code>](#OnClickEventData) | The click event data. |

<a name="OnSuccessCallback" id="OnSuccessCallback" href="#OnSuccessCallback">&nbsp;</a>

## OnSuccessCallback : <code>function</code>
Callback for onSuccess method.

**Kind**: global typedef  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnCreateOTTSuccessfulEventData</code>](#OnCreateOTTSuccessfulEventData) | The OTT creation result including the token, amount, and address data. |

<a name="OnUnavailableCallback" id="OnUnavailableCallback" href="#OnUnavailableCallback">&nbsp;</a>

## OnUnavailableCallback : <code>function</code>
Callback for onUnavailable method.

**Kind**: global typedef  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnUnavailableEventData</code>](#OnUnavailableEventData) | Data describing why the wallet is unavailable. |

<a name="OnErrorCallback" id="OnErrorCallback" href="#OnErrorCallback">&nbsp;</a>

## OnErrorCallback : <code>function</code>
Callback for onError method.

**Kind**: global typedef  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnErrorEventData</code>](#OnErrorEventData) | The error event data including the Error object and context. |

<a name="OnCancelCallback" id="OnCancelCallback" href="#OnCancelCallback">&nbsp;</a>

## OnCancelCallback : <code>function</code>
Callback for onCancel method.

**Kind**: global typedef  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnCancelEventData</code>](#OnCancelEventData) | Data associated with the cancellation event. |

<a name="OnShippingAddressChangeCallback" id="OnShippingAddressChangeCallback" href="#OnShippingAddressChangeCallback">&nbsp;</a>

## OnShippingAddressChangeCallback ⇒ [<code>OnShippingAddressChangeEventResponse</code>](#OnShippingAddressChangeEventResponse) \| [<code>Promise.&lt;OnShippingAddressChangeEventResponse&gt;</code>](#OnShippingAddressChangeEventResponse)
Callback for onShippingAddressChange method.

**Kind**: global typedef  
**Returns**: [<code>OnShippingAddressChangeEventResponse</code>](#OnShippingAddressChangeEventResponse) \| [<code>Promise.&lt;OnShippingAddressChangeEventResponse&gt;</code>](#OnShippingAddressChangeEventResponse) - Address update result containing updated amount, shipping options, and optional error.  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnShippingAddressChangeEventData</code>](#OnShippingAddressChangeEventData) | The shipping address data from the wallet. |

<a name="OnShippingOptionsChangeCallback" id="OnShippingOptionsChangeCallback" href="#OnShippingOptionsChangeCallback">&nbsp;</a>

## OnShippingOptionsChangeCallback ⇒ [<code>OnShippingOptionChangeEventResponse</code>](#OnShippingOptionChangeEventResponse) \| [<code>Promise.&lt;OnShippingOptionChangeEventResponse&gt;</code>](#OnShippingOptionChangeEventResponse)
Callback for onShippingOptionsChange method.

**Kind**: global typedef  
**Returns**: [<code>OnShippingOptionChangeEventResponse</code>](#OnShippingOptionChangeEventResponse) \| [<code>Promise.&lt;OnShippingOptionChangeEventResponse&gt;</code>](#OnShippingOptionChangeEventResponse) - Shipping options update result containing the updated amount.  

| Param | Type | Description |
| --- | --- | --- |
| data | [<code>OnShippingOptionChangeEventData</code>](#OnShippingOptionChangeEventData) | The selected shipping option data. |


# Click To Pay

## Overview

Integrate with Click To Pay using Paydock's Click To Pay widget.
For a full description of the methods and parameters, reference the [README file](https://www.npmjs.com/package/@paydock/client-sdk#ClickToPay).

## Click To Pay simple example

The following section provides an example use case and integration for the widget.

### Create a Container

To integrate the Click To Pay checkout iFrame, create a container in your HTML code. This container serves as the placeholder for the iFrame.

```html
<div id="checkoutIframe"></div>
```

### Initialize the Widget

Use the following code to initialize your widget:

```javascript
var src = new paydock.ClickToPay(
    "#checkoutIframe",
    "service_id",
    "paydock_public_key_or_access_token",
    {}, // meta
);
src.load();
```

```javascript
// ES2015 | TypeScript
import { ClickToPay } from '@paydock/client-sdk';
var src = new ClickToPay(
    "#checkoutIframe",
    "service_id",
    "paydock_public_key_or_access_token",
    {}, // meta
);
src.load();
```

*NOTE:* Paydock recommends that you use a Paydock Access Token instead of a public key for security reasons in production environments. When creating your access token, you must enable the `Secure Remote Commerce` and add a whitelist for the domain of your checkout screen.

### Full example

A full example of the container and the initialized widget is as follows:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 300px;}</style>
</head>
<body>
    <div id="checkoutIframe"></div>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
    <script>
        var src = new paydock.ClickToPay(
            "#checkoutIframe",
            "service_id",
            "paydock_public_key_or_access_token",
            {},
        );
        src.load();
    </script>
</body>
</html>
```

## Customize your Click To Pay Checkout

The following is an advanced example that includes customization. You can use these methods to enhance your checkout experience.

### Settings

```javascript
src.setEnv('sandbox'); // set environment
src.hideCheckout(); // hide checkout iframe
src.showCheckout(); // show checkout iframe
src.on('iframeLoaded', () => {
    console.log("Initial iframe loaded");
});
src.on('checkoutReady', () => {
    console.log("Checkout ready to be used");
});
src.on('checkoutCompleted', (token) => {
    console.log(token);
});
src.on('checkoutError', (error) => {
    console.log(error);
});
```

### Full example

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>iframe {border: 0;width: 40%;height: 450px;}</style>
</head>
<body>
    <div id="checkoutIframe"></div>
    <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
    <script>
        var src = new paydock.ClickToPay(
            "#checkoutIframe",
            "service_id",
            "paydock_public_key_or_access_token",
            {},
        );
        src.on('iframeLoaded', () => {
            console.log("Initial iframe loaded");
        });
        src.on('checkoutReady', () => {
            console.log("Checkout ready to be used");
        });
        src.on('checkoutCompleted', (token) => {
            console.log(token);
        });
        src.on('checkoutError', (error) => {
            console.log(error);
        });
        src.load();
    </script>
</body>
</html>
```

## Customize your billing address fields

To customize your billing address experience, Paydock uses a flag that manages whether a customer's billing address is mandatory.
The options for this customization are NONE (default option), and POSTAL_COUNTRY or FULL.

```
var src = new paydock.ClickToPay(
    "#checkoutIframe",
    "service_id",
    "paydock_public_key_or_access_token",
    {
        "dpa_transaction_options": {
            "dpa_billing_preference": "FULL"
        }
    },
);
```

The Click To Pay checkout in the example requires the billing address from the customer, which is then returned as a part of the checkout data. The data is then stored and leveraged in the Paydock charge.
You can also provide the billing address at the time of creating the charge. For example, if you have a different method for collecting the billing address, such as outside of the Click To Pay checkout, you can provide it alongside other information at the charge creation step:
1. Disable the billing address in Paydock's Click To Pay widget.
2. Get your One Time Token from the Click To Pay widget alongside other details that may have been collected outside the Click To Pay checkout as the shipping address.
3. Send the billing address when creating the charge.

```
POST v1/charges
{
    "amount": "10.00",
    "currency": "AUD",
    "token": "one_time_token",
    "customer": {
        "payment_source": {
            "gateway_id": "gateway_id",
            "address_line1": "address_line1",
            "address_line2": "address_line2",
            "address_city": "address_city",
            "address_postcode": "address_postcode",
            "address_state": "address_state",
            "address_country": "address_country"
        }
    },
    "shipping": {
        "address_line1": "address_line1",
        "address_line2": "address_line2",
        "address_line3": "address_line3",
        "address_city": "address_city",
        "address_postcode": "address_postcode",
        "address_state": "address_state",
        "address_country": "address_country"
    }
}
```

## How to customize accepted cards

You can send a flag `unaccepted_card_type` to block the usage of a specific card type. The available options are 'DEBIT' and 'CREDIT'.

### Example code

The following example demonstrates how to block the card:

```
var src = new paydock.ClickToPay(
    "#checkoutIframe",
    "service_id",
    "paydock_public_key",
    {
        unaccepted_card_type: 'DEBIT'
    },
);
```

## Personalize the Style

Customize the look and feel of your UI. The following example demonstrates changes in the styling of the buttons.

### Example code

```
var src = new paydock.ClickToPay(
    "#checkoutIframe",
    "service_id",
    "paydock_public_key",
    {},
);
src.setStyles({
    enable_src_popup: true,
    primary_button_color: 'red',
    secondary_button_color: 'red',
    primary_button_text_color: 'red',
    secondary_button_text_color: 'red',
    font_family: 'Arial',
});
```

## Configurations for background loading and improved User Load times

### hold_for_customer_data
When set to `true`, this flag allows you to load the Click to Pay iframe in the background while collecting customer information. This improves the perceived performance by starting the iframe load process early.

```javascript
const clickToPay = new cba.ClickToPay("#checkoutIframe", SERVICE_ID, PUBLIC_KEY, {
  hold_for_customer_data: true,
  dpa_config: {
    dpa_id: DPA_ID,
    // ... other config
  }
});
```

### injectCustomerData(customer)
Once you have collected the customer information, use this method to provide it to the Click to Pay iframe. This will trigger the checkout to continue.

```javascript
clickToPay.injectCustomerData({
  email: "customer@example.com",
  first_name: "John",
  last_name: "Doe",
  phone: "+61400123456"  // Include country code
});
```

### Background Loading Example
Here's a complete example showing how to implement background loading while collecting customer information:

```javascript
// 1. Initialize with hold_for_customer_data
const clickToPay = new cba.ClickToPay("#checkoutIframe", SERVICE_ID, PUBLIC_KEY, {
  hold_for_customer_data: true,
  dpa_config: {
    dpa_id: DPA_ID,
    // ... other config
  }
});

// Hide checkout and show form initially
document.getElementById("checkoutIframe").style.display = 'none';
document.getElementById("customerForm").style.display = 'block';
document.getElementById("loader").style.display = 'none';

// 2. Setup event handlers
clickToPay.on('iframeLoaded', () => {
  // Iframe is now loaded
});

clickToPay.on('checkoutReady', () => {
  // Hide loader, show checkout
  document.getElementById("loader").style.display = 'none';
  document.getElementById("checkoutIframe").style.display = 'block';
  clickToPay.showCheckout();
});

// 3. Start loading in background
clickToPay.load();

// 4. Handle form submission
document.getElementById("submitButton").addEventListener("click", (e) => {
  e.preventDefault();

  const customer = {
    email: document.getElementById("email").value.trim(),
    first_name: document.getElementById("firstName").value.trim(),
    last_name: document.getElementById("lastName").value.trim(),
    phone: document.getElementById("phone").value.trim()
  };

  // Hide form, show loader
  document.getElementById("customerForm").style.display = "none";
  document.getElementById("loader").style.display = "flex";

  try {
    // Inject customer data to continue checkout
    clickToPay.injectCustomerData(customer);
  } catch (error) {
    // Show form again on error
    document.getElementById("customerForm").style.display = "block";
    document.getElementById("loader").style.display = "none";
    alert("An error occurred. Please try again.");
  }
});
```

#### HTML Structure
Here's the required HTML structure for the background loading example:

```html
<!-- Click to Pay iframe container -->
<div id="checkoutIframe"></div>

<!-- Customer information form -->
<form id="customerForm">
  <input type="email" id="email" placeholder="Email" required>
  <input type="text" id="firstName" placeholder="First Name" required>
  <input type="text" id="lastName" placeholder="Last Name" required>
  <input type="tel" id="phone" placeholder="Phone (with country code)" required>
  <button type="submit" id="submitButton">Continue to Checkout</button>
</form>

<!-- Loading indicator -->
<div id="loader" style="display: none;">
  Loading...
</div>
```

## Classes

<dl>
<dt><a href="#ClickToPay">ClickToPay</a> ⇐ <code>SRC</code></dt>
<dd><p>Class ClickToPay include methods for interacting with the ClickToPay checkout and Manual Card option</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#IMastercardSRCMeta">IMastercardSRCMeta</a> : <code>object</code></dt>
<dd><p>Interface of data used for the Mastercard Checkout. For further information refer to <a href="https://developer.mastercard.com/unified-checkout-solutions/documentation/sdk-reference/init">the documentation</a>.</p>
</dd>
<dt><a href="#EventData">EventData</a> : <code>object</code></dt>
<dd><p>Interface for data returned in callbacks</p>
</dd>
<dt><a href="#EventDataCheckoutCompletedData">EventDataCheckoutCompletedData</a> : <code>object</code></dt>
<dd><p>Event data returned for checkoutCompleted callback, holding the One Time Token and the flow type completed.
When the flow type is src, masked checkoutData available is also returned</p>
</dd>
<dt><a href="#IStyles">IStyles</a> : <code>object</code></dt>
<dd><p>Interface for style configs inyected to the Click to Pay checkout</p>
</dd>
</dl>

<a name="IMastercardSRCMeta" id="IMastercardSRCMeta" href="#IMastercardSRCMeta">&nbsp;</a>

## IMastercardSRCMeta : <code>object</code>
Interface of data used for the Mastercard Checkout. For further information refer to [the documentation](https://developer.mastercard.com/unified-checkout-solutions/documentation/sdk-reference/init).

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [disable_summary_screen] | <code>boolean</code> | Boolean flag that controls if a final summary screen is presented in the checkout flow. |
| [dpa_data] | <code>object</code> | Object where the DPA creation data is stored. |
| [dpa_data.dpa_presentation_name] | <code>string</code> | Name in which the DPA is presented. |
| [dpa_data.dpa_uri] | <code>string</code> | Used for indicating the DPA URI. |
| [dpa_data.dpa_address] | <code>string</code> | Address associated with the DPA. |
| [dpa_data.dpa_email_address] | <code>string</code> | Email address for DPA communication. |
| [dpa_data.dpa_phone_number] | <code>object</code> | Phone number structure for DPA communication. |
| [dpa_data.dpa_phone_number.country_code] | <code>string</code> | The country code of the phone number. |
| [dpa_data.dpa_phone_number.phone_number] | <code>string</code> | The phone number part of the phone number. |
| [dpa_data.dpa_logo_uri] | <code>string</code> | URI for the DPA logo. |
| [dpa_data.dpa_supported_email_address] | <code>string</code> | Supported email address for DPA support. |
| [dpa_data.dpa_supported_phone_number] | <code>object</code> | Supported phone number for DPA support. |
| [dpa_data.dpa_supported_phone_number.country_code] | <code>string</code> | The country code of the phone number. |
| [dpa_data.dpa_supported_phone_number.phone_number] | <code>string</code> | The phone number part of the phone number. |
| [dpa_data.dpa_support_uri] | <code>string</code> | URI for DPA support. |
| [dpa_data.application_type] | <code>string</code> | Application type, either 'WEB_BROWSER' or 'MOBILE_APP'. |
| [co_brand_names] | <code>Array.&lt;string&gt;</code> | List of co-brand names associated with the Click to Pay experience. |
| [checkout_experience] | <code>string</code> | Checkout experience type, either 'WITHIN_CHECKOUT' or 'PAYMENT_SETTINGS'. |
| [services] | <code>string</code> | Services offered, such as 'INLINE_CHECKOUT' or 'INLINE_INSTALLMENTS'. |
| [dpa_transaction_options] | <code>object</code> | Object that stores options for creating a transaction with DPA. |
| [dpa_transaction_options.dpa_locale] | <code>string</code> | DPA's preferred locale, example en_US. |
| [dpa_transaction_options.dpa_accepted_billing_countries] | <code>Array.&lt;string&gt;</code> | List of accepted billing countries for DPA in ISO 3166-1 alpha-2 format. |
| [dpa_transaction_options.dpa_billing_preference] | <code>string</code> | Billing preferences for DPA, options are 'FULL', 'POSTAL_COUNTRY', 'NONE'. |
| [dpa_transaction_options.payment_options] | <code>Array.&lt;object&gt;</code> | Payment options included in the transaction. |
| [dpa_transaction_options.payment_options.dynamic_data_type] | <code>string</code> | Dynamic data types. |
| [dpa_transaction_options.order_type] | <code>string</code> | Type of the order, options are 'SPLIT_SHIPMENT', 'PREFERRED_CARD'. |
| [dpa_transaction_options.three_ds_preference] | <code>string</code> | Preference for 3DS usage in the transaction. |
| [dpa_transaction_options.confirm_payment] | <code>boolean</code> | Indicates if payment confirmation is required. |
| [dpa_transaction_options.consumer_name_requested] | <code>boolean</code> | Indicates if consumer name is requested. |
| [dpa_transaction_options.consumer_email_address_requested] | <code>boolean</code> | Indicates if consumer email address is requested. |
| [dpa_transaction_options.consumer_phone_number_requested] | <code>boolean</code> | Indicates if consumer phone number is requested. |
| [dpa_transaction_options.transaction_amount] | <code>object</code> | Details of the transaction amount. |
| [dpa_transaction_options.transaction_amount.transaction_amount] | <code>number</code> | Amount of the transaction. |
| [dpa_transaction_options.transaction_amount.transaction_currency_code] | <code>string</code> | Currency code of the transaction in 3 letter ISO code format. |
| [dpa_transaction_options.merchant_order_id] | <code>string</code> | Merchant's order ID. |
| [dpa_transaction_options.merchant_category_code] | <code>string</code> | Merchant's category code. |
| [dpa_transaction_options.merchant_country_code] | <code>string</code> | Merchant's country code in ISO 3166-1 alpha-2 format. |
| [customer] | <code>object</code> | Object where the customer data is stored to prefill in the checkout. |
| [customer.email] | <code>string</code> | Customer email. |
| [customer.first_name] | <code>string</code> | Customer first name. |
| [customer.last_name] | <code>string</code> | Customer last name. |
| [customer.phone] | <code>object</code> | Object where the customer phone is stored. |
| [customer.phone.country_code] | <code>string</code> | Customer phone country code (example "1" for US). |
| [customer.phone.phone] | <code>string</code> | Customer phone number. |
| [unaccepted_card_type] | <code>string</code> | Used to block a specific card type. Options are 'CREDIT', 'DEBIT'. |
| [dpa_config] | <code>object</code> | Raw DPA configuration object for performance optimization. Skips API call when provided. |
| [dpa_config.dpa_id] | <code>string</code> | DPA identifier. |
| [dpa_config.dpa_name] | <code>string</code> | DPA name. |
| [dpa_config.dpa_supported_card_schemes] | <code>Array.&lt;string&gt;</code> | List of supported card schemes: 'MASTERCARD', 'VISA', 'AMEX', 'DISCOVER'. |
| [dpa_config.mode] | <code>string</code> | DPA mode, either 'sandbox' or 'live'. |
| [hold_for_customer_data] | <code>boolean</code> | Flag to hold initialization for customer data injection. Enables background initialization. |

<a name="EventData" id="EventData" href="#EventData">&nbsp;</a>

## EventData : <code>object</code>
Interface for data returned in callbacks

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| type | [<code>EVENT\_DATA\_TYPE</code>](#EVENT_DATA_TYPE) | Event type of type [EVENT_DATA_TYPE](#EVENT_DATA_TYPE) |
| data | <code>string</code> \| [<code>EventDataCheckoutCompletedData</code>](#EventDataCheckoutCompletedData) | optional data returning a string for checkoutError event or [EventDataCheckoutCompletedData](#EventDataCheckoutCompletedData) for checkoutCompleted |

<a name="EventDataCheckoutCompletedData" id="EventDataCheckoutCompletedData" href="#EventDataCheckoutCompletedData">&nbsp;</a>

## EventDataCheckoutCompletedData : <code>object</code>
Event data returned for checkoutCompleted callback, holding the One Time Token and the flow type completed.
When the flow type is src, masked checkoutData available is also returned

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| type | <code>string</code> | type of the checkout, can be `src` or `manual`. |
| token | <code>string</code> | one time token value. |
| token_type | <code>string</code> | one time token type value, can be `card` or `card_scheme_token`. |
| [checkoutData] | <code>object</code> | Optional checkout data related to the checkout information. Only available on src flow. |
| [checkoutData.card_number_bin] | <code>string</code> | The BIN of the card used for the transaction. |
| [checkoutData.card_number_last4] | <code>string</code> | The last four digits of the card number. |
| [checkoutData.card_scheme] | <code>string</code> | The card scheme. Values: visa, mastercard, amex, diners, discover. |
| [checkoutData.card_type] | <code>string</code> | The type of card. Values: credit, debit, prepaid, combo, flex. |
| [checkoutData.address_line1] | <code>string</code> | Address line 1 for billing address. |
| [checkoutData.address_line2] | <code>string</code> | Address line 2 for billing address. |
| [checkoutData.address_line3] | <code>string</code> | Address line 3 for billing address. |
| [checkoutData.address_city] | <code>string</code> | City for billing address. |
| [checkoutData.address_postcode] | <code>string</code> | Postal code for billing address. |
| [checkoutData.address_state] | <code>string</code> | State or province for billing address. |
| [checkoutData.address_country] | <code>string</code> | Country for billing address. |
| [checkoutData.shipping] | <code>object</code> | Optional shipping information. |
| [checkoutData.shipping.address_line1] | <code>string</code> | Address line 1 for shipping address. |
| [checkoutData.shipping.address_line2] | <code>string</code> | Address line 2 for shipping address. |
| [checkoutData.shipping.address_line3] | <code>string</code> | Address line 3 for shipping address. |
| [checkoutData.shipping.address_city] | <code>string</code> | City for shipping address. |
| [checkoutData.shipping.address_postcode] | <code>string</code> | Postal code for shipping address. |
| [checkoutData.shipping.address_state] | <code>string</code> | State or province for shipping address. |
| [checkoutData.shipping.address_country] | <code>string</code> | Country for shipping address. |

<a name="IStyles" id="IStyles" href="#IStyles">&nbsp;</a>

## IStyles : <code>object</code>
Interface for style configs inyected to the Click to Pay checkout

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [primary_button_color] | <code>string</code> | Color Code for primary button. |
| [primary_button_text_color] | <code>string</code> | Color Code for primary button text. |
| [secondary_button_color] | <code>string</code> | Color Code for secondary button. |
| [secondary_button_text_color] | <code>string</code> | Color Code for secondary button text. |
| [font_family] | <code>string</code> | Font family to be used. |
| [enable_src_popup] | <code>boolean</code> | Boolean flag to make the Click to Pay checkout show in a popup window instead of embedded in iframe. |

<a name="ClickToPay" id="ClickToPay" href="#ClickToPay">&nbsp;</a>

## ClickToPay ⇐ <code>SRC</code>
Class ClickToPay include methods for interacting with the ClickToPay checkout and Manual Card option

**Kind**: global class  
**Extends**: <code>SRC</code>  

* [ClickToPay](#ClickToPay) ⇐ <code>SRC</code>
    * [new ClickToPay(iframe_selector, service_id, public_key_or_access_token, meta)](#new_ClickToPay_new)
    * [.load()](#ClickToPay+load)
    * [.injectCustomerData(customerData)](#ClickToPay+injectCustomerData)
    * [.setStyles(fields)](#SRC+setStyles)
    * [.setEnv(env, [alias])](#SRC+setEnv)
    * [.getEnv()](#SRC+getEnv)
    * [.on(eventName, [cb])](#SRC+on) ⇒ <code>Promise.&lt;any&gt;</code> \| <code>void</code>
    * [.hideCheckout([saveSize])](#SRC+hideCheckout)
    * [.showCheckout()](#SRC+showCheckout)
    * [.reload()](#SRC+reload)
    * [.useAutoResize()](#SRC+useAutoResize)

<a name="new_ClickToPay_new" id="new_ClickToPay_new" href="#new_ClickToPay_new">&nbsp;</a>

### new ClickToPay(iframe_selector, service_id, public_key_or_access_token, meta)

| Param | Type | Description |
| --- | --- | --- |
| iframe_selector | <code>string</code> | Selector of html element. Container for Click To Pay checkout iFrame. |
| service_id | <code>string</code> | Card Scheme Service ID |
| public_key_or_access_token | <code>string</code> | Paydock public key or Access Token |
| meta | <code>IClickToPayMeta</code> | Data that configures the Click To Pay checkout |

**Example**  
```js
var mastercardSRC = new ClickToPay('#checkoutIframe', 'service_id', 'public_key', {});
```
<a name="ClickToPay+load" id="ClickToPay+load" href="#ClickToPay+load">&nbsp;</a>

### clickToPay.load()
The final method after configuring the SRC to start the load process of Click To Pay checkout

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
<a name="ClickToPay+injectCustomerData" id="ClickToPay+injectCustomerData" href="#ClickToPay+injectCustomerData">&nbsp;</a>

### clickToPay.injectCustomerData(customerData)
Inject customer data after widget initialization via postMessage

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Throws**:

- <code>Error</code> When customer data is invalid or widget is not ready


| Param | Type | Description |
| --- | --- | --- |
| customerData | <code>Customer</code> | Customer data to inject |

**Example**  
```js
widget.injectCustomerData({
    email: 'user@example.com',
    first_name: 'John',
    last_name: 'Doe'
});
```
<a name="SRC+setStyles" id="SRC+setStyles" href="#SRC+setStyles">&nbsp;</a>

### clickToPay.setStyles(fields)
Object contain styles for widget - call before `.load()`.

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>setStyles</code>](#SRC+setStyles)  

| Param | Type | Description |
| --- | --- | --- |
| fields | [<code>IStyles</code>](#IStyles) | name of styles which can be shown in widget [STYLE](STYLE) |

**Example**  
```js
widget.setStyles({
    enable_src_popup: true
    primary_button_color: 'red',
    secondary_button_color: 'blue',
    primary_button_text_color: 'white',
    secondary_button_text_color: 'white',
    font_family: 'Arial',
});
```
<a name="SRC+setEnv" id="SRC+setEnv" href="#SRC+setEnv">&nbsp;</a>

### clickToPay.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>setEnv</code>](#SRC+setEnv)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  
```js
SRC.setEnv('production');
```
<a name="SRC+getEnv" id="SRC+getEnv" href="#SRC+getEnv">&nbsp;</a>

### clickToPay.getEnv()
Method to read the current environment

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>getEnv</code>](#SRC+getEnv)  
**Example**  
```js
SRC.getEnv();
```
<a name="SRC+on" id="SRC+on" href="#SRC+on">&nbsp;</a>

### clickToPay.on(eventName, [cb]) ⇒ <code>Promise.&lt;any&gt;</code> \| <code>void</code>
Listen to events of SRC

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>on</code>](#SRC+on)  

| Param | Type | Description |
| --- | --- | --- |
| eventName | <code>string</code> | Available event names [EVENT](#EVENT) |
| [cb] | <code>listener</code> | The callback to handle the event. When available, it will send back data of type [EventData](#EventData) |

**Example**  
```js
SRC.on('checkoutCompleted', function (token) {
     console.log(token);
});
// or
SRC.on('checkoutCompleted').then(function (token) {
     console.log(token);
});
```
<a name="SRC+hideCheckout" id="SRC+hideCheckout" href="#SRC+hideCheckout">&nbsp;</a>

### clickToPay.hideCheckout([saveSize])
Using this method you can hide checkout after load and button click

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>hideCheckout</code>](#SRC+hideCheckout)  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [saveSize] | <code>boolean</code> | <code>false</code> | using this param you can save iframe's size (if applicable) |

**Example**  
```js
SRC.hideCheckout();
```
<a name="SRC+showCheckout" id="SRC+showCheckout" href="#SRC+showCheckout">&nbsp;</a>

### clickToPay.showCheckout()
Using this method you can show checkout after using hideCheckout method

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>showCheckout</code>](#SRC+showCheckout)  
**Example**  
```js
SRC.showCheckout()
```
<a name="SRC+reload" id="SRC+reload" href="#SRC+reload">&nbsp;</a>

### clickToPay.reload()
Using this method you can reload the whole checkout

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>reload</code>](#SRC+reload)  
**Example**  
```js
SRC.reload()
```
<a name="SRC+useAutoResize" id="SRC+useAutoResize" href="#SRC+useAutoResize">&nbsp;</a>

### clickToPay.useAutoResize()
Use this method for resize checkout iFrame according to content height, if applicable

**Kind**: instance method of [<code>ClickToPay</code>](#ClickToPay)  
**Overrides**: [<code>useAutoResize</code>](#SRC+useAutoResize)  
**Example**  
```js
SRC.useAutoResize();
```
<a name="EVENT" id="EVENT" href="#EVENT">&nbsp;</a>

## EVENT : <code>enum</code>
List of available event's name in the Click To Pay checkout lifecycle

**Kind**: global enum  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| IFRAME_LOADED | <code>string</code> | <code>&quot;iframeLoaded&quot;</code> | Initial event sent when IFrame is initially loaded. |
| CHECKOUT_READY | <code>string</code> | <code>&quot;checkoutReady&quot;</code> | Event sent when checkout is loaded and ready to be used by customer. Leverage alongside [showCheckout](#SRC+showCheckout) and [hideCheckout](#SRC+hideCheckout). |
| CHECKOUT_POPUP_OPEN | <code>string</code> | <code>&quot;checkoutPopupOpen&quot;</code> | Event sent when Click To Pay checkout flow is started, regardless of embedded or windowed mode. |
| CHECKOUT_POPUP_CLOSE | <code>string</code> | <code>&quot;checkoutPopupClose&quot;</code> | Event sent when Click To Pay checkout flow is closed, regardless of embedded or windowed mode. |
| CHECKOUT_COMPLETED | <code>string</code> | <code>&quot;checkoutCompleted&quot;</code> | Event sent on successful checkout by customer. Check [data](#EventDataCheckoutCompletedData) for more information. |
| CHECKOUT_ERROR | <code>string</code> | <code>&quot;checkoutError&quot;</code> | Event sent on error checkout by customer. Check [data](#EventData) for more information. |

<a name="EVENT_DATA_TYPE" id="EVENT_DATA_TYPE" href="#EVENT_DATA_TYPE">&nbsp;</a>

## EVENT\_DATA\_TYPE : <code>enum</code>
List of available event data types

**Kind**: global enum  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| CRITICAL_ERROR | <code>string</code> | <code>&quot;CriticalError&quot;</code> | in this error scenario the checkout is understood to be in a non-recoverable state and should be closed by the merchant and give alternate payment options to the user |
| USER_ERROR | <code>string</code> | <code>&quot;UserError&quot;</code> | in this error scenario the error in likely a user input error and the checkout is in a recoverable state, so the user will be kept within the checkout and can retry the flow |
| SUCCESS | <code>string</code> | <code>&quot;Success&quot;</code> |  |


# Fraud prevention

The Fraud Prevention module allows you to add security layers to your payment workflows
by integrating with any of our underlying fraud prevention providers.

## Real time user behavior analysis

### Forter

One of Forter's key features is our ability to track the user's real-time behavior on
the site and use it to separate fraudsters from legitimate buyers. To take advantage
of Forter's technology, a JavaScript snippet needs to be placed on EVERY page
of your commerce site beginning with the homepage and up to and including the final
"Thank you for your purchase" page.

The integration is simple and straightforward - you only need to configure event
listeners and then instantiate a FraudPreventionService with your site configuration.

Additional setup is required in case your website uses Content Security Policies (CSP)

#### Forter: Code snippet

```html
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Real time user behaviour anaylsis - Forter example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="https://widget.paydock.com/sdk/latest/widget.umd.js" ></script>
</head>

<body>
  <main>
    <h1>Real time user behaviour anaylsis - Forter example</h1>
    <div class="forter-test">
      <h2>Forter Integration</h2>

      <div class="status-card">
        <p>
          <strong>Integration Status:</strong>
          <span data-fraud-prevention="status-indicator" class="status pending">
            Pending
          </span>
        </p>
        <p>
          <strong>Token Value:</strong>
          <code data-fraud-prevention="forter-token">Not available</code>
        </p>
        <p data-fraud-prevention="error-container" style="display: none;">
          <strong>Error Code:</strong>
          <span data-fraud-prevention="error-code" class="error"></span>
        </p>
      </div>
    </div>
  </main>
  <script>
    const { FRAUD_PREVENTION_EVENTS, FraudPreventionService } = window.paydock

    let token = '';
    let errorCode = '';

    const render = () => {
      const statusIndicator = document.querySelector('[data-fraud-prevention="status-indicator"]');
      const tokenValue = document.querySelector('[data-fraud-prevention="forter-token"]');
      const errorContainer = document.querySelector('[data-fraud-prevention="error-container"]');
      const errorCodeElement = document.querySelector('[data-fraud-prevention="error-code"]');

      if (token) {
        statusIndicator.className = 'status success';
        statusIndicator.textContent = 'Active';
        tokenValue.textContent = token;
      } else {
        statusIndicator.className = 'status pending';
        statusIndicator.textContent = 'Pending';
        tokenValue.textContent = 'Not available';
      }

      if (errorCode) {
        errorCodeElement.textContent = errorCode;
        errorContainer.style.display = 'block';
      } else {
        errorContainer.style.display = 'none';
      }
    };

    document.addEventListener(FRAUD_PREVENTION_EVENTS.NAMESPACE, (event) => {
      switch (event.detail.type) {
        case FRAUD_PREVENTION_EVENTS.TYPES.FINTERPRINT_TOKEN_READY: {
          token = event.detail.payload.token;
          break;
        }
        case FRAUD_PREVENTION_EVENTS.TYPES.FINGERPRINT_TOKEN_ERROR: {
          errorCode = event.detail.payload.code;
          break;
        }
        default: {
          throw new Error(
            `${FRAUD_PREVENTION_EVENTS.NAMESPACE} emitted an unsupported event: ${JSON.stringify(event.detail)}.`,
          );
        }
      }

      render();
    });

    const fraudPreventionServiceConfig = {
      environmentId: 'sandbox',
      mode: 'test'
    }

    // Set "csp" to true if your website uses Content Security Policies
    const csp = false;

    new FraudPreventionService(fraudPreventionServiceConfig)
      .withForter({
        siteId: 'example_site_id_or_subsite_id',
        csp,
      });

    // new FraudPreventionService(fraudPreventionServiceConfig)
    //   .withAccessTokenStrategy("eyJhb_access_token_example_...")
    //   .withForter({
    //     providerId: environment.forter.serviceId,
    //     csp,
    //   });

    // new FraudPreventionService(fraudPreventionServiceConfig)
    //   .withPublicKeyStrategy("pk_example_...")
    //   .withForter({
    //     providerId: environment.forter.serviceId,
    //     csp,
    //   });
  </script>
</body>

</html>
```

#### Forter: Content Security Policies

If your site enforces Content Security Policies (CSP), make sure to:

1. Set the `csp` option to `true` when invoking `withForter` on your `FraudPreventionService` instance.
2. Allowlist Forter's domains on `connect-src`, `script-src` and `worker-src` as shown below.

```bash
connect-src https://*.forter.com wss://cdn0.forter.com https://d2o5idwacg3gyw.cloudfront.net https://dz8rit8v72mig.cloudfront.net https://db7q4jg5rkhk8.cloudfront.net https://1.1.1.1 https://d94qwxh6czci4.cloudfront.net https://dr6vcclmzwk74.cloudfront.net https://d6rak4b14t5gp.cloudfront.net https://d3k4bt74u9esq1.cloudfront.net https://d1ezzflfzltk6e.cloudfront.net https://d3nocrch4qti4v.cloudfront.net https://duuytoqss3gu4.cloudfront.net https://df45ay5pw60dy.cloudfront.net
script-src https://*.forter.com https://dlthst9q2beh8.cloudfront.net https://d2nww8zpyj5pk0.cloudfront.net https://d2w2nqfk3z9hdt.cloudfront.net
worker-src blob:
```


## PayPalSavePaymentSource Widget

PayPalSavePaymentSource Widget allows to obtain a Paydock one time token linked with a Paypal payment source from the customer.

The general flow to use the widgets is:
1. Configure your PayPal gateway and connect it using Paydock API or Dashboard.
2. Create a container in your site
```html
<div id="widget"></div>
```
3. Initialize the specific `PayPalSavePaymentSourceWidget`, providing your Access token or Public Key, the Gateway ID that Paydock provides plus required and optional config parameter for the widget in use. The general format is:
```js
new paydock.PayPalSavePaymentSourceWidget(
    "#widget",
    accessTokenOrPublicKey,
    gatewayId,
    widgetSpecificConfig,
);
```
4. Handle the `onSuccess`, `onError` and `onCancel` for paypal setup token results.
5. If `onSuccess` event is emmited, event data should contain `token` and `email` ready to use.

### Example

A full description of the config parameters for [PayPalSavePaymentSourceWidget](#PayPalSavePaymentSourceWidget) meta parameters can be found [here](#PayPalSavePaymentSourceWidgetConfig). Below you will find a fully working html example.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Using PayDock PayPalSavePaymentSourceWidget!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let button = new paydock.PayPalSavePaymentSourceWidget(
        "#widget",
        accessTokenOrPublicKey,
        gatewayId,
        {
            style: {
                layout: 'vertical',
                color:  'gold',
                shape:  'pill',
                label:  'paypal'
            }
        }
    );

    payPalSavePaymentSourceWidget.onSuccess((data) => console.log('On success: ', data));
    payPalSavePaymentSourceWidget.onError((data) => console.log('On error: ', data));
    payPalSavePaymentSourceWidget.onCancel(() => console.log('On cancelled'));

    button.setEnv('sandbox');

    button.load();
</script>
</html>
```

## Classes

<dl>
<dt><a href="#PayPalSavePaymentSourceWidget">PayPalSavePaymentSourceWidget</a></dt>
<dd><p>PayPal Save Payment Source Widget constructor</p>
</dd>
</dl>

## Typedefs

<dl>
<dt><a href="#OnSuccessCallback">OnSuccessCallback</a> : <code>function</code></dt>
<dd><p>Callback for onSuccess method.</p>
</dd>
<dt><a href="#OnErrorCallback">OnErrorCallback</a> : <code>function</code></dt>
<dd><p>Callback for onError method.</p>
</dd>
<dt><a href="#OnCancelCallback">OnCancelCallback</a> : <code>function</code></dt>
<dd><p>Callback for onCancel method.</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#PayPalSavePaymentSourceWidgetConfig">PayPalSavePaymentSourceWidgetConfig</a> : <code>object</code></dt>
<dd><p>Interface of data used for PayPal configuration. For further information refer to <a href="https://developer.paypal.com/sdk/js/reference/#style">the documentation</a>.</p>
</dd>
<dt><a href="#ErrorCodes">ErrorCodes</a> : <code>object</code></dt>
<dd><p>Interface of possible error codes inside onError event data.</p>
</dd>
<dt><a href="#IOnSuccessEventData">IOnSuccessEventData</a> : <code>object</code></dt>
<dd><p>Interface for IOnSuccessEventData</p>
</dd>
<dt><a href="#IOnErrorEventData">IOnErrorEventData</a> : <code>object</code></dt>
<dd><p>Interface for IOnErrorEventData</p>
</dd>
<dt><a href="#IOnCancelEventData">IOnCancelEventData</a> : <code>object</code></dt>
<dd><p>Interface for IOnCancelEventData</p>
</dd>
</dl>

<a name="PayPalSavePaymentSourceWidgetConfig" id="PayPalSavePaymentSourceWidgetConfig" href="#PayPalSavePaymentSourceWidgetConfig">&nbsp;</a>

## PayPalSavePaymentSourceWidgetConfig : <code>object</code>
Interface of data used for PayPal configuration. For further information refer to [the documentation](https://developer.paypal.com/sdk/js/reference/#style).

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [style.layout] | <code>&#x27;vertical&#x27;</code> \| <code>&#x27;horizontal&#x27;</code> | Used for indicating the PayPal Button layout. |
| [style.color] | <code>&#x27;blue&#x27;</code> \| <code>&#x27;gold&#x27;</code> \| <code>&#x27;silver&#x27;</code> \| <code>&#x27;black&#x27;</code> \| <code>&#x27;white&#x27;</code> | Used for indicating the main color of the PayPal Button. |
| [style.shape] | <code>&#x27;rect&#x27;</code> \| <code>&#x27;sharp&#x27;</code> \| <code>&#x27;pill&#x27;</code> | Used for indicating the shape of the PayPal Button. |
| [style.label] | <code>&#x27;paypal&#x27;</code> \| <code>&#x27;checkout&#x27;</code> \| <code>&#x27;buynow&#x27;</code> \| <code>&#x27;pay&#x27;</code> | Used for indicating the label of the PayPal Button. |
| [style.disableMaxWidth] | <code>boolean</code> | Used for indicating if the max width will be disabled. |
| [style.disableMaxHeight] | <code>boolean</code> | Used for indicating the max height will be disabled. |
| [style.height] | <code>number</code> | Used for indicating the height of the PayPal Button, if disableMaxHeight is true. |
| [style.borderRadius] | <code>number</code> | Used for indicating the border radius of the PayPal Button. |
| [style.tagline] | <code>boolean</code> | Used for indicating the tagline of the PayPal Button. |
| [message.amount] | <code>number</code> | Used for indicating an amount before the payment. |
| [message.align] | <code>&#x27;center&#x27;</code> \| <code>&#x27;left&#x27;</code> \| <code>&#x27;right&#x27;</code> | Used for indicating the align of the message. |
| [message.color] | <code>&#x27;black&#x27;</code> \| <code>&#x27;white&#x27;</code> | Used for indicating the color of the message. |
| [message.position] | <code>&#x27;top&#x27;</code> \| <code>&#x27;bottom&#x27;</code> | Used for indicating the position of the message. |

<a name="ErrorCodes" id="ErrorCodes" href="#ErrorCodes">&nbsp;</a>

## ErrorCodes : <code>object</code>
Interface of possible error codes inside onError event data.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [unavailable] | <code>string</code> | Error code when an error occurs loading the widget. |
| [onPaypalVaultSetupTokenError] | <code>string</code> | Error code when an error occrus on PayPal side. |
| [onGetIdTokenError] | <code>string</code> | Error code when trying to get ID token from PayPal. |
| [onGetWalletConfigError] | <code>string</code> | Error code when trying to get wallet config from Paydock. |
| [onGetSetupTokenError] | <code>string</code> | Error code when trying to get the setup token from PayPal. |
| [onOneTimeTokenError] | <code>string</code> | Error code when trying to get the one time token from Paydock. |

<a name="IOnSuccessEventData" id="IOnSuccessEventData" href="#IOnSuccessEventData">&nbsp;</a>

## IOnSuccessEventData : <code>object</code>
Interface for IOnSuccessEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>EVENTS</code> | Event Name is 'ON_SUCCESS' |
| data | <code>object</code> | Data object |
| data.token | <code>string</code> | One Time Token to be exchanged for a Paydock Customer. |
| [data.email] | <code>string</code> | Paypal account customer email if retrieved from Paypal servers. |

<a name="IOnErrorEventData" id="IOnErrorEventData" href="#IOnErrorEventData">&nbsp;</a>

## IOnErrorEventData : <code>object</code>
Interface for IOnErrorEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>EVENTS</code> | Event Name is 'ON_ERROR' |
| data | <code>object</code> | Error data object |
| data.error_code | [<code>ErrorCodes</code>](#ErrorCodes) | Error code. One of ErrorCodes. |
| [data.details] | <code>string</code> | Error details. |
| [data.message] | <code>string</code> | Error message. |

<a name="IOnCancelEventData" id="IOnCancelEventData" href="#IOnCancelEventData">&nbsp;</a>

## IOnCancelEventData : <code>object</code>
Interface for IOnCancelEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| event | <code>EVENTS</code> | Event Name is 'ON_CANCEL' |

<a name="PayPalSavePaymentSourceWidget" id="PayPalSavePaymentSourceWidget" href="#PayPalSavePaymentSourceWidget">&nbsp;</a>

## PayPalSavePaymentSourceWidget
PayPal Save Payment Source Widget constructor

**Kind**: global class  

* [PayPalSavePaymentSourceWidget](#PayPalSavePaymentSourceWidget)
    * [new PayPalSavePaymentSourceWidget(selector, publicKey, gatewayId, config)](#new_PayPalSavePaymentSourceWidget_new)
    * [.load()](#PayPalSavePaymentSourceWidget+load)
    * [.setEnv(env, [alias])](#PayPalSavePaymentSourceWidget+setEnv)
    * [.onSuccess([callback])](#PayPalSavePaymentSourceWidget+onSuccess)
    * [.onError([callback])](#PayPalSavePaymentSourceWidget+onError)
    * [.onCancel([callback])](#PayPalSavePaymentSourceWidget+onCancel)

<a name="new_PayPalSavePaymentSourceWidget_new" id="new_PayPalSavePaymentSourceWidget_new" href="#new_PayPalSavePaymentSourceWidget_new">&nbsp;</a>

### new PayPalSavePaymentSourceWidget(selector, publicKey, gatewayId, config)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | Selector of html element. Container for PayPal Save Payment Source Widget. |
| publicKey | <code>string</code> | PayDock users public key. |
| gatewayId | <code>string</code> | PayDock's PayPal gatewayId. |
| config | [<code>PayPalSavePaymentSourceWidgetConfig</code>](#PayPalSavePaymentSourceWidgetConfig) | Extra configuration for the widget, like styles. |

**Example**  
```js
var payPalSavePaymentSourceWidget = new PayPalSavePaymentSourceWidget('#paypalButton', 'public_key', 'gateway_id');
```
<a name="PayPalSavePaymentSourceWidget+load" id="PayPalSavePaymentSourceWidget+load" href="#PayPalSavePaymentSourceWidget+load">&nbsp;</a>

### payPalSavePaymentSourceWidget.load()
The final method after configuring the PayPalSavePaymentSource Widget to
start the load process.

**Kind**: instance method of [<code>PayPalSavePaymentSourceWidget</code>](#PayPalSavePaymentSourceWidget)  
<a name="PayPalSavePaymentSourceWidget+setEnv" id="PayPalSavePaymentSourceWidget+setEnv" href="#PayPalSavePaymentSourceWidget+setEnv">&nbsp;</a>

### payPalSavePaymentSourceWidget.setEnv(env, [alias])
Current method can change environment. By default environment = sandbox.
Also we can change domain alias for this environment. By default domain_alias = paydock.com

**Kind**: instance method of [<code>PayPalSavePaymentSourceWidget</code>](#PayPalSavePaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | sandbox, production |
| [alias] | <code>string</code> | Own domain alias |

**Example**  
```js
payPalSavePaymentSourceWidget.setEnv('production');
```
<a name="PayPalSavePaymentSourceWidget+onSuccess" id="PayPalSavePaymentSourceWidget+onSuccess" href="#PayPalSavePaymentSourceWidget+onSuccess">&nbsp;</a>

### payPalSavePaymentSourceWidget.onSuccess([callback])
If the setup token was successfully approved and a OTT was generated, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PayPalSavePaymentSourceWidget</code>](#PayPalSavePaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| [callback] | [<code>OnSuccessCallback</code>](#OnSuccessCallback) | Function to be called when the result is successful. |

**Example**  
```js
payPalSavePaymentSourceWidget.onSuccess((eventData) => console.log('One time token and email obtained successfully'));
```
<a name="PayPalSavePaymentSourceWidget+onError" id="PayPalSavePaymentSourceWidget+onError" href="#PayPalSavePaymentSourceWidget+onError">&nbsp;</a>

### payPalSavePaymentSourceWidget.onError([callback])
If in the process for obtaining the setup token fails, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PayPalSavePaymentSourceWidget</code>](#PayPalSavePaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| [callback] | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when there is an error in the flow. |

**Example**  
```js
payPalSavePaymentSourceWidget.onError((eventData) => console.log('Some error occurred'));
```
<a name="PayPalSavePaymentSourceWidget+onCancel" id="PayPalSavePaymentSourceWidget+onCancel" href="#PayPalSavePaymentSourceWidget+onCancel">&nbsp;</a>

### payPalSavePaymentSourceWidget.onCancel([callback])
If in the process for obtaining the setup token was cancelled, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PayPalSavePaymentSourceWidget</code>](#PayPalSavePaymentSourceWidget)  

| Param | Type | Description |
| --- | --- | --- |
| [callback] | [<code>OnCancelCallback</code>](#OnCancelCallback) | Function to be called when the operation is cancelled. |

**Example**  
```js
payPalSavePaymentSourceWidget.onCancel(() => console.log('Operation cancelled'));
```
<a name="OnSuccessCallback" id="OnSuccessCallback" href="#OnSuccessCallback">&nbsp;</a>

## OnSuccessCallback : <code>function</code>
Callback for onSuccess method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>IOnSuccessEventData</code>](#IOnSuccessEventData) | 

<a name="OnErrorCallback" id="OnErrorCallback" href="#OnErrorCallback">&nbsp;</a>

## OnErrorCallback : <code>function</code>
Callback for onError method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>IOnErrorEventData</code>](#IOnErrorEventData) | 

<a name="OnCancelCallback" id="OnCancelCallback" href="#OnCancelCallback">&nbsp;</a>

## OnCancelCallback : <code>function</code>
Callback for onCancel method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>IOnCancelEventData</code>](#IOnCancelEventData) | 


## PayPalDataCollector Widget

Widget that collect browser-based data to help reduce fraud. Upon checkout, these data elements are sent directly to PayPal Risk Services for fraud and risk assessment.

The general flow to use the widgets is:
1. Initialize the PayPal Data Collector Widget, providing a Source Website Identifier (Flow ID), plus optional config parameters for the widget. The general format is:
```js
var paypalDataCollector = new paydock.PayPalDataCollector(
    sourceWebsiteIdentifier,
    widgetConfigParams,
);
```
2. Handle the `collectDeviceData` function, that will return the generated correlation ID, like following:
```js
const collectedDeviceData = await paypalDataCollector.collectDeviceData();
const correlationId = collectedDeviceData.correlation_id;
```
3. Use freely the correlation_id value as is needed.
4. Handle the `onError` callback. The error handler is set up before scripts are loaded to prevent race conditions where script load failures occur before the promise rejection handler is assigned.
5. If you are using Content Security Policy (CSP), you must allowlist the paypal fraudnet script URL: `https://c.paypal.com`. See reference [here](https://developer.paypal.com/limited-release/fraudnet/integrate/#link-contentsecuritypolicyintegration).

### PayPalDataCollector Widget example

A full description of the config parameters for [PayPalDataCollector](#PayPalDataCollector) meta parameters can be found [here](#PayPalDataCollectorConfig). Below you will find a fully working html example.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Using PayDock PayPalDataCollector Widget!</h2>
    <div id="widget"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    let payPalDataCollector = new paydock.PayPalDataCollector(
        'FLOW_ID',
        {
            mouse_movement: true
        }
    );

    payPalDataCollector.setEnv('test');

    payPalDataCollector.onError(function(error) {
        console.log("On Error Callback", error);
    });

    payPalDataCollector.collectDeviceData()
        .then(function(collectedDeviceData) {
            //Here when the promise is resolved, it should be able to see the correlation_id.
            const correlationId = collectedDeviceData.correlation_id;
            console.log("On Success", correlationId);
        })
        .catch(function(error) {
            // Handle promise rejection if script loading fails
            console.log("Promise rejected", error);
        });
</script>
</html>
```

## Classes

<dl>
<dt><a href="#PayPalDataCollector">PayPalDataCollector</a></dt>
<dd><p>PayPal Data Collector Widget constructor</p>
</dd>
</dl>

## Typedefs

<dl>
<dt><a href="#OnErrorCallback">OnErrorCallback</a> : <code>function</code></dt>
<dd><p>Callback for onError method.</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#PayPalDataCollectorConfig">PayPalDataCollectorConfig</a> : <code>object</code></dt>
<dd><p>Interface of data used for PayPal configuration. For further information refer to <a href="https://developer.paypal.com/sdk/js/reference/#style">the documentation</a>.</p>
</dd>
<dt><a href="#CollectedDeviceData">CollectedDeviceData</a> : <code>object</code></dt>
<dd><p>Data object with the corresponding <code>correlation_id</code>.</p>
</dd>
<dt><a href="#IOnErrorEventData">IOnErrorEventData</a> : <code>object</code></dt>
<dd><p>Interface for IOnErrorEventData</p>
</dd>
</dl>

<a name="PayPalDataCollectorConfig" id="PayPalDataCollectorConfig" href="#PayPalDataCollectorConfig">&nbsp;</a>

## PayPalDataCollectorConfig : <code>object</code>
Interface of data used for PayPal configuration. For further information refer to [the documentation](https://developer.paypal.com/sdk/js/reference/#style).

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [mouse_movement] | <code>boolean</code> | Used for indicating if is enabled mouse movement collection. |

<a name="CollectedDeviceData" id="CollectedDeviceData" href="#CollectedDeviceData">&nbsp;</a>

## CollectedDeviceData : <code>object</code>
Data object with the corresponding `correlation_id`.

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [correlation_id] | <code>string</code> | The correlation ID that was used on the subsecuent requests. |

<a name="IOnErrorEventData" id="IOnErrorEventData" href="#IOnErrorEventData">&nbsp;</a>

## IOnErrorEventData : <code>object</code>
Interface for IOnErrorEventData

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| error_code | <code>string</code> | Error code. One of 'promise_not_enabled' or 'script_error'. |

<a name="PayPalDataCollector" id="PayPalDataCollector" href="#PayPalDataCollector">&nbsp;</a>

## PayPalDataCollector
PayPal Data Collector Widget constructor

**Kind**: global class  

* [PayPalDataCollector](#PayPalDataCollector)
    * [new PayPalDataCollector([flowId], [config])](#new_PayPalDataCollector_new)
    * [.collectDeviceData()](#PayPalDataCollector+collectDeviceData) ⇒ [<code>Promise.&lt;CollectedDeviceData&gt;</code>](#CollectedDeviceData)
    * [.onError([callback])](#PayPalDataCollector+onError)
    * [.setEnv(env)](#PayPalDataCollector+setEnv)

<a name="new_PayPalDataCollector_new" id="new_PayPalDataCollector_new" href="#new_PayPalDataCollector_new">&nbsp;</a>

### new PayPalDataCollector([flowId], [config])

| Param | Type | Description |
| --- | --- | --- |
| [flowId] | <code>string</code> | This string identifies the source website of the FraudNet request. |
| [config] | [<code>PayPalDataCollectorConfig</code>](#PayPalDataCollectorConfig) | Extra configuration for the widget. |

**Example**  
```js
var payPalDataCollector = new PayPalDataCollector('FLOW_ID', {});
```
<a name="PayPalDataCollector+collectDeviceData" id="PayPalDataCollector+collectDeviceData" href="#PayPalDataCollector+collectDeviceData">&nbsp;</a>

### payPalDataCollector.collectDeviceData() ⇒ [<code>Promise.&lt;CollectedDeviceData&gt;</code>](#CollectedDeviceData)
After configuring the PayPalDataCollector Widget, starts the process and returns
the correlation id used among the requests asynchronously.

**Kind**: instance method of [<code>PayPalDataCollector</code>](#PayPalDataCollector)  
**Returns**: [<code>Promise.&lt;CollectedDeviceData&gt;</code>](#CollectedDeviceData) - Promise when resolved, returns an object
that contains the `correlation_id` key. The promise may be rejected if script loading fails.  
**Example**  
```js
const collectedDeviceData = await payPalDataCollectorWidget.collectDeviceData();
console.log(collectedDeviceData.correlation_id)
```
**Example**  
```js
payPalDataCollectorWidget.collectDeviceData()
  .then((collectedDeviceData) => {
    console.log(collectedDeviceData.correlation_id);
  })
  .catch((error) => {
    console.error('Failed to collect device data', error);
  });
```
<a name="PayPalDataCollector+onError" id="PayPalDataCollector+onError" href="#PayPalDataCollector+onError">&nbsp;</a>

### payPalDataCollector.onError([callback])
If the process fails, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>PayPalDataCollector</code>](#PayPalDataCollector)  

| Param | Type | Description |
| --- | --- | --- |
| [callback] | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when there is an error in the flow. |

**Example**  
```js
PayPalDataCollector.onError((eventData) => console.log('Some error occur'));
```
<a name="PayPalDataCollector+setEnv" id="PayPalDataCollector+setEnv" href="#PayPalDataCollector+setEnv">&nbsp;</a>

### payPalDataCollector.setEnv(env)
Current method can change environment. By default environment = test.
This method does not affect Paydock's API calls or environments, is only for PayPal Data Collector
script, in order to know if the script is injected on a live server or is a testing
environment. The available values are `test` and `live`. This should match with the used
`gateway.mode` in Paydock to process the transaction.

**Kind**: instance method of [<code>PayPalDataCollector</code>](#PayPalDataCollector)  

| Param | Type | Description |
| --- | --- | --- |
| env | <code>string</code> | test, live |

**Example**  
```js
PayPalDataCollector.setEnv('live');
```
<a name="OnErrorCallback" id="OnErrorCallback" href="#OnErrorCallback">&nbsp;</a>

## OnErrorCallback : <code>function</code>
Callback for onError method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | [<code>IOnErrorEventData</code>](#IOnErrorEventData) \| <code>null</code> | 


## AfterpayOnSiteMessaging

Afterpay On-Site Messaging informs customers that Afterpay had an available payment method on the website. Allows to have this features when implemented:
- An interactive icon ⓘ that shows a modal with some available information.
- Shows if an instalment is available and its amount.
- Displays the best payment option available on that particular product.

The general flow to use it is:
1. Initialize the Afterpay On Site Messaging class, providing a HTML selector id, and configuration parameters that requires AfterPay. The general format is:
```js
var afterpayOnSiteMessaging = new paydock.AfterpayOnSiteMessaging(
    "#selector",
    configParams,
);
```
2. Once all in place, just call load function to start the injection, like following:
```js
afterpayOnSiteMessaging.load();
```

### AfterpayOnSiteMessaging example

A full description of the config parameters for [AfterpayOnSiteMessaging](#AfterpayOnSiteMessaging) meta parameters can be found [here](#IAfterpayOnSiteMessagingConfig). Below you will find a fully working html example.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Using PayDock AfterpayOnSiteMessaging!</h2>
    <div id="afterpayOnSiteMessagingDiv"></div>
</body>
<script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js" ></script>
<script>
    const afterpayOnSiteMessaging = new paydock.AfterpayOnSiteMessaging(
        '#afterpayOnSiteMessagingDiv',
        {
            mpid: "uuid-uuid-uuid-uuid-uuid",
            placement_id: "uuid-uuid-uuid-uuid-uuid",
            page_type: "product",
            amount: "100",
            currency: "AUD",
            consumer_locale: "AU",
            item_skus: "Test",
            item_categories: "Test",
            is_eligible: true
        }
    );

    afterpayOnSiteMessaging.onError(function(error) {
        console.log("On Error Callback", error);
    });

    afterpayOnSiteMessaging.load();
</script>
</html>
```

## Classes

<dl>
<dt><a href="#AfterpayOnSiteMessaging">AfterpayOnSiteMessaging</a></dt>
<dd><p>Afterpay On Site Messaging constructor</p>
</dd>
</dl>

## Typedefs

<dl>
<dt><a href="#OnErrorCallback">OnErrorCallback</a> : <code>function</code></dt>
<dd><p>Callback for onError method.</p>
</dd>
</dl>

## Interfaces

<dl>
<dt><a href="#IAfterpayOnSiteMessagingConfig">IAfterpayOnSiteMessagingConfig</a> : <code>object</code></dt>
<dd><p>Interface of data used for Afterpay On Site Messaging configuration.
For further information refer to <a href="https://developers.afterpay.com/docs/api/afterpay-messaging/getting-started-with-afterpay-on-site-messaging">the documentation</a>.</p>
</dd>
</dl>

<a name="IAfterpayOnSiteMessagingConfig" id="IAfterpayOnSiteMessagingConfig" href="#IAfterpayOnSiteMessagingConfig">&nbsp;</a>

## IAfterpayOnSiteMessagingConfig : <code>object</code>
Interface of data used for Afterpay On Site Messaging configuration.
For further information refer to [the documentation](https://developers.afterpay.com/docs/api/afterpay-messaging/getting-started-with-afterpay-on-site-messaging).

**Kind**: global interface  

| Param | Type | Description |
| --- | --- | --- |
| [mpid] | <code>string</code> | Used for indicating the MPID. |
| [placement_id] | <code>string</code> | Used for indicating the product Placement ID. |
| [page_type] | <code>&#x27;cart&#x27;</code> \| <code>&#x27;product&#x27;</code> | Used for indicating the page type. Allowed values are: cart, product. |
| [amount] | <code>string</code> | Used for indicating the amount. |
| [currency] | <code>string</code> | Used for indicating the currency. |
| [consumer_locale] | <code>string</code> | Used for indicating the consumer locale. |
| [item_skus] | <code>string</code> | Used for indicating the SKU. |
| [item_categories] | <code>string</code> | Used for indicating the category. |
| [is_eligible] | <code>boolean</code> | Used for indicating if the user is eligible. |

<a name="AfterpayOnSiteMessaging" id="AfterpayOnSiteMessaging" href="#AfterpayOnSiteMessaging">&nbsp;</a>

## AfterpayOnSiteMessaging
Afterpay On Site Messaging constructor

**Kind**: global class  

* [AfterpayOnSiteMessaging](#AfterpayOnSiteMessaging)
    * [new exports.AfterpayOnSiteMessaging(selector, config)](#new_AfterpayOnSiteMessaging_new)
    * [.load()](#AfterpayOnSiteMessaging+load)
    * [.onError([callback])](#AfterpayOnSiteMessaging+onError)

<a name="new_AfterpayOnSiteMessaging_new" id="new_AfterpayOnSiteMessaging_new" href="#new_AfterpayOnSiteMessaging_new">&nbsp;</a>

### new exports.AfterpayOnSiteMessaging(selector, config)

| Param | Type | Description |
| --- | --- | --- |
| selector | <code>string</code> | Selector of html element. Container for Afterpay On Site Messaging. |
| config | [<code>IAfterpayOnSiteMessagingConfig</code>](#IAfterpayOnSiteMessagingConfig) | Required configuration for the Afterpay On Site Messaging. |

**Example**  
```js
var afterpayOnSiteMessaging = new AfterpayOnSiteMessaging('#afterpayButton', config);
```
<a name="AfterpayOnSiteMessaging+load" id="AfterpayOnSiteMessaging+load" href="#AfterpayOnSiteMessaging+load">&nbsp;</a>

### afterpayOnSiteMessaging.load()
The final method after configuring the AfterpayOnSiteMessaging to
start the load process.

**Kind**: instance method of [<code>AfterpayOnSiteMessaging</code>](#AfterpayOnSiteMessaging)  
<a name="AfterpayOnSiteMessaging+onError" id="AfterpayOnSiteMessaging+onError" href="#AfterpayOnSiteMessaging+onError">&nbsp;</a>

### afterpayOnSiteMessaging.onError([callback])
If the process fails, the function passed as parameter will be called.
Important: Do not perform thread blocking operations in callback such as window.alert() calls.

**Kind**: instance method of [<code>AfterpayOnSiteMessaging</code>](#AfterpayOnSiteMessaging)  

| Param | Type | Description |
| --- | --- | --- |
| [callback] | [<code>OnErrorCallback</code>](#OnErrorCallback) | Function to be called when there is an error in the flow. |

**Example**  
```js
AfterpayOnSiteMessaging.onError((eventData) => console.log('Some error occur'));
```
<a name="OnErrorCallback" id="OnErrorCallback" href="#OnErrorCallback">&nbsp;</a>

## OnErrorCallback : <code>function</code>
Callback for onError method.

**Kind**: global typedef  

| Param | Type |
| --- | --- |
| data | <code>unknown</code> \| <code>null</code> | 


## License
Copyright (c) 2025 paydock
