# UI SDK Reference

Complete API reference for the Widget SDK. This document describes every constructor option, method, callback, styling property, and error code available in the SDK.

For step-by-step integration guides, see [Card & ACH](/docs/card-ach), [Apple Pay](/docs/apple-pay), and [PayPal & Venmo](/docs/paypal).

## Constructor

#### `new Widget(config)`

Creates a new SDK instance and establishes a session. `onTokenizationComplete` is required. Everything else is optional and depends on which payment methods you plan to use.

[Creating Session Token Using JWT](/docs/session-token)

| Option | Type | Required | Description |
|  --- | --- | --- | --- |
| `tokenGroup` | `string` | No | Token group name as per NPS |
| `entityId` | `string` | **Preferred** | A unique ID assigned by NPS that represents the client |
| `partnerInternalMerchantIdentifier` | `string` | Apple Pay only | Apple Pay merchant identifier |
| `domainName` | `string` | Apple Pay only | Registered domain for Apple Pay |


[Callbacks](#callbacks)

| Option | Type | Required | Description |
|  --- | --- | --- | --- |
| `onReady` | `function` | No | Invoked when the payment form is fully initialized |
| `onTokenizationComplete` | `function` | **Yes** | Invoked after successful tokenization |
| `onError` | `function` | No | Invoked on SDK or tokenization errors (see [Error Codes](#error-codes)) |
| `onCancel` | `function` | No | Invoked when the user cancels a PayPal/Venmo/Apple Pay payment |


```js
const wg = new Widget({
  tokenGroup: '<TOKEN_GROUP>',
  entityId: '<ENTITY_ID>',
  onReady: () => {},
  onTokenizationComplete: (result) => {},
  onError: (error) => {},
  onCancel: (payload) => {}
});
```

## Methods

#### `mount(container, options)`

Renders the payment UI inside the specified container element.

- For **card** and **ACH**, this renders a secure hosted payment form inside an iframe.
- For **paypal**, **venmo**, or **paypalVenmo**, this loads the PayPal SDK and renders checkout button(s) directly in the container.


Styling and display options can be passed here to control the look and feel of the payment form. See [Styling](#styling) and [Display Options](#display-options) for all available options.

| Parameter | Type | Required | Description |
|  --- | --- | --- | --- |
| `container` | `string` | `HTMLElement` | **Yes** | CSS selector or DOM element |
| `options` | `object` | No | Mount configuration |


#### Mount Options

| Option | Type | Description |
|  --- | --- | --- |
| `paymentMethod` | `string` | `card`, `ach`, `paypal`, `venmo`, or `paypalVenmo` |
| `styling` | `object` | Styling configuration (see [Styling](#styling)) |
| `displayOptions` | `object` | Field visibility toggles (see [Display Options](#display-options)) |
| `width` | `string` | Payment form width (e.g. `'100%'`) |
| `paypal` | `object` | PayPal/Venmo options (see below) |


#### `paypal` Sub-Options (required for `paypal`, `venmo`, and `paypalVenmo` payment methods)

| Option | Type | Required | Description |
|  --- | --- | --- | --- |
| `returnUrl` | `string` | **Yes** | URL PayPal redirects to on approval |
| `cancelUrl` | `string` | **Yes** | URL PayPal redirects to on cancellation |


#### Payment Method Values

| Value | Renders |
|  --- | --- |
| `card` | Secure card input form (iframe) |
| `ach` | Secure ACH input form (iframe) |
| `paypal` | PayPal checkout button |
| `venmo` | Venmo checkout button |
| `paypalVenmo` | Both PayPal and Venmo buttons (only eligible buttons are shown) |


**Card / ACH Example:**

```js
wg.mount('#payment-container', {
  paymentMethod: 'card',
  styling: { ... },
  displayOptions: { ... }
});
```

**PayPal Example:**

```js
wg.mount('#paypalVenmo-container', {
  paymentMethod: 'paypal',
  paypal: {
    returnUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/cancel'
  }
});
```

**paypalVenmo Example (Renders Both PayPal And Venmo):**

```js
wg.mount('#paypalVenmo-container', {
  paymentMethod: 'paypalVenmo',
  paypal: {
    returnUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/cancel'
  }
});
```

#### `updateSessionToken(token)`

Sets or refreshes the session token used by the SDK for all payment API calls. This method must be called before `tokenize()` (for card/ACH) or before the user clicks a PayPal/Venmo button. The token is stored internally and used for all subsequent API calls until updated again.

Call this method whenever you need to provide a fresh session token — for example, when the user selects a paypalVenmo payment method, or right before submitting a card/ACH payment.

| Parameter | Type | Required | Description |
|  --- | --- | --- | --- |
| `token` | `string` | **Yes** | A valid session token |


```js
const token = await fetchSessionToken();
wg.updateSessionToken(token);
```

#### `updatePaymentMethod(method,options)`

Switches the active payment method without tearing down and remounting. This is useful when your checkout page lets the customer toggle between card, ACH, and paypalVenmo payment methods.

When switching between card/ACH and PayPal/Venmo/paypalVenmo, the SDK automatically handles cleanup and re-rendering.

| Parameter | Type | Required | Description |
|  --- | --- | --- | --- |
| `method` | `string` | **Yes** | `card`, `ach`, `paypal`, `venmo`, or `paypalVenmo` |
| `options` | `object` | No | Additional options |


| Option | Type | Description |
|  --- | --- | --- |
| `accountType` | `string` | `checking` or `savings` (ACH only) |


```js
wg.updatePaymentMethod('ach', { accountType: 'checking' });
```

```js
wg.updatePaymentMethod('paypalVenmo');
```

#### `tokenize(data)`

Triggers tokenization for **card and ACH payment methods only**. When called, the SDK securely collects the payment data from the hosted form and exchanges it for an NPS token.

A session token must be set via `updateSessionToken()` before calling this method.

On success, `onTokenizationComplete` is invoked with the token and associated metadata. On failure, `onError` is invoked with a structured error payload. If the iframe does not respond within 30 seconds, the SDK automatically times out and emits an `UNEXPECTED_ERROR`.

Apple Pay, PayPal, and Venmo do not use this method. Those payment methods handle tokenization through their respective button clicks — the customer's interaction triggers the flow directly, and results are delivered via `onTokenizationComplete`.

| Field | Type | Required | Description |
|  --- | --- | --- | --- |
| `amount` | `number` | **Yes** | Payment amount |
| `name` | `string` | **Yes** | Payer name |
| `billingAddress` | `object` | **Yes** | Billing address (see fields below) |
| `accountType` | `string` | ACH only | `checking` or `savings` |
| `tenderType` | `string` | ACH only | e.g. `Consumer` |
| `metadata` | `object` | No | Merchant-defined metadata |


#### `billingAddress` fields

| Field | Type | Required | Description |
|  --- | --- | --- | --- |
| `addressLine1` | `string` | **Yes** | Street address |
| `addressLine2` | `string` | No | Apartment, suite, unit, etc. |
| `city` | `string` | **Yes** | City |
| `state` | `string` | **Yes** | State or province |
| `postalCode` | `string` | **Yes** | Postal / ZIP code |
| `country` | `string` | **Yes** | Country code (e.g. `US`) |


```js
const token = await fetchSessionToken();
wg.updateSessionToken(token);

const result = await wg.tokenize({
  amount: 125.00,
  name: 'Jane Smith',
  billingAddress: {
    addressLine1: '123 Main St',
    addressLine2: 'Suite 100',     // optional
    city: 'Omaha',                 
    state: 'NE',                   
    postalCode: '68102',
    country: 'US'
  }
});
```

#### `renderApplePayButton(selector, options)`

Renders an Apple Pay button directly on the merchant page. When the customer clicks the button, the native Apple Pay payment sheet opens with the amount specified in `options`. After the customer authorizes, `onTokenizationComplete` is invoked with the token. There is no separate `tokenize()` call for Apple Pay.

The merchant must host the Apple domain verification file at `/.well-known/apple-developer-merchantid-domain-association` on their registered domain.

| Parameter | Type | Required | Description |
|  --- | --- | --- | --- |
| `selector` | `string` | `Element` | **Yes** | CSS selector or DOM element |
| `options` | `object` | **Yes** | Payment options (see below) |


#### Options

| Field | Type | Required | Description |
|  --- | --- | --- | --- |
| `amount` | `number` | **Yes** | Payment amount (one-time) |
| `multiTokenContexts` and `lineItems` | `array` | Multi-merchant only | Array of merchant contexts (see below) |
| `recurringPaymentRequest` | `object` | Recurring only | Recurring payment configuration (see below) |


#### `multiTokenContexts` entries

| Field | Type | Required | Description |
|  --- | --- | --- | --- |
| `partnerMerchantIdentifier` | `string` | **Yes** | Apple Pay merchant identifier |
| `merchantName` | `string` | **Yes** | The merchant's display name |
| `entityId` | `string` | **Yes** | A unique ID assigned by NPS that represents the client |
| `amount` | `string` | **Yes** | Amount for this merchant |


#### `lineItems` entries

| Field | Type | Required | Description |
|  --- | --- | --- | --- |
| `label` | `string` | **Yes** | Description of the line item (e.g. `Tuition`, `Service Fee`) |
| `amount` | `string` | **Yes** | Amount for this line item |


**One-time payment:**

```js
wg.renderApplePayButton('#apple-pay-button', {
  amount: 75.00
});
```

**Multi-merchant payment:**

```js
wg.renderApplePayButton('#apple-pay-button', {
  amount: 110.00,
  lineItems: [
    { label: 'AAA University', amount: '100.00' },
    { label: 'BBB Service Fee', amount: '10.00' }
  ],
  multiTokenContexts: [
    {
      partnerMerchantIdentifier: 'TESTCLIENT_a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6',
      entityId: 'A-123',
      entityName: 'AAA University',
      amount: '100.00'
    },
    {
      partnerMerchantIdentifier: 'TESTCLIENT_a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6',
      entityId: 'B-456',
      entityName: 'BBB Service Fee',
      amount: '10.00'
    }
  ]
});
```

**Recurring payment:**

```js
wg.renderApplePayButton('#apple-pay-button', {
  amount: 4.99,
  lineItems: [
    { label: 'Recurring', amount: '4.99' }
  ],
  recurringPaymentRequest: {
    paymentDescription: 'A description of the recurring payment to display to the user in the payment sheet.',
    regularBilling: {
      label: 'Recurring',
      amount: '4.99'
    },
    billingAgreement: 'A localized billing agreement displayed to the user in the payment sheet prior to the payment authorization.',
    managementURL: 'https://applepaydemo.apple.com'
  }
});
```

#### `destroy()`

Unmounts the payment form, removes event listeners, and releases all resources held by the SDK instance. Call this when the checkout page is being torn down or when the payment form is no longer needed.

```js
wg.destroy();
```

## Callbacks

#### `onReady()`

Invoked when the payment form is fully initialized and ready to accept input. This is a good place to enable your "Pay" button or show the payment form container if it was hidden during loading.

#### `onTokenizationComplete(result)`

Invoked after successful tokenization. This callback is used by all payment methods — card, ACH, Apple Pay, PayPal, and Venmo. The result contains the NPS token and metadata about the payment credential. The exact set of properties depends on the payment method. Some of them are given below.

| Property | Type | Description |
|  --- | --- | --- |
| `token` | `string` | Secure payment token |
| `category` | `string` | Card category (e.g. `CREDIT`, `DEBIT`) |
| `lastFour`/`tokenLastFour` | `string` | Last four digits of the card or account number |
| `network` | `string` | Card network (e.g. `VISA`, `MASTERCARD`, `AMEX`, `DISCOVER`) |
| `isoCountry` | `string` | Issuing country name |
| `isoCountryCode` | `string` | Issuing country code |
| `isInternational` | `boolean` | Whether the card is international |
| `tokenGroupName` | `string` | Token group name |
| `paymentMethod` | `string` | Payment method used (PayPal/Venmo only: `paypal` or `venmo`) |
| `paymentTransactionId` | `string` | Transaction ID (PayPal/Venmo only) |
| `countryCode` | `string` | Payer's country code (PayPal, Venmo) |


#### `onError(error)`

Invoked when a validation, session, network, or provider error occurs. The error object always contains `responseCode`, `responseMessage`, and a `description` string.

| Property | Type | Description |
|  --- | --- | --- |
| `responseCode` | `string` | Standardized error code (see [Error Codes](#error-codes)) |
| `responseMessage` | `string` | Error category identifier |
| `description` | `string` | Human-readable error detail |


```js
onError: (error) => {
  console.error(`[${error.responseCode}] ${error.responseMessage}: ${error.description}`);
}
```

#### `onCancel(payload)`

Invoked when the user cancels a PayPal, Venmo, or Apple Pay payment (e.g. closes the popup without completing). This callback is **not** fired for card or ACH — those flows have no cancel concept since the form is inline.

The payload follows the same structure as error payloads.

| Property | Type | Description |
|  --- | --- | --- |
| `responseCode` | `string` | `E402` |
| `responseMessage` | `string` | `PAYMENT_CANCELLED` |
| `description` | `string` | Human-readable cancellation message |


```js
onCancel: (payload) => {
  console.log(payload.description); // e.g. "PayPal payment cancelled by user"
}
```

## Styling

Styling is passed via `options.styling` in the `mount()` call. All styling options affect the payment form only — the surrounding page layout, fonts, and design remain fully under merchant control.

### Theme & Layout

These options control the overall visual structure of the payment form.

| Option | Type | Values | Default |
|  --- | --- | --- | --- |
| `theme` | `string` | `light`, `dark` | `light` |
| `labelStyle` | `string` | `stacked`, `floating`, `hidden` | `stacked` |
| `fieldStyle` | `string` | `outlined`, `filled`, `underlined` | `outlined` |
| `fieldLayout` | `string` | `stacked`, `inline-split`, `inline` | `stacked` |


When `fieldLayout` is `inline`, `labelStyle` is automatically forced to `hidden`.

### Colors

Color values are passed via `styling.colors`. These control the color scheme of input fields, labels, and error states inside the payment form.

| Key | Type | Description |
|  --- | --- | --- |
| `label` | `string` | Label text color |
| `text` | `string` | Input text color |
| `border` | `string` | Default border color |
| `focusBorder` | `string` | Border color on focus |
| `error` | `string` | Error border and text color |
| `helpText` | `string` | Placeholder and help text color |


### Typography

These options control font choices and sizing for various elements inside the payment form.

| Option | Type | Description |
|  --- | --- | --- |
| `fontFamily` | `string` | Font family (e.g. `'Inter'`) |
| `fontSize` | `number` | Input text font size in pixels (10–24) |
| `labelFontSize` | `number` | Label font size in pixels (10–24) |
| `labelFontWeight` | `number` | Label font weight (100–900) |
| `helpTextFontSize` | `number` | Help text font size in pixels (10–24) |
| `helpTextFontWeight` | `number` | Help text font weight (100–900) |


### Spacing & Dimensions

These options control the physical sizing and spacing of input fields and the payment form.

| Option | Type | Description |
|  --- | --- | --- |
| `spacing` | `number` | Spacing from top and between elements (0–32px) |
| `borderRadius` | `number` | Input corner radius (0–32px) |
| `borderWidth` | `number` | Border width in pixels (0–32px) |
| `inputHeight` | `number` | Input height in pixels (min 20) |
| `iframeWidth` | `string` | Total width of the payment form (e.g. `'100%'`) |


### Full Styling Example

```js
wg.mount('#payment-container', {
  paymentMethod: 'card',
  styling: {
    theme: 'light',
    labelStyle: 'floating',
    fieldStyle: 'outlined',
    fieldLayout: 'stacked',
    fontFamily: 'Inter',
    fontSize: 15,
    labelFontSize: 14,
    labelFontWeight: 500,
    helpTextFontSize: 14,
    helpTextFontWeight: 400,
    spacing: 12,
    borderRadius: 4,
    borderWidth: 1,
    inputHeight: 36,
    iframeWidth: '100%',
    colors: {
      label: '#5A5E66',
      border: '#C4C8CC',
      error: '#D32F2F',
      text: '#000000',
      focusBorder: '#3B82F6',
      helpText: '#9CA3AF'
    }
  }
});
```

## Display Options

Display options are passed via `options.displayOptions` in the `mount()` call. They control the visibility of labels, icons, placeholders, and other UI elements inside the payment form.

| Option | Type | Default | Description |
|  --- | --- | --- | --- |
| `showLabels` | `boolean` | `true` | Show field labels |
| `showIcons` | `boolean` | `true` | Show card brand icons |
| `showErrors` | `boolean` | `true` | Show validation error messages |
| `showPlaceholders` | `boolean` | `true` | Show placeholder text |
| `showSecurityCodeIndicator` | `boolean` | `true` | Show CVC/CVV icon |


```js
wg.mount('#payment-container', {
  paymentMethod: 'card',
  displayOptions: {
    showLabels: true,
    showIcons: true,
    showErrors: true,
    showPlaceholders: true,
    showSecurityCodeIndicator: true
  }
});
```

## Error Codes

All errors surfaced through `onError` or `onCancel` use a standardized payload format:

```json
{
  "responseCode": "E400",
  "responseMessage": "SDK_ERROR",
  "description": "Human-readable detail about what went wrong"
}
```

| responseCode | responseMessage | Delivered Via | When |
|  --- | --- | --- | --- |
| `E400` | `SDK_ERROR` | `onError` | Config/setup issues (missing client ID, container not found, etc.) |
| `E400` | `VALIDATION_ERROR` | `onError` | Missing required fields (`sessionToken`, `name`, `billingAddress`) |
| `E400` | `TOKENIZATION_FAILED` | `onError` | Iframe-based tokenization fails |
| `E401` | `PAYPAL_ERROR` | `onError` | PayPal SDK load failure, order creation failure, verification failure |
| `E402` | `PAYMENT_CANCELLED` | `onCancel` | User cancels PayPal/Venmo payment |
| `E402` | `PAYMENT_CANCELLED` | `onCancel` | User cancels Apple Pay payment |
| `E402` | `APPLEPAY_ERROR` | `onError` | Apple Pay error |
| `E500` | `UNEXPECTED_ERROR` | `onError` | Any unhandled exception, network failure, or tokenization timeout (30s) |


### Notes

- Card/ACH errors are returned both as promise rejections from `tokenize()` **and** via the `onError` callback.
- PayPal/Venmo errors are delivered only via the `onError` callback (there is no promise to reject).
- `onCancel` is only fired for PayPal, Venmo, and Apple Pay. Card and ACH have no cancel concept.
- The `description` field always contains a human-readable message suitable for logging or display.


## Tokenization Data Summary

This table shows which fields are required in the `tokenize()` call for card and ACH. A session token must be set via `updateSessionToken()` before calling `tokenize()`.

| Field | Card | ACH |
|  --- | --- | --- |
| `amount` | **Required** | **Required** |
| `name` | **Required** | **Required** |
| `billingAddress` | **Required** | **Required** |
| `accountType` | — | **Required** |


Apple Pay, PayPal, and Venmo do not use `tokenize()`. Their transaction details are passed directly to the render method (`renderApplePayButton`) or handled automatically by the SDK on button click (`paypal`, `venmo`, `paypalVenmo`). For PayPal/Venmo, call `updateSessionToken()` before the user clicks the payment button.