Native Checkout v2

Native Checkout v2 is an advanced method to integrate with Viva Wallet to accept payments online for your online store. It involves considerable technical effort on your side, but it has the main benefit that it integrates directly with your e-commerce website without customers being redirected to a Viva Wallet page for payment.

Native Checkout v2 has 3DS support which provides stronger security for both merchants and cardholders. Merchants have the ability to request cardholder authentication from issuers, therefore minimising fraud exposure. Cardholders with 3DS-enrolled cards can be certain that no transactions will be authorised without their consent. Native Checkout v2 has the added benefit that it integrates directly with your e-commerce website without customers being redirected to a Viva Wallet page for payment.

Before you start

The demo environment has a base URL of https://demo-api.vivapayments.com/ and for the live environment it’s https://api.vivapayments.com/. For information on how to generate an access token, see OAuth 2 token generation on our Authentication page.

  1. Create an account with Viva Wallet, if you do not already have one. There are two types:
  2. Log in to your demo account or live account .
  3. Complete our Request access token procedure.
  4. Make a note of your access token which will expire after 3600 seconds (one hour). Include a function in your code that repeats step 3 above programmatically before each expiry.
  5. Create a payment source selecting Redirection/Native Checkout v2 as the integration method.

Integration flow diagram

The below sequence diagram outlines the Native Checkout v2 integration procedure from beginning to end.

sequenceDiagram participant Merchant app participant Merchant backend participant Viva Wallet API Merchant app->>Viva Wallet API: Generate charge token from card details Viva Wallet API-->>Merchant app: Charge token, e.g. "ctok_Rc4c27orSU56SSMOLDijTMYA8X4" Merchant app->>Viva Wallet API: Make the actual charge using charge token Viva Wallet API-->>Merchant backend:Transaction ID (200 OK)

Integration flow instructions

Integrating with Native Checkout v2 consists of the following steps:

  1. Build a custom payment form to collect the card details
  2. Add reference to VivaPayments.js
  3. Initialize Native Checkout
  4. Generate one-time charge token
  5. Make the actual charge using the charge token
  6. Verify payment and set webhook (optional)

Step 1: Build a custom payment form to collect the card details

You need to build your own payment form to capture the following details:

The following is an example of a typical payment HTML form that you can easily build with an HTML editor. Decorate your form with data-vp attributes.

<form action="" method="POST" id="payment-form">
	<div class="form-row">
	<label>
		<span>Cardholder Name</span>
		<input type="text" data-vp="cardholder" size="20" name="txtCardHolder" autocomplete="off"/>
	</label>
	</div>

	<div class="form-row">
	<label>
		<span>Card Number</span>
		<input type="text" data-vp="cardnumber" size="20" name="txtCardNumber" autocomplete="off"/>
	</label>
	</div>

	<div class="form-row">
	<label>
		<span>CVV</span>
		<input type="text" data-vp="cvv" name="txtCVV" size="4" autocomplete="off"/>
	</label>
	</div>

	<div class="form-row">
	<label>
		<span>Expiration (MM/YYYY)</span>
		<input type="text" data-vp="month" size="2" name="txtMonth" autocomplete="off"/>
	</label>
	<span> / </span>
	<input type="text" data-vp="year" size="4" name="txtYear" autocomplete="off"/>
	</div>
	<input type="button" id="submit" value="Pay now" />
</form>

Step 2: Add reference to VivaPayments.js

Native Checkout v2 functionality is provided by the VivaPayments JS library. jQuery Core v1.10.x is required. Add a reference within your page using the following script tag:

<script type="text/javascript" src="https://www.vivapayments.com/web/checkout/v2/js"></script>

The Native Checkout v2 JS must be included directly in your pages. When testing you need to change the baseURL entry in the code to https://demo-api.vivapayments.com.

Step 3: Initialize Native Checkout

Initialize Native Checkout v2 by calling the VivaPayments.cards.setup() method.

In the below JavaScript example, replace [access token] with the one you obtained during the OAuth 2 token generation procedure outlined on our Authentication page.

VivaPayments.cards.setup({
	authToken: '[access token]',
	baseURL: 'https://api.vivapayments.com',
	cardHolderAuthOptions: {
		cardHolderAuthPlaceholderId: 'threed-pane',
		cardHolderAuthInitiated: function() {
			alert('Cardholder authentication started!');
		},
		cardHolderAuthFinished: function() {
			alert('Cardholder authentication has finished');
		}
	}
});

Parameters

ParameterDescriptionImportance
authTokenAccess token issued by the Viva Wallet IdentityServer (OAuth2) authentication.Required
baseURLhttps://demo-api.vivapayments.com/ for the demo environment and https://api.vivapayments.com/ for the live environment.Optional
cardHolderAuthOptionsCardholder 3DS authentication session options (1, 2 and 3 below).Optional
cardHolderAuthOptions.cardHolderAuthPlaceholderId (1)HTML element ID which will act as a placeholder when rendering the cardholder’s authentication page. We recommend you use a popup window as a placeholder of at least 400 x 400 pixels size.Optional
cardHolderAuthOptions.cardHolderAuthInitiated (2)Function that will be called when the cardholder’s authentication page is rendered.Optional
cardHolderAuthOptions.cardHolderAuthFinished (3)Function that will be called when the cardholder’s authentication session has completed.Optional
installmentsHandler(maxInstallments)Callback function triggered when a card supports installments. Any number between 1 and 36 (representing months). Indicates the maximum number of installments a customer may select if their credit card supports installments (Greece only).Optional

Step 4: Generate one-time charge token

Next, you will need to generate a charge token by simply calling the requestToken method using JavaScript as indicated below. The charge token contains all the necessary cardholder information (including the 3DS authentication outcome) to complete a payment, and will expire after 10 minutes.

Example in JavaScript showing payment amount of €1.

VivaPayments.cards.requestToken({
  amount: 100, // amount is in currency's minor unit of measurement
  installments: 1,
}).done(function (responseData) {
  console.log(`Here is the charge token: ${responseData.chargeToken}`);
}).fail(function (responseData) {
  console.log('Here is the reason it failed: '  + responseData.Error.toString());
});

If the card is 3DS-enrolled, Native checkout will render the issuing bank’s authentication page to an iframe within the HTML defined in cardHolderAuthOptions.cardHolderAuthPlaceholderId. The authentication process is completely transparent and once concluded, the Promise object created from the call to requestToken will be resolved and provide the charge token as an argument.

Client implementations who make calls directly to the Native Checkout v2 API will need to render and display the issuing bank’s authentication HTML window themselves using the value from redirectToACSForm field. Furthermore, custom implementations will need to provide a sessionRedirectUrl (see below).

The redirectToACSForm field will have a value of null when the value of the payment is below a certain threshold (set by the card issuer). This indicates a frictionless transaction involving no 3DS challenge.

Working example in HTML

Here is an example that includes steps 1 to 4, above, for testing in the demo environment. Paste the HTML code below into a text editor:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Native 3DS test</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
        integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://demo.vivapayments.com/web/checkout/v2/js"></script>
</head>

<body>

    <form action="" method="POST" id="payment-form">
        <div class="form-row">
            <label>
                <span>Cardholder Name</span>
                <input type="text" size="20" name="txtCardHolder" autocomplete="off" data-vp="cardholder"
                    value="Joe Blogs" />
            </label>
        </div>

        <div class="form-row">
            <label>
                <span>Card Number</span>
                <input type="text" size="20" name="txtCardNumber" autocomplete="off" data-vp="cardnumber"
                    value="5188340000000060" />
            </label>
        </div>
        <div class="form-row">
            <label>
                <span>CVV</span>
                <input type="text" name="txtCVV" size="4" autocomplete="off" data-vp="cvv" value="111" />
            </label>
        </div>
        <div class="form-row">
            <label>
                <span>Expiration (MM/YYYY)</span>
                <input type="text" size="2" name="txtMonth" autocomplete="off" data-vp="month" value="1" />
            </label>
            <span> / </span>
            <input type="text" size="04" name="txtYear" autocomplete="off" data-vp="year" value="2025" />
        </div>
        <button type="button" id="submit" (click)="submit($event)">Pay now</button>
    </form>
    <div id="threed-pane" style="height: 450px;width:500px">
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            const baseUrl = 'https://demo-api.vivapayments.com';
            VivaPayments.cards.setup({
                baseURL: baseUrl,
                authToken: '[access-token]',
                cardHolderAuthOptions: {
                    cardHolderAuthPlaceholderId: 'threed-pane',
                    cardHolderAuthInitiated: function () {
                        $('#threed-pane').show();
                    },
                    cardHolderAuthFinished: function () {
                        $('#threed-pane').hide();
                    }
                },
                installmentsHandler: function (response) {
                    if (!response.Error) {
                        if (response.MaxInstallments == 0)
                            return;
                        $('#drpInstallments').show();
                        for (i = 1; i <= response.MaxInstallments; i++) {
                            $('#drpInstallments').append($("<option>").val(i).text(i));
                        }
                    }
                    else {
                        alert(response.Error);
                    }
                }
            });

            $('#submit').on('click', function (evt) {
                evt.preventDefault();
                VivaPayments.cards.requestToken({
                    amount: 100
                }).done(function (data) {
                    console.log(data);
                    alert(data.chargeToken);
                });
            });

        });
    </script>
</body>
</html>

Replace [access token] with your own. Save as an HTML file and open in a browser:

Charge token popup

Click on the Pay now button.
A dialog box will be displayed within the page:

3ds popup simulator

Click on Yes.
After a few moments you will receive the charge token in a popup:

Charge token popup

Step 5: Make the actual charge using the charge token

Now that you have acquired the one-time charge token from the previous step, you will need to create a charge, in order to conclude the payment:

post    /nativecheckout/v2/transactions

Request example

Tip: The below call cannot be made through a browser. Use a backend channel instead. Replace [access token] with the one you obtained during the OAuth 2 token generation procedure outlined on our Authentication page. You should swap [4-digit code of your payment source] for the code of the payment source you created earlier. Overwrite [charge token] with the time-limited token generated in step 4, above.

curl -X POST \
  https://demo-api.vivapayments.com/nativecheckout/v2/transactions \
  -H 'Authorization: Bearer [access token]' \
  -H 'Content-Type: application/json' \
  -d '{
 "amount": 100,
 "tipAmount": 50, //optional
 "preauth": false,
 "sourceCode": "[4-digit code of your payment source]",
 "chargeToken": "[charge token]",
 "installments": 1,
 "allowsRecurring": false,
 "merchantTrns": "Merchant transaction reference",
 "customerTrns": "Short description of items/services purchased to display to your customer",
 "currencyCode": 978,
 "customer": {
      "email": "native@vivawallet.com",
      "phone": "442037347770",
      "fullname": "John Smith",
      "requestLang": "en",
      "countryCode": "GB"
   }
}'

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://demo-api.vivapayments.com/nativecheckout/v2/transactions',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
 "amount": 100,
 "tipAmount": 50, //optional
 "preauth": false,
 "sourceCode": "[4-digit code of your payment source]",
 "chargeToken": "[charge token]",
 "installments": 1,
 "merchantTrns": "Merchant transaction reference",
 "customerTrns": "Short description of items/services purchased to display to your customer",
 "currencyCode": 978,
 "customer": {
      "email": "native@vivawallet.com",
      "phone": "442037347770",
      "fullname": "John Smith",
      "requestLang": "en",
      "countryCode": "GB"
   }
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json',
    'Authorization: Bearer 19D796327FDB4962B994D8F49B465F5323513F20D02A37F6A5B282369D176600'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

currencyCode is an ISO 4217 code. It should be set to the same currency as your Viva Wallet account. In the example above, the currency is GBP. If you registered your account in a Eurozone country, it would be EUR with a code of 978.

requestLang and countryCode should be set appropriately for the customer’s language and country.

Response example

If the cardholder’s authentication was successful and all other requirements meet (e.g. account has enough balance etc.) then the payment will be successful and you should receive a response containing the charge’s transactionId:

{
  "transactionId": "1549bffb-f82d-4f43-9c07-0818cdcdb2c4"
}

Step 6: Verify payment and set webhook (optional)

You can make a call to Retrieve transactions in order to verify the status of a payment. To get automatic notifications you can make use of our webhooks functionality.

Conclusion: Switch from sandbox/demo to production/live

When you are happy with your integration with Viva Wallet, see our go-live steps to find out how to launch to live.

Further information

Check out the related tutorials below for more details about OAuth 2 authentication and setting webhooks: