@paydock/client-sdk
Version:
Paydock client sdk
366 lines • 16.8 kB
TypeScript
import { ApiInternal } from '../../api/api-internal';
import type { GetConfigResponse } from '../../api/api-service-internal';
import { Container } from '../../components/container';
import { EventEmitter } from '../../helper/event-emitter';
import { ERROR_OPERATION } from '../enum/error-operation.enum';
import type { OnCancelEventData, OnClickEventData, OnCreateOTTSuccessfulEventData, OnErrorEventData, OnLoadedEventData, OnUnavailableEventData, OpenWalletMeta } from '../interfaces';
import type { WalletType } from '../types';
import type { OnShippingAddressChangeEventData } from '../types/on-shipping-address-change-event-data.interface';
import type { OnShippingAddressChangeEventResponse } from '../types/on-shipping-address-change-event-response.interface';
import type { OnShippingOptionChangeEventData } from '../types/on-shipping-option-change-event-data.interface';
import type { OnShippingOptionChangeEventResponse } from '../types/on-shipping-option-change-event-response.interface';
import type { OpenWalletService } from './open-wallet.service';
/**
* @classdesc Abstract base class for Open Wallet buttons. **Do not instantiate directly.**
* Use {@link ApplePayOpenWalletButton} or {@link GooglePayOpenWalletButton} instead.
*
* Use one of the concrete implementations instead:
* - {@link ApplePayOpenWalletButton} for Apple Pay integration
* - {@link GooglePayOpenWalletButton} for Google Pay integration
*
* These subclasses inherit all event handlers and lifecycle methods documented below.
*
* @class OpenWalletButtons
* @abstract
* @hideconstructor
*/
export declare abstract class OpenWalletButtons<TMeta extends OpenWalletMeta = OpenWalletMeta> {
protected container: Container;
protected api: ApiInternal;
protected env: string;
protected serviceId: string;
protected meta: TMeta;
protected eventEmitter: EventEmitter;
protected walletService: OpenWalletService | undefined;
private onShippingOptionsChangeHandlerRegistered;
/** @private */
abstract readonly walletType: WalletType;
/** @private */
constructor(selector: string, publicKeyOrAccessToken: string, serviceId: string, meta: TMeta);
/**
* Creates the wallet-specific service instance for this button.
* Each concrete subclass implements this to instantiate its specific wallet service.
*
* @param serviceConfig - The service configuration response from the API.
* @returns The wallet service instance.
*/
protected abstract createWalletService(serviceConfig: GetConfigResponse): OpenWalletService;
/**
* Validates that the service configuration type matches the expected wallet type.
* Each concrete subclass implements this to ensure the service ID corresponds
* to the correct wallet type.
*
* @param serviceConfig - The service configuration response from the API.
* @throws {Error} If the service type does not match the expected wallet type.
*/
protected abstract validateServiceType(serviceConfig: GetConfigResponse): void;
/**
* Validates wallet-specific metadata requirements.
* Each concrete subclass implements this to enforce its own required fields
* (e.g. Apple Pay requires `amount_label`).
*
* Called automatically during construction after base meta validation.
*
* @throws {Error} If any wallet-specific required field is missing or invalid.
*/
protected abstract validateWalletMeta(): void;
private getApiAuthType;
/**
* Validates the base metadata fields common to all wallet types:
* `meta` must exist, `amount` must be a number, `currency` and `country` must be strings.
*
* @private
* @throws {Error} If any base required field is missing or has an invalid type.
*/
private validateBaseMeta;
protected getOpenWalletServiceConfig(): Promise<GetConfigResponse>;
protected handleOnError(error: Error, operation?: ERROR_OPERATION): void;
/**
* 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.
*
* @example
* button.onClick((data) => { ... });
* button.onSuccess((data) => { ... });
* button.onError((error) => { ... });
* button.load();
*/
load(): void;
/**
* 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()`.
*
* @example
* button.setEnv('production', 'paydock.com');
*
* @param {string} env - The target environment: `'sandbox'` or `'production'`.
* @param {string} [alias] - Own domain alias.
*/
setEnv(env: string, alias?: string): void;
/**
* 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.
*
* @example
* button.setMeta({ ...meta, amount: 29.99 });
*
* @param {ApplePayOpenWalletMeta | GooglePayOpenWalletMeta} meta - The updated metadata object. The concrete type depends on the button class.
*/
setMeta(meta: TMeta): void;
/**
* 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).
*
* @example
* button.destroy();
*/
destroy(): void;
/**
* Callback for onClick method.
*
* @callback OnClickCallback
* @param {OnClickEventData} data - The click event data.
* @returns {boolean | void | Promise<boolean | void>} Return `false` to abort, or a Promise to defer.
*/
/**
* 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.
*
* @example
* // Synchronous usage — continue normally
* button.onClick((event) => {
* performValidationLogic();
* });
*
* @example
* // Synchronous abort — return false to cancel the payment
* button.onClick((event) => {
* if (!isOrderValid()) return false;
* });
*
* @example
* // Asynchronous usage — defer wallet sheet until the promise resolves
* button.onClick(async (event) => {
* await fetch('/validate-order').then(res => res.json());
* });
*
* @param {OnClickCallback} handler - Function to be called when the wallet button is clicked.
*/
onClick(handler: (data: OnClickEventData) => boolean | undefined | Promise<boolean | undefined>): void;
/**
* Callback for onSuccess method.
*
* @callback OnSuccessCallback
* @param {OnCreateOTTSuccessfulEventData} data - The OTT creation result including the token, amount, and address data.
*/
/**
* 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.
*
* @example
* button.onSuccess((event) => {
* console.log('OTT created:', event.data.token.temp_token);
* console.log('Amount:', event.data.amount);
* });
*
* @example
* // Async handler
* button.onSuccess(async (event) => {
* await submitTokenToServer(event.data.token.temp_token);
* });
*
* @param {OnSuccessCallback} handler - Function to be called when the OTT creation was successful.
*/
onSuccess(handler: (data: OnCreateOTTSuccessfulEventData) => void | Promise<void>): void;
/**
* Callback for onUnavailable method.
*
* @callback OnUnavailableCallback
* @param {OnUnavailableEventData} data - Data describing why the wallet is unavailable.
*/
/**
* 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.
*
* @example
* button.onUnavailable((event) => {
* console.log('Wallet not available:', event.data.reason);
* });
*
* @param {OnUnavailableCallback} handler - Function to be called when the wallet is not available in the current context.
*/
onUnavailable(handler: (data: OnUnavailableEventData) => void | Promise<void>): void;
/**
* Callback for onError method.
*
* @callback OnErrorCallback
* @param {OnErrorEventData} data - The error event data including the Error object and context.
*/
/**
* 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.
*
* @example
* button.onError((event) => {
* console.error('Wallet error:', event.data.error.message);
* console.log('Context:', event.data.context);
* });
*
* @param {OnErrorCallback} handler - Function to be called when the wallet has an error.
*/
onError(handler: (data: OnErrorEventData) => void | Promise<void>): void;
/**
* Callback for onCancel method.
*
* @callback OnCancelCallback
* @param {OnCancelEventData} data - Data associated with the cancellation event.
*/
/**
* 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.
*
* @example
* button.onCancel((event) => {
* console.log('Wallet checkout cancelled', event);
* });
*
* @param {OnCancelCallback} handler - Function to be called when the wallet checkout is cancelled.
*/
onCancel(handler: (data: OnCancelEventData) => void | Promise<void>): void;
/**
* 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.
*
* @example
* button.onLoaded((event) => {
* console.log('Wallet button loaded');
* });
*
* @param {Function} handler - Function to be called when the wallet button is loaded.
*/
onLoaded(handler: (data: OnLoadedEventData) => void | Promise<void>): void;
/**
* Callback for onShippingAddressChange method.
*
* @callback OnShippingAddressChangeCallback
* @param {OnShippingAddressChangeEventData} data - The shipping address data from the wallet.
* @returns {OnShippingAddressChangeEventResponse | Promise<OnShippingAddressChangeEventResponse>} Address update result containing updated amount, shipping options, and optional error.
*/
/**
* 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.
*
* @example
* // 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
* // Sync handler
* button.onShippingAddressChange((data) => {
* return {
* amount: calculateShipping(data.data.address_country),
* shipping_options: getOptionsForCountry(data.data.address_country),
* };
* });
*
* @param {OnShippingAddressChangeCallback} handler - Function to be called when the shipping address data is updated.
*/
onShippingAddressChange(handler: (data: OnShippingAddressChangeEventData) => OnShippingAddressChangeEventResponse | Promise<OnShippingAddressChangeEventResponse>): () => void;
/**
* Callback for onShippingOptionsChange method.
*
* @callback OnShippingOptionsChangeCallback
* @param {OnShippingOptionChangeEventData} data - The selected shipping option data.
* @returns {OnShippingOptionChangeEventResponse | Promise<OnShippingOptionChangeEventResponse>} Shipping options update result containing the updated amount.
*/
/**
* 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.
*
* @example
* // 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
* // Sync handler
* button.onShippingOptionsChange((data) => {
* return {
* amount: lookupShippingCost(data.data.shipping_option_id),
* };
* });
*
* @param {OnShippingOptionsChangeCallback} handler - Function to be called when the shipping options data is updated.
*/
onShippingOptionsChange(handler: (data: OnShippingOptionChangeEventData) => OnShippingOptionChangeEventResponse | Promise<OnShippingOptionChangeEventResponse>): () => void;
/**
* Whether a shipping options change handler has been registered.
* Used internally by wallet services to validate shipping configuration.
*
* @private
* @returns {boolean} `true` if an `onShippingOptionsChange` handler has been registered.
*/
get isShippingOptionsChangeHandlerRegistered(): boolean;
}
//# sourceMappingURL=open-wallet-buttons.d.ts.map