UNPKG

@paydock/client-sdk

Version:

Paydock client sdk

1,441 lines (1,205 loc) 116 kB
# 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. ### Download from CDN ```html <script src="https://widget.paydock.com/sdk/latest/widget.umd.min.js"></script> <script> var widget = new paydock.HtmlWidget('#tag', 'publicKey', 'gatewayId'); </script> ``` 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. ### With package manager ```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'" ``` 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. ## 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> ``` ## 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> ``` ## 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> ``` ## 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 {