NAV Navbar
Browser Server (Javascript) Server (Java)

Token Merchant Quick Checkout

This page describes Token’s Merchant Quick Checkout offering and demonstrates how to integrate it into a merchant website. This page doesn’t try to describe the whole Token platform; for that, please see the TokenOS Overview. Specifically, this page does not describe how to implement an in-app merchant; it shows how to add Token functionality to a web page.

Quick Checkout Button

The Token Quick Checkout product’s benefits include:

The Token API uses Smart Tokens to track authorization for money transfers. You can learn more about Smart Tokens. Token uses members to keep track of users who can have bank accounts. You can learn more about members.

You can try out the system with Token’s development sandbox:

  1. Get the SDK
  2. Set up a Token member
  3. Add a Checkout button to your site
  4. Create and redeem Smart Tokens

Image: Integration Steps

Onboarding

To get started accepting payments using Token, first you must create a Token member account, which will allow you to initiate API calls, request payments, and request information.

For testing, you can manually or automatically create member using the Token Javascript or Java SDK.

Download Sample code

To see the minimal implementation of the merchant quick checkout (client and server), click one of the following links:

Clone or download the appropriate sample. Its README.md tells how to build and run the sample.

Using the Token SDK

The sample code shows a merchant web site “back end” written in Java or Javascript (Node.js).

To use the Javascript SDK to build the sample code described here, you don’t need to download the SDK; the build tool does that automatically. To install the Javascript Token SDK in other node JS apps, npm install token-io

To use the Java SDK to build the sample code described here, you don’t need to download the SDK; the build tool does that automatically. (To see the gradle configuration that refers to the SDK, see the SDK documentation)

The Quick Checkout sample code shows how to use the SDK to create a test member and get information about payments. The SDK can do more; see its documentation for more information.

Merchant Member

A Token Member is roughly equivalent to a Token user account. A merchant creates a member, associates it with a bank account, and uses it to receive funds. You can learn more about members.

The sample code automatically creates a test merchant member with a random email address.

Normally, after you create a member you must verify its email address: check your email for mail from Token. If you’re running in the test “sandbox” environment and the address contains +noverify@, then Token automatically verifies the email. The sample code uses a +noverify@ address so you don’t need to check your email.

As you’ll see later, the customer is another Token member, created a different way.

Create a member

Click the Server tab with the language of your choice to see this.

const alias = {
    type: 'EMAIL',
    value: "msjs-" + Math.random().toString(36).substring(2, 10) + "+noverify@example.com"
};
Token.createMember(alias, Token.UnsecuredFileCryptoEngine).then(function(m) {
    member = m;
    // launch server
    initServer(member, alias);
});
Path keys = Files.createDirectories(Paths.get("./keys"));
return TokenIO.builder()
        .connectTo(SANDBOX)
        // This KeyStore reads private keys from files.
        // Here, it's set up to read the ./keys dir.
        .withKeyStore(new UnsecuredFileSystemKeyStore(
                keys.toFile()))
        .devKey("4qY7lqQw8NOl9gng0ZHgT4xdiDqxqoGVutuZwrUYQsI")
        .build();
String email = "merchant-sample-" + generateNonce().toLowerCase() + "+noverify@example.com";
Alias alias = Alias.newBuilder()
        .setType(EMAIL)
        .setValue(email)
        .build();
return tokenIO.createMember(alias);

Using the Sample Server

Once you build the server, following the directions in its README, you’re ready to try it out. You will need to create another member to be the customer:

Create the Customer member

To act as a Customer member, you will need the Token Open Banking demo app. The demo app and the sample code, uses Token’s “sandbox” testing environment.

Demo App for iOS

Demo App for Android

The app prompts you to enter an email address and to link accounts from one of our test banks (Gold, Iron, or Silver). The email address you enter should be valid (you will need to verify it) and is different than the email you entered for the PFM member.

Try your Quick Checkout button

Now that you have created a user on the demo app, you can interact with your website’s Quick Checkout button.

You don’t need to do this using your mobile device; you can use any web browser. The first time you try to use the Quick Checkout button (or some other Token gadget), Token will prompt you for your alias. Entering requires approval in the mobile app.

You can also use your customer member to try Token’s demo merchant site.

Browser: Step by Step

A web merchant can set up a Quick Checkout button on a web page with some Javascript. By writing callback functions, it’s possible to provide a choice of shipping methods, adapt behavior to shipping address, detect creation of tokens, and detect canceled interactions.

The sample code here shows how a merchant could add a Quick Checkout button to a shopping cart web page.

Load the Token library

In the page’s html, load the token.js library.

The token.js library is available at web-app.sandbox.token.io/token.js . (This is the link for the Sandbox testing environment, the same environment you used to create the Merchant member and Customer member. For the “real” non-testing library, omit the sandbox.)

Load the Token Library

This is client-side code. Click the Browser tab to see this.

This is client-side code. Click the Browser tab to see this.

<script src="https://web-app.sandbox.token.io/token.js">
</script>

Add Button to Page

Add a Quick Checkout div to the page. (We call this a “button” and will style it to look like a button; this code works better with Firefox if the “button” is a div.) Give it an id; you’ll refer to that later.

Image showing Token Button

This is client-side code. Click the Browser tab to see this.

This is client-side code. Click the Browser tab to see this.

<div id="tokenPayBtn" style="width:200px"></div>

Shipping callback

The merchant might do things differently depending on the customer’s shipping address. The address might affect taxes, shipping method choices, and shipping costs. To specify this behavior, the merchant can define an (optional) shipping callback function.

Token calls the shipping callback function when the user chooses a shipping address. It passes in an address structure and another callback function. The merchant’s callback function can use data from the passed-in address structure (e.g., the address.country field) to choose shipping methods and/or compute taxes. To pass these results back into the token system, the shipping callback invokes the passed-in callback.

A merchant selling “virtual” goods can specify a null shipping callback; this tells Token not to prompt the user to choose a shipping address.

The shipping callback is client-side Javascript used by the merchant site web page.

This is client-side code. Click the Browser tab to see this.

This is client-side code. Click the Browser tab to see this.

function shippingCb(address, tokenCallback) {
    tokenCallback({ // Can return price based on address
        shippingMethods: [
            {
                id: '0',
                name: 'Standard Ground (5-9 business days)',
                deliveryTime: '5 - 9 Business Days',
                cost: 0
            },
        ],
        tax: 0
    });
}

Bind the button

Call the Token.styleButton and .bindPayButton functions. styleButton changes the html styles so that the button has a Token checkout logo and colors. bindPayButton changes the button’s click behavior to launch the Token checkout experience.

These functions take several arguments:

  • Id of the button
  • Label that should be in the button
  • Merchant Member’s alias (identifying who should receive payment)
  • JSON object containing desired terms for Smart Token
  • Callback to define shipping costs (null to not ask for shipping info)
  • Callback for success. This function is called after the customer approves and creates the token. No money has been moved yet. The merchant has not yet redeemed the token.
  • Callback for failure

The button-binding code is client-side Javascript used by the merchant site web page.

This is client-side code. Click the Browser tab to see this.

This is client-side code. Click the Browser tab to see this.

Token.styleButton({            // Sets up the Quick Checkout button
    id: "tokenPayBtn",
    label: "Token Quick Checkout"
}).bindPayButton(
    {                               // Terms
        alias: {                    // Merchant alias
            type: 'EMAIL',
            value: '{alias}'        // (filled in by server)
        },
        amount: 4.99,               // Amount
        currency: 'EUR',            // Currency
        destinations: []
    },
    shippingCb,          // Shipping callback (null for "virtual" goods)
    function(data) {     // Success callback
        $.post(
            'http://localhost:3000/transfer',
            data);
    },
    function(error) {    // Failure callback
        console.log('Something\'s wrong!', error);
    }
);

Browser pairing

Clicking the button triggers the checkout experience.

If the user has not used Token with this browser before, they are prompted to link it:

This stores a low-privilege private key in the customer’s browser local storage. The Token API uses this key to call TokenOS to fetch balances, addresses, etc.

Token Login

Token Login

Customer approval

The customer can select which account to pay from and a shipping address. Changing the address triggers the shipping callback, if provided. If the shipping callback provides multiple shipping methods, the customer can choose one.

Image showing Token Checkout

Some banks require more interaction from the user here. E.g., if your Customer member’s bank account is at the WOOD fake bank, then WOOD prompts the user to log in and confirm the payment. Some banks (e.g., the Gold, Silver, and Iron fake banks), better-integrated with TokenOS, don’t require this kind of interaction.

If the purchase is over a certain amount, Token requires a second factor approval from the customer. They get a push notification on their mobile device, which they approve to complete the transaction.

When the customer clicks Submit, it endorses (approves) a Smart Token. Token calls the merchant’s success callback, if defined; it passes the token as a parameter.

Image showing Token Checkout

Success Callback

When the customer successfully authorizes payment, Token calls a merchant-supplied callback function, passing in data about the order.

The passed-in data structure has the fields

  • tokenId: Id of the endorsed token
  • amount: amount of payment
  • currency: currency of payment
  • shippingAddress: shipping address
  • shippingMethod: chosen shipping method

The sample code here posts the the data so that the server code can redeem payment. The callback can do more; for example, it could show a “Thank you” message or clear out a shopping cart.

The success callback is client-side Javascript used by the merchant site web page.

This is client-side code. Click the Browser tab to see this.

This is client-side code. Click the Browser tab to see this.

function(data) {     // Success callback
    $.post(
        'http://localhost:3000/transfer',
        data);
},

…or no Success Callback

In some corner cases, the success callback never gets called. Perhaps the customer cancels out of the endorsement interaction. Perhaps the customer endorses the token but navigates to another page before the success callback is called.

There could be a “dangling” transfer token in the Token Cloud: endorsed but not redeemed.

For typical usage, it makes sense to treat these cases as if a customer cancelled the payment interaction: Don’t redeem tokens, don’t ship items, don’t change shopping cart contents. Though the merchant can redeem the endorsed token, the merchant doesn’t have the chosen shipping address or method.

Server: Step by Step

Once the user has finished interacting with the Token UI in the browser, the server redeems the token.

Redeeming Tokens

The Smart Token is just an authorization. To initiate the transfer of funds, the merchant redeems the Smart Token. Using the same merchant member, call the redeemToken method to create the transfer. This returns a transfer object.

(This happens in the server code, the same code you used to keep track of the merchant member.)

Redeeming tokens

Click the Server tab with the language of your choice to see this.

app.post('/transfer', urlencodedParser, function (req, res) {
    console.log('User request', req.body);
    // Get the token first and check its validity
    member.getToken(req.body.tokenId)
        .then(function (token) {
            // Redeem the token to move the funds
            member.redeemToken(token, 4.99, 'EUR', 'Order 123', destinations)
                .then(function (res) {
                    console.log('\n Reedeem Token Response:', res);
                });
        });
});
Spark.post("/transfer", (req, res) -> {
    Map<String, String> formData = parseFormData(req.body());
    String tokenId = formData.get("tokenId");

    // Make sure to get the token first,
    // and check its validity
    Token token = merchantMember.getToken(tokenId);

    // Transfer destinations. If your bank supports
    // Token payments, you can use your Token member
    // and account ID instead or in addition.
    TransferEndpoint dest = Destinations.sepa(
            "IRONUSCA000",
            "DK5000440441116263");

    // Redeem the token at the server, to move the funds
    Transfer transfer = merchantMember.redeemToken(token, 4.99, "EUR", "example", dest);
    return "";
});

You can get the Smart Token via the getToken API. Since that Smart Token was created in client-side Javascript, it’s good practice to validate its terms.

Both Smart Tokens and transfers are objects that can be fetched from TokenOS. This is useful, for example, to view a token’s attachments or to get the status of a transfer.

member.getToken(tokenId)
    .then(function (token) {
        console.log(token);
    });

member.getTransfer(transferId)
    .then(function (transfer) {
        console.log(transfer);
    });
Token transferToken = member.getToken(tokenId);
System.out.printf("Token contents: %s \n",
    transferToken.toString())

Transfer transfer = member.getTransfer(transferId);
System.out.printf("Transfer contents: %s \n",
    transfer.toString())

Administration Dashboard (Under Construction)

The administration dashboard enables you to view all of your Smart Tokens, transfers, and transactions, as well as all data and relevant information associated with the transactions.

The dashboard also enables management of keys and devices, access to support, settings, and other functions.

It is currently in development and will be available later in the year.

Copyright © 2017 Token, Inc. All Rights Reserved