Card vault - Android

Card Vault widgets integrate functionalities like wallets and tokenization without processing the payment.

DEUNA's Payment Vault contains different types of widgets that allow you to:

  • Save credit and debit cards securely in the Vault.
  • Make payments with Click To Pay using the Click To Pay Widget.

Initialize the Widget

Before integrating the Payment Widget, complete the Getting Started - Android.

1. Display the Widget

Display in a Dialog

To display the widget in a DialogFragment, call the initElements function passing the following data:

val callbacks = ElementsCallbacks().apply{
    onSuccess = { response ->
        deunaSDK.close() // Close the widget
    },
    onError = { error ->
        // handle the error
        deunaSDK.close() // Close the widget
    },
    onClosed = { action ->
       // The VAULT widget was closed
    },
    onEventDispatch = { type, response ->
       // Listen to events
    }
}

// Display the VAULT widget
deunaSDK.initElements(
  context = YOUR_ACTIVITY_CONTEXT,
  userToken = "<DEUNA user token>", // optional
  userInfo = DeunaSDK.UserInfo("Esteban", "Posada", "[email protected]"), // optional
  callbacks = callbacks,
  types = ...,// optional, If this value is not passed, the VAULT Widget will be shown by default.
  widgetExperience = ElementsWidgetExperience( // optional
    userExperience = ElementsWidgetExperience.UserExperience(
      showSavedCardFlow = false, // optional
      defaultCardFlow = false // optional
    )
  )
)  

Display Embedded (Jetpack Compose)

To display the widget embedded in your application with Compose, use the AndroidView composable and the DeunaWidget view.

📘

DeunaWidget does not support dynamic dimensions so the AndroidView container must define the dimensions that the DEUNA widget will use.

@Composable
fun YourScreen(
    deunaSDK: DeunaSDK,
    orderToken: String,
    userToken: String,
) {
    // Maintains the Deuna WebView instance across recompositions
    val deunaWidget = remember { mutableStateOf<DeunaWidget?>(null) }

    Column(modifier = Modifier.padding(16.dp)) {
        // Container for the embedded payment widget
        // MUST specify dimensions (e.g., .height(400.dp) or .weight(1f) in parent Column)
        Box(
            modifier = yourModifier 
        ) {
            AndroidView(
                modifier = Modifier.fillMaxSize(),
                factory = { context ->
                    DeunaWidget(context).apply {
                        
                        this.widgetConfiguration = ElementsWidgetConfiguration(
                                sdkInstance = deunaSDK,
                                hidePayButton = true, // (Optional) Hide the pay button in the embedded widget
                                orderToken = orderToken,
                                userToken = userToken,
                                userInfo = UserInfo(
                                    firstName = "Darwin",
                                    lastName = "Morocho",
                                    email = "[email protected]"
                                ),
                                callbacks = ElementsCallbacks().apply {
                                    this.onSuccess = { data ->
                                        val savedCard = (data["metadata"] as Json)["createdCard"] as Json
                                    }
                                },
                            )
              
                        this.build() // Render the DEUNA widget
                        // Store reference for later submission
                        deunaWidget.value = this
                    }
                }
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        // Custom payment submission button
        // Only needed when hidePayButton = true
        Button(
            onClick = {
                // Programmatically submit payment details to Deuna
                // Required when hidePayButton = true
                deunaWidget.value?.submit { result ->
                    // Handle submission result
                    // result.status: "success"|"error"
                    // result.message: Detailed status message
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("Complete Payment")
        }
    }

    // Critical: Clean up DeunaWidget resources when composable leaves composition
    DisposableEffect(Unit) {
        onDispose {
            deunaWidget.value?.destroy()
            Log.d("DeunaWidget", "WebView resources cleaned up")
        }
    }
}


Parameters

ParameterDialogEmbeddedDescription
callbacksAn instance of the ElementsCallbacks class, which contains callbacks that will be called in case of success, error, or when the widget is closed.
userToken (Optional)The token of a user obtained using DEUNA's API
https://docs.deuna.com/reference/users-register
https://docs.deuna.com/reference/request-otp
https://docs.deuna.com/reference/login-with-otp
orderToken(Optional)The orderToken is a unique token generated for the payment order. This token is generated through DEUNA's API and you must implement the corresponding endpoint in your backend to obtain this information.

User information available in billing_address can be extracted to use within the widget.
userInfo(Optional)Instance of the DeunaSDK.UserInfo class that contains firstName, lastName and email.

In case the userToken is not sent or is an empty string (""), this parameter is required.
styleFile (Optional)UUID provided by DEUNA. This applies if you want to configure a custom custom styles file (Change colors, texts, logo, etc). If a valid value is provided for styleFile the vault widget will use the UI configuration provided by the theme configuration that matches the provided UUID.
types(Optional)An instance of type List<Map<String,Any>> with a list of the widget types that the initElements function should render.

Allowed values are: vault and click_to_pay.

Example: listOf( mapOf("name" to ElementsWidget.VAULT) )

If this parameter is not passed, DEUNA's Vault Widget for saving credit and debit cards will be shown by default.
language(Optional)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 configuration.
- If not provided: The widget will use the language configured by the merchant.
widgetExperience(Optional)Overrides merchant configurations. Currently supported by the widget are the following:

userExperience.showSavedCardFlow: Shows card saving toggle.
userExperience.defaultCardFlow: Shows toggle to save the card as default.

Click To Pay Widget

Using the types parameter of the initElements function you can make a payment with Click To Pay. The following code snippet shows how to display the ClickToPay widget:

📘

The userInfo parameter is required to be able to display the ClickToPay widget.

deunaSDK.initElements(
  context = this,
  userInfo = UserInfo(// Required for click_to_pay
    firstName = "Esteban",
    lastName = "Posada",
    email = "[email protected]",
  ),
  types = listOf(
    mapOf(
      "name" to ElementsWidget.CLICK_TO_PAY // Display the ClickToPay widget
    )
  ),
  callbacks = ElementsCallbacks().apply {
    onSuccess = {
      deunaSdk.close()
    }
    onEventDispatch = ...
    onError = ...
    onClosed = ...
  },
)  

2. Listen to Widget Events

It's crucial to properly handle Widget events to provide a smooth experience to users. Define the necessary callbacks to update your application's interface.

Callbacks

CallbackDialogEmbeddedWhen is it triggered?
onSuccessIt's executed when a card is successfully saved or when the Click to Pay payment was successful. This callback contains a parameter of type Map<String,Any> .
onErrorIt's executed when an error occurs while processing the operation of the displayed widget. This callback contains a parameter of type ElementsError
onClosed
(Optional)
It's executed when the payment widget is closed.

This callback contains a parameter of type enum CloseAction with the following values:

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

- systemAction: When the widget is closed due to the execution of the close function.
onEventDispatch (Optional)It's executed when specific events are detected in the widget. This callback contains a parameter of type ElementsEvent

3. Close the Widget

By default, Element Widgets only close when the user presses the widget's close button or when they press the "back" button on Android.

To close the modal when an operation is successful or when an error occurs, you must call the close function.

The following example code shows how to close the widget

val callbacks = ElementsCallbacks().apply {
    onSuccess = { response ->
        deunaSDK.close() // Close the Vault Widget
        // Your additional code
    }
}

// Display the Vault Widget
deunaSDK.initElements(
    context = YOUR_ACTIVITY_CONTEXT,
    userToken = "<DEUNA user token>", // optional
    userInfo = DeunaSDK.UserInfo("Esteban", "Posada", "[email protected]"), // optional
    callbacks = callbacks
)

Optional Features

In addition to the mandatory steps to operate the widget, you have the following customization options:

Customize Widget Appearance

Use the setCustomStyle function to customize the Widget appearance.

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

📘

For more information, go to Style Customization.

Example

val callbacks = ElementsCallbacks().apply{
    onSuccess = ...,
    onError = ...,
    onClosed = ...,
    onCanceled = ...,
    onEventDispatch = { type, response ->
       // Listen to events
       deunaSDK.setCustomStyle(
             data = JSONObject(
                        """
                        {
                          "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"
                                }
                              }
                            }
                          }
                        }
                        """
         ).toMap()
        )
    }
}

// Display the VAULT widget
deunaSDK.initElements(
    context = YOUR_ACTIVITY_CONTEXT,
    userToken = "<DEUNA user token>", // optional
    userInfo = DeunaSDK.UserInfo("Esteban", "Posada", "[email protected]"), // optional
    callbacks = callbacks
)  

Hide Payment Button (Embedded Widget)

When the widget is displayed embedded, you can use the hidePayButton parameter to hide the payment button of the DeunaWidget.

// Maintains the Deuna WebView instance across recompositions
val deunaWidget = remember { mutableStateOf<DeunaWidget?>(null) }
.
.
.

DeunaWidget(context).apply {
   // Set true to handle payment submission manually via submit()
   // Set false to use Deuna's built-in payment button
   this.widgetConfiguration = ElementsWidgetConfiguration(
     hidePayButton = true,
     .
     .
     .
   )
   .
   .
   .
 }

deunaWidget.value?.isValid { it ->  }
deunaWidget.value?.submit {result -> }

You can use the following functions to validate and execute the payment.

MethodDescriptionResponse
.isValid{...}Validates if the entered information is correct and if the payment can be processed.true if the information is valid, false otherwise.
.submit{...}Executes the payment process, equivalent to pressing the pay button. Performs the same internal validations.{ status: "success", message: "Payment processed successfully" } or { status: "error", message: "The submit flow is not available" }

Considerations

  • It's recommended to use isValid{} before calling submit{} to avoid errors in the payment process.
  • If the payment flow is not yet available, submit{} will always return an error with the message "The submit flow is not available"