Skip to content

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, Apple Pay, and PayPal & Venmo.

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

OptionTypeRequiredDescription
tokenGroupstringNoToken group name as per NPS
entityIdstringPreferredA unique ID assigned by NPS that represents the client

For Apple Pay, the merchant identifier is passed in the applePay mount options (not the constructor), and the domain is detected automatically from the page — see applePay Sub-Options.

Callbacks

OptionTypeRequiredDescription
onReadyfunctionNoInvoked when the payment form is fully initialized
onTokenizationCompletefunctionYesInvoked after successful tokenization
onErrorfunctionNoInvoked on SDK or tokenization errors (see Error Codes)
onCancelfunctionNoInvoked when the user cancels a PayPal/Venmo/Apple Pay payment
onHelpClickfunctionNoInvoked when the payer clicks a field's help icon (see onHelpClick)
onFormReadyfunctionNoInvoked when the card/ACH form becomes complete and valid, or regresses (see onFormReady)
onFieldErrorsfunctionNoInvoked when tokenize() is blocked by field validation errors (see onFieldErrors)
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.
  • For applePay, the SDK loads the Apple Pay JS SDK and renders the Apple Pay button directly in the container.

Styling and display options can be passed here to control the look and feel of the payment form. See Styling and Display Options for all available options.

ParameterTypeRequiredDescription
containerstring | HTMLElementYesCSS selector or DOM element
optionsobjectNoMount configuration

Mount Options

OptionTypeDescription
paymentMethodstringcard, ach, paypal, venmo, paypalVenmo, or applePay
stylingobjectStyling configuration (see Styling)
displayOptionsobjectField visibility toggles (see Display Options)
widthstringPayment form width (e.g. '100%')
paypalobjectPayPal/Venmo options (see below)
applePayobjectApple Pay options (see applePay Sub-Options)
supportedCardBrandsarrayCard only. Accepted card brands (see Card and ACH Field Options)
requireAccountConfirmationbooleanACH only. Renders a Confirm Account Number field (see Card and ACH Field Options)
helpIconsarrayField ids that render a help icon (see Card and ACH Field Options)
localestringPayer-facing language of the payment form: en (default) or es (see Card and ACH Field Options)

Card and ACH Field Options

These options apply to the direct card and ACH mounts only; they do not apply to PayPal, Venmo, Apple Pay, or the hosted Payment Widget modes. All are optional.

OptionApplies toDescription
supportedCardBrandsCardArray of accepted brands: visa, mastercard, amex, discover, diners, jcb, unionpay. Common aliases are normalized (e.g. 'American Express' → amex, 'MC' → mastercard); case, spaces, hyphens, and underscores are ignored; unknown entries are dropped. If the option is omitted, or nothing valid remains after normalization, all detected brands are accepted, so a mistyped list can never block the payment form. When the payer enters a card of an unsupported brand, a localized inline error appears below the card field and the brand's icon is hidden.
requireAccountConfirmationACHRenders a "Confirm Account Number" field that must match the account number before tokenization. Paste is blocked in the confirm field, and the confirm value never leaves the payment form; it is not transmitted or included in tokenize data. Default false.
helpIconsBothArray of field ids that render a keyboard-accessible ? icon beside the field label: cardNumber, expiryDate, securityCode, routingNumber, accountNumber, confirmAccountNumber. Clicking the icon invokes onHelpClick. The SDK renders no help content itself; your page shows the modal or tooltip.
localeBothLanguage of the payer-facing text inside the payment form (labels, placeholders, validation messages): en (default) or es. Region variants are normalized (es-MX → es); unknown values fall back to en. Your surrounding page is unaffected.
const wg = new Widget({
  onTokenizationComplete: (result) => { /* ... */ },
  onHelpClick: ({ field }) => showHelpModal(field),
  onFormReady: ({ ready }) => { payButton.disabled = !ready; }
});

wg.mount('#payment-form', {
  paymentMethod: 'card',
  supportedCardBrands: ['visa', 'mastercard'],
  helpIcons: ['securityCode'],
  locale: 'es'
});

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

OptionTypeRequiredDescription
returnUrlstringYesURL PayPal redirects to on approval
cancelUrlstringYesURL PayPal redirects to on cancellation

Payment Method Values

ValueRenders
cardSecure card input form (iframe)
achSecure ACH input form (iframe)
paypalPayPal checkout button
venmoVenmo checkout button
paypalVenmoBoth PayPal and Venmo buttons (only eligible buttons are shown)
applePayApple Pay button

Card / ACH Example:

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

PayPal Example:

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

paypalVenmo Example (Renders Both PayPal And Venmo):

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, or Apple Pay 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.

ParameterTypeRequiredDescription
tokenstringYesA valid session token
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.

ParameterTypeRequiredDescription
methodstringYescard, ach, paypal, venmo, or paypalVenmo
optionsobjectNoAdditional options
OptionTypeDescription
accountTypestringchecking or savings (ACH only)
wg.updatePaymentMethod('ach', { accountType: 'checking' });
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.

FieldTypeRequiredDescription
amountnumberYesPayment amount
accountHolderNamestringPreferredPayer name
billingAddressobjectPreferredBilling address (see fields below)
accountTypestringACH onlychecking or savings
tenderTypestringACH onlye.g. Consumer
metadataobjectNoMerchant-defined metadata

billingAddress fields

FieldTypeRequiredDescription
addressLine1stringYesStreet address
addressLine2stringNoApartment, suite, unit, etc.
citystringYesCity
statestringYesState or province
postalCodestringYesPostal / ZIP code
countrystringYesCountry code (e.g. US)
const token = await fetchSessionToken();
wg.updateSessionToken(token);

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

applePay Sub-Options (required for the applePay payment method)

Apple Pay is rendered via mount() with paymentMethod: 'applePay' and an applePay options object. The SDK 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 applePay.total. After the customer authorizes, onTokenizationComplete is invoked with the token (result.paymentMethod is 'applePay'). There is no separate tokenize() call for Apple Pay.

The SDK automatically loads the Apple Pay JS SDK. On non-Safari browsers (Chrome, Edge, including Windows), the payment sheet is replaced by a code the customer scans with an iPhone (iOS 18+) to authorize the payment there.

The merchant must host the Apple domain verification file at /.well-known/apple-developer-merchantid-domain-association on their registered domain. The SDK always uses the hostname of the page for merchant validation, so the checkout page must be served from that verified domain — there is no domain option to configure.

A session token must be set via updateSessionToken() before the customer clicks the button. The country and currency are always US and USD. Supported card networks are Visa, Mastercard, American Express, and Discover.

FieldTypeRequiredDescription
totalobjectYes{ label, amount } — the payment sheet total. Both fields are required; amount is a string (e.g. '75.00') greater than zero.
displayNamestringNoMerchant name used during Apple merchant validation. Defaults to total.label.
partnerInternalMerchantIdentifierstringNoApple Pay merchant identifier, used during merchant validation. For multi-merchant, defaults to the first context's partnerMerchantIdentifier.
lineItemsarrayNoItemized breakdown shown on the sheet above the total (see below)
multiTokenContextsarrayMulti-merchant onlyArray of merchant contexts (see below). Requires Apple Pay version 14+. Cannot be combined with recurringPaymentRequest.
recurringPaymentRequestobjectRecurring onlyRecurring payment configuration (see below). Requires Apple Pay version 14+.

multiTokenContexts entries

The sum of the context amounts cannot exceed total.amount.

FieldTypeRequiredDescription
partnerMerchantIdentifierstringYesApple Pay merchant identifier
entityIdstringYesA unique ID assigned by NPS that represents the client
amountstringYesAmount for this merchant
entityNamestringNoThe merchant's display name (merchantName is accepted as an alias). Defaults to the total label.
merchantDomainstringNoDomain for this merchant. Defaults to the page's hostname.

lineItems entries

FieldTypeRequiredDescription
labelstringYesDescription of the line item (e.g. Tuition, Service Fee)
amountstringYesAmount for this line item

recurringPaymentRequest fields

The SDK validates the required fields and rejects the request with an error if any are missing. The recurring payment plan (billing schedule, agreement, and any trial pricing) is managed by NPS, not Apple.

FieldTypeRequiredDescription
paymentDescriptionstringYesDescription of the recurring payment shown on the payment sheet
regularBillingobjectYesRecurring line item: label and amount
managementURLstringYesPage on your site where the customer can manage or cancel the subscription. Apple links to it from the Wallet app.

One-time payment:

wg.mount('#apple-pay-button', {
  paymentMethod: 'applePay',
  applePay: {
    total: { label: 'Nelnet Campus Commerce', amount: '75.00' },
    partnerInternalMerchantIdentifier: '<MERCHANT_IDENTIFIER>'
  }
});

Multi-merchant payment:

wg.mount('#apple-pay-button', {
  paymentMethod: 'applePay',
  applePay: {
    total: { label: 'Total Amount', 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:

Set total.amount (the sheet total) to the recurring amount in regularBilling.

wg.mount('#apple-pay-button', {
  paymentMethod: 'applePay',
  applePay: {
    total: { label: 'Meal Plan Subscription', amount: '9.99' },
    partnerInternalMerchantIdentifier: '<MERCHANT_IDENTIFIER>',
    recurringPaymentRequest: {
      paymentDescription: 'Campus Meal Plan — billed monthly',
      regularBilling: {
        label: 'Meal Plan Subscription',
        amount: '9.99'
      },
      managementURL: 'https://checkout.example.com/account/subscriptions'
    }
  }
});

focusField(field)

Moves keyboard focus to a field inside the secure payment form (card and ACH mounts only). Typically used together with onFieldErrors so an error-summary banner on your page can jump the payer to the field that needs attention.

ParameterTypeRequiredDescription
fieldstringYesOne of cardNumber, expiryDate, securityCode, routingNumber, accountNumber, confirmAccountNumber
wg.focusField('cardNumber');

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.

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.

PropertyTypeDescription
tokenstringSecure payment token
categorystringCard category (e.g. CREDIT, DEBIT)
lastFour/tokenLastFourstringLast four digits of the card or account number
networkstringCard network (e.g. VISA, MASTERCARD, AMEX, DISCOVER)
isoCountrystringIssuing country name
isoCountryCodestringIssuing country code
isInternationalbooleanWhether the card is international
tokenGroupNamestringToken group name
paymentMethodstringPayment method used (applePay, paypal, or venmo; not set for card/ACH)
paymentTransactionIdstringTransaction ID (PayPal/Venmo only)
accountHolderNamestringName of the account holder (PayPal, Venmo)
accountHolderIdstringUnique ID of the account holder record (PayPal, Venmo)
phoneNumberstringAccount holder's phone number (PayPal, Venmo)
emailAddressstringAccount holder's email address (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.

PropertyTypeDescription
responseCodestringStandardized error code (see Error Codes)
responseMessagestringError category identifier
descriptionstringHuman-readable error detail
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.

PropertyTypeDescription
responseCodestringE402
responseMessagestringPAYMENT_CANCELLED
descriptionstringHuman-readable cancellation message
onCancel: (payload) => {
  console.log(payload.description); // "Payment cancelled by user"
}

onHelpClick(payload)

Invoked when the payer clicks the ? help icon beside a field (rendered via the helpIcons mount option). The SDK renders no help content; displaying a modal or tooltip is your page's job.

PropertyTypeDescription
fieldstringId of the field whose icon was clicked (e.g. securityCode)

Also dispatched as a window CustomEvent named wg-help-click with the same payload in event.detail.

onHelpClick: ({ field }) => {
  showHelpModal(field); // e.g. explain what a CVV is
}

onFormReady(payload)

Invoked when the aggregate validity of the card/ACH form changes: ready: true when every required field for the active payment method is complete and valid, ready: false if the form regresses (for example, the payer edits a field back to an invalid state). Informational only; it does not start tokenization. The typical use is enabling or disabling your Pay button.

PropertyTypeDescription
readybooleanWhether the form is complete and valid

Also dispatched as a window CustomEvent named wg-form-ready with the same payload in event.detail.

onFormReady: ({ ready }) => {
  document.getElementById('pay-btn').disabled = !ready;
}

onFieldErrors(payload)

Invoked when a tokenize() attempt is blocked by field validation. The payload lists every errored field with its localized message, which is useful for building an accessible error-summary banner on your page. Pair each entry with focusField(field) to jump the payer to the field. On a blocked tokenize the SDK also automatically scrolls the page to the first errored field; no wiring is needed for that.

PropertyTypeDescription
errorsarray[{ field, message }]: errored field ids with localized messages

Also dispatched as a window CustomEvent named wg-field-errors with the same payload in event.detail.

onFieldErrors: ({ errors }) => {
  renderErrorSummary(errors.map(e => ({
    text: e.message,
    onClick: () => wg.focusField(e.field)
  })));
}

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.

OptionTypeValuesDefault
themestringlight, darklight
labelStylestringstacked, floating, hiddenstacked
fieldStylestringoutlined, filled, underlinedoutlined
fieldLayoutstringstacked, inline-split, inlinestacked

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.

KeyTypeDescription
labelstringLabel text color
textstringInput text color
borderstringDefault border color
focusBorderstringBorder color on focus
errorstringError border and text color
helpTextstringPlaceholder and help text color

Typography

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

OptionTypeDescription
fontFamilystringFont family (e.g. 'Inter')
fontSizenumberInput text font size in pixels (10–24)
labelFontSizenumberLabel font size in pixels (10–24)
labelFontWeightnumberLabel font weight (100–900)
helpTextFontSizenumberHelp text font size in pixels (10–24)
helpTextFontWeightnumberHelp text font weight (100–900)

Spacing & Dimensions

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

OptionTypeDescription
spacingnumberSpacing from top and between elements (0–32px)
labelSpacingnumberGap between a field label and its input in pixels. Defaults to half of spacing, clamped to 4–8px, so labels stay visually attached to their inputs
borderRadiusnumberInput corner radius (0–32px)
borderWidthnumberBorder width in pixels (0–32px)
inputHeightnumberInput height in pixels (min 20)
iframeWidthstringTotal width of the payment form (e.g. '100%')

Full Styling Example

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.

OptionTypeDefaultDescription
showLabelsbooleantrueShow field labels
showIconsbooleantrueShow card brand icons
showErrorsbooleantrueShow validation error messages
showPlaceholdersbooleantrueShow placeholder text
showSecurityCodeIndicatorbooleantrueShow CVC/CVV icon
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. The same codes are used consistently across all payment methods — the description field identifies the specific cause.

{
  "responseCode": "E400",
  "responseMessage": "SDK_ERROR",
  "description": "Human-readable detail about what went wrong"
}
responseCoderesponseMessageDelivered ViaWhen
E400SDK_ERRORonErrorConfig/setup issues — invalid or missing mount options, container not found, the payment method is not available on the device/browser, or a payment provider script failed to load
E400VALIDATION_ERRORonErrorMissing required fields (sessionToken, accountHolderName, billingAddress)
E400TOKENIZATION_FAILEDonErrorTokenization fails — the payment could not be converted into a token (including provider and merchant validation failures)
E402PAYMENT_CANCELLEDonCancelUser cancels the payment before authorizing
E500UNEXPECTED_ERRORonErrorAny 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 and Apple Pay 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().

FieldCardACH
amountRequiredRequired
accountHolderNamePreferredPreferred
billingAddressPreferredPreferred
accountType—Required

Apple Pay, PayPal, and Venmo do not use tokenize(). Their transaction details are passed directly in the mount() options (applePay or paypal), and the SDK handles the flow on button click. For PayPal, Venmo, and Apple Pay, call updateSessionToken() before the user clicks the payment button.