Payment widget - Web

The Payment widget is an integrated tool that allows you to offer multiple payment methods to end customers.

The Payment widget supports:

  • Alternative payment methods (APMs): such as OXXO, KueskiPay, Aplazo, among others.
  • Credit and debit cards: MasterCard, Visa, American Express, and so on.

Initialize the widget

Before integrating the Payment Widget, complete the First steps - Web.

1. Display the widget

To display the Payment widget:

  1. Call the function initPaymentWidget.
  2. Pass the following data:
await DeunaSDK.initPaymentWidget({
  orderToken: "<DEUNA order token>", // Mandatory order token to start widget
  userToken: ..., // optional
  styleFile: ..., // optional
  language: ..., // optional
  hidePayButton: ..., // optional
  callbacks: {
    // optional
    onClosed: (action) => console.log("closed from Payment Widget"),
    onSuccess: (data) => console.log("purchaseResponse: ", data),
    onInstallmentSelected: (data) => console.log("installment selected"),
    onCardBinDetected: (payload) => console.log("bin detected"),
    onError: (error) => console.log("error", error),
    onEventDispatch: (event, payload) => {
      console.log("onEventDispatch: ", { event, payload });
    },
  },
});

Parameters

AttributesDescription
orderTokenThe orderToken is a unique token generated for the payment order. This token is generated through the DEUNA API and you must implement the corresponding endpoint in your backend to obtain this information.

IMPORTANT_: When creating the order with the API In DEUNA, a redirect URL (redirect_url) must not be defined for the onSuccess callback to execute correctly.
userToken (Optionall)The bearer token of the DEUNA user. When this is sent, all actions within the widget will be done on this DEUNA user.

Important: For this userToken to be used and to display the saved cards to the customer, the email associated with that userToken must be the same as the one sent when creating the order in billing_address.email. If the emails do not match, the flow will proceed without displaying the cards for security reasons.
language
(Optional)
The payment widget language can be overridden by sending a parameter with a supported language. The main languages available are en (English), es (Spanish) and pt (Portuguese). If this parameter is not sent, the default language will be used.
callbacksCallbacks are return functions that are responsible for listening to and handling events from the payment widget. These events allow you to manage specific actions based on the status of the payment. The main callbacks include. onSuccess, onError, onClosed, onCanceled, onCardBinDetected, onInstallmentSelected```
styleFile
(Optional)
UUID provided by DEUNA. This applies if you want to configure a custom styles custom file (Change colors, texts, logo, etc).

If a valid value is provided for styleFile The payment widget will use the UI settings provided by the theme configuration that matches the provided UUID.
paymentMethods (Optional)A list of allowed payment methods. This parameter determines what type of widget should be rendered.
target(Optional)By default, DEUNA widgets are displayed in a modal.
If you prefer to display the widget inside a specific HTML element, use the parameter target to specify the ID or class name of the HTML element (using selectors) where you want to render the widget.

Examples: #my-container , .my-container
language(Optionall)This parameter allows you to specify the language in which the widget interface will be displayed. It must be provided as a valid language code (for example, "es" for Spanish, "en" for English, "pt" for Portuguese).

Behavior:

- If provided: The widget will use the language specified in this parameter, regardless of the merchant's settings.
- If not provided: The widget will use the language configured by the merchant.
behavior (Optional)Use this parameter to configure the widget behavior
hidePayButton(Optionall)By establishing hidePayButton: true, the widget's default payment button is hidden, transferring full control of the payment flow to the integrator.

2. Show or hide payment methods

The Payment widget can display multiple payment methods available for an order without adding each button individually to the frontend.

Show or hide payment methods:

  1. Invoke the function initaymentWidget
  2. The parameter paymentMethods defines the payment methods that the widget displays:
    If a method is passed in paymentMethods, the widget automatically opens the payment method form without displaying buttons for other payment methods.
    If more than one payment method is specified in the parameter paymentMethods, then the widget displays the enabled methods which must be configured in your store.
  3. If no method list is specified in paymentMethods and the include_payment_options parameter was not used when creating the order, then the widget displays all payment methods configured for the merchant.


// example of Click to Pay
await DeunaSDK.initPaymentWidget({
    orderToken: "<DEUNA order token>",
    callbacks: ...,
    paymentMethods: [
        {
            paymentMethod: "wallet",
            processors: ["click_to_pay"],
        },
    ],
});




await DeunaSDK.initPaymentWidget({
    orderToken: "<DEUNA order token>",
    callbacks: ...,
});





📘

You don't need to pass the processor array to process credit cards. You can have multiple processors configured for routing.

await DeunaSDK.initPaymentWidget({
    orderToken: "<DEUNA order token>",
    callbacks: ...,
    paymentMethods: [
        {
           paymentMethod: "credit_card",
        },
        {
            paymentMethod: "voucher",
            processors: ["daviplata"],
        },
    ],
});



Payment method configuration priority table

The following table shows how the payment widget decides which payment methods to display when the parameter is not passed paymentMethods:

PriorityConfiguration sSourceDescriptionBehavior of a single payment method
1.Payment methods passed when executing the function .initPaymentWidgetPayment methods are displayed based on those passed when starting the widget, as long as they are activated and configured at the merchant level.If only one payment method is passed, then the widget automatically opens the payment method form without displaying any buttons.
2.Order and include-payment-optionsThe order is reviewed to see if include_payment_options has payment methods that are configured and activated at the merchant level. Unconfigured methods are not displayed.If only one payment method is passed, then the widget automatically opens the payment method form without displaying any buttons.
3.Methods configured at the commerce level. [API/ payment methods]If no payment method is passed in either the .initPaymentWidget function or include_payment_options when creating the order, then the methods configured at the merchant level are used.If only one payment method is passed, then the widget automatically opens the payment method form without displaying any buttons.

3. Listen to Payment Widget Events

When a transaction succeeds or fails, update your interface to notify users about the result of the transaction. You can do this by listening to the events of the payment widget through callbacks.

The callbacks passed to initPaymentWidget allow you to listen for widget events. Define the corresponding callbacks to update your app's interface.

Callbacks

CallbackWhen is it triggered
onsuccessExecuted when payment is complete. This callback contains a JSON parameter containing the order information.
onerrorExecuted when an error occurs while processing the payment. This callback contains a JSON parameter that identifies the type of error that occurred.
onclosed [optional]Runs when the payment widget is closed.

This callback contains a string parameter whose values can be one of the following:

- userAction: When the widget was manually closed by the user (by pressing the close X button) without the operation being completed.

- systemAction: When the widget is closed due to the execution of the function close.
onCardBinDetected (Optional)Executes when the payment widget detects the BIN of an entered credit or debit card or when the user deletes the entered card number.

This callback contains a parameter of type JSON with the bin information and card brand entered.

NOTE: The type parameter JSON is null when the user deletes the text entered in the card number field.
onInstallmentSelected (Optional)This callback will be executed when the user clicks on the pay button and the payment is being processed.

NOTE: If there is any incorrect field in the payment form, then this event is not run.
`onEventDispatch (Optional)It is run on all events that the widget can produce.
This callback contains a parameter of type string and the data (JSON) associated with said event.
`onResize (Optional)This callback allows you to "listen" to the changes in height from the content of the DEUNA widget

Adjust the height of your embedded widget's container

Example:

await DeunaSDK.initPaymentWidget({
  orderToken: "<DEUNA order token>", // Obligatorio: Token de la orden para inicializar el widget
  callbacks: {
    onSuccess: ...,
    onInstallmentSelected: (data) => {
    },
    onCardBinDetected: async (cardBinMetadata) => {
      if (cardBinMetadata) {
      
      }
    },
    onError: (error) => console.log("error", error),
    onEventDispatch: (event, payload) => {
	    console.log("onEventDispatch: ", { event, payload });
	  }
  },
});

4. Close the Widget

By default, the payment widget closes when the user presses the widget's close button.

To close the modal when a payment is successful or when an error occurs, call the function close.

await DeunaSDK.close();

The following example code shows how to close the widget when a payment is successful..

await DeunaSDK.initPaymentWidget({
  orderToken: "<DEUNA order token>", // Obligatorio: Token de la orden para inicializar el widget
  callbacks: {
    // opcionales
    onSuccess: async (data) => {
      await DeunaSDK.close(); // Cierra el widget de pago
      console.log("purchaseResponse: ", data);
    },
  },
});

5. Customize the appearance of the widget

If the payment widget is visible and you want to customize its appearance, use the setCustomStyle function.

await DeunaSDK.setCustomStyle({...});

Please refer to the following documentation documentación to learn more about all the costumization options for the payment widget.

Below is how to change the colors and logo of the payment widget using setCustomStyle

await DeunaSDK.initPaymentWidget({
  orderToken: "<DEUNA order token>", // Obligatorio: Token de la orden para inicializar el widget
  callbacks: {
    onSuccess: ...,
    onCardBinDetected: async (cardBinMetadata) => {
      await DeunaSDK.setCustomStyle({
        theme: {
          colors: {
            primaryTextColor: "#023047",
            backgroundSecondary: "#8ECAE6",
            backgroundPrimary: "#F2F2F2",
            buttonPrimaryFill: "#FFB703",
            buttonPrimaryHover: "#FFB703",
            buttonPrimaryText: "#000000",
            buttonPrimaryActive: "#FFB703",
          },
        },
        HeaderPattern: {
          overrides: {
            Logo: {
              props: {
                url: "https://images-staging.getduna.com/ema/fc78ef09-ffc7-4d04-aec3-4c2a2023b336/test2.png",
              },
            },
          },
        },
      });
    },
  },
});

6. Refresh the payment widget

The function refetchOrder updates the payment widget and returns the updated order data.

const order = await DeunaSDK.refetchOrder();

Use case

The function refetchOrderis useful for offering promotions.

One use case is: 20% off when paying with Mastercard.

In this scenario:

  1. Your system listens to the onCardBinDetected event to identify the card franchise.
  2. Your business updates the order in DEUNA (which is responsible for calculating the promotions)..
  3. Through the function refetchOrder, your business notifies the widget to update.
  4. The order amount is refreshed and changed.

Example

await DeunaSDK.initPaymentWidget({
    orderToken: "<DEUNA order token>", // Obligatorio: Token de la orden para inicializar el widget
    callbacks: {
        onCardBinDetected: async (cardBinMetadata) => {
            if (cardBinMetadata.cardBrand === "mastercard") {
                // Aquí el comercio debe hacer sus calculos y posteriormente actualizar la orden
                // de DEUNA por API usando: https://docs.deuna.com/reference/order_token
                const order = await DeunaSDK.refetchOrder();
                if (order) {
                    console.log("ORDER", order);
                }
            }
        },
    },
});