Omise.js

Omise.js is a JavaScript library which helps secure card information by sending sensitive details from the cardholder's browser directly to the Omise server. The details are converted into a one-time-use token which can be used to create a charge right away or attached to a customer object for later use.

This document will guide you through the steps in developing an in-app checkout page and building your payment form using Omise.js.

More details on why it's recommended to use Omise.js can be found in Security Best Practices.

Implementing Omise.js into your own payment form

Public Methods

The following are public methods that you can execute in order to send card information from your own payment form to Omise server to create a one-time-use token.

setPublicKey(key)

With script tag, setup your public key to authenticate against Omise API.
Learn more about authentication

Argument Value
key (required) key is the public keys that you can find in your dashboard once you're signed in.

Example

<script>
  Omise.setPublicKey("pkey_test_4xpip92iqmehclz4a4d");
</script>

createToken(type, object, callback)

Send the card object to Omise server to create a one-time-use token that you can use to create a charge or attach to a customer object.

Argument Value
type (required) type of token you want to create. For now this value must be card.
object (required) a JavaScript object containing the 5 values required for a card: name, number, expiration_month, expiration_year, security_code. Parameters reference can be found here.
callback (required) a callback that will be triggered whenever the request with Omise server is completed (for both error and success). Two arguments will be passed back into the callback. The first argument is HTTP status code; 200 for success or others for error such as 400. The second argument is the response from the Omise API.

Example

<script>
  Omise.createToken('card', cardObject, function(statusCode, response) { /* callback */ });
</script>

Usage Sample

This demonstrates the steps in implementing Omise.js into your own payment form.

  1. Insert Omise.js into your HTML page
  2. Implement a payment form
  3. Implement a JavaScript file to handle your payment form's event and send data to Omise.js

1. Insert Omise.js into your HTML page

Lets say you have already created a checkout page named checkout.html. Insert Omise.js into your checkout page.

You can select from either of our two CDNs

  • Primary CDN (Singapore) : https://cdn.omise.co/omise.js
  • Secondary CDN (Japan) : https://cdn2.omise.co/omise.js

Example

<body>
  <!-- .. Your code goes here .. -->

  <script src="https://cdn.omise.co/omise.js"></script>
</body>

2. Implement a payment form

Build your own payment form using HTML. Remember to add a hidden input field to your payment form used to assign the Omise token that will be returned from Omise.js

You'll need to implement a JavaScript file to handle a form submit event to send card information to Omise.js before performing a real form submit action. In this example, we've named it "app.js".
Include the file into your checkout page.

Example HTML (checkout.html)

<body>
  <!--
  This is your checkout form.

  NOTE: Here, we're using `data-name` to prevent sending credit card information fields to the backend server via HTTP Post
  (according to the security best practice https://www.omise.co/security-best-practices#never-send-card-data-through-your-servers).
  -->
  <form id="checkout-form" action="/checkout.php" method="POST">

    <!-- This is a hidden field you must add, to input omise token -->
    <input type="hidden" name="omiseToken" />

    <!-- This is card information fields that we required for tokenization -->
    <div>
      <label>Card Number</label>
      <input type="text" data-name="cardNumber" placeholder="••••••••••••••••" />
    </div>

    <div>
      <label>Name on card</label>
      <input type="text" data-name="nameOnCard" placeholder="Full Name" />
    </div>

    <div>
      <label>Expiry date</label>
      <select data-name="expiryMonth">
        <option value="">MM</option>
        <option value="1">1</option>
        <!-- ... -->
        <option value="12">12</option>
      </select>

      <select data-name="expiryYear">
        <option value="">YYYY</option>
        <option value="2017">2017</option>
        <!-- ... -->
        <option value="2025">2025</option>
      </select>
    </div>

    <div>
      <label>Security code</label>
      <input type="text" data-name="securityCode" placeholder="123" />
    </div>

    <div>
      <button>Checkout</button>
    </div>
  </form>

  <!-- Include omise.js. -->
  <script src="https://cdn.omise.co/omise.js"></script>

  <!-- Include your app.js. -->
  <script src="app.js"></script>
</body>

3. Implement JavaScript file

Set your public key and collect card information from your payment form. Next, pass the information on to Omise server for tokenization by executing Omise.createToken(). Omise will then create an Omise Token ID and return it to the callback function of Omise.createToken(type, object, callback) method.

Next, assign the token id back to the hidden input field that you have created in your payment form at step 2 and perform a real form submit action to send the Omise token to your backend server.

Data is now encoded in the form of a token before it's sent off. This is to protect sensitive details from prying eyes.

Example JavaScript (app.js)

// Set your Omise public key to authenticate against Omise API. This allows card information to be sent directly to Omise.
Omise.setPublicKey('YOUR_PUBLIC_KEY');

var checkoutForm = document.getElementById('checkout-form')
    checkoutForm.addEventListener('submit', submitHandler, false);

// Submit handler for checkout form.
function submitHandler(event) {
  event.preventDefault();

  /*
  NOTE: Using `data-name` to prevent sending credit card information fields to the backend server via HTTP Post
  (according to the security best practice https://www.omise.co/security-best-practices#never-send-card-data-through-your-servers).
  */
  var cardObject = {
    name:             document.querySelector('[data-name="nameOnCard"').value,
    number:           document.querySelector('[data-name="cardNumber"').value,
    expiration_month: document.querySelector('[data-name="expiryMonth"').value,
    expiration_year:  document.querySelector('[data-name="expiryYear"').value,
    security_code:    document.querySelector('[data-name="securityCode"').value
  };

  Omise.createToken('card', cardObject, function(statusCode, response) {
    if (statusCode === 200) {
      // Success: assign Omise token back to your checkout form.
      checkoutForm.omiseToken.value = response.id;

      // Then, perform a form submit action.
      checkoutForm.submit();
    }
    else {
      // Error: display an error message. Note that `response.message` contains
      // a preformatted error message. Also note that `response.code` will be
      // "invalid_card" in case of validation error on the card.

      console.log(response.message);
    }
  });
}

The full example code for HTML and JavaScript files can be found here.

Your backend can retrieve the token via POST request and process a charge.

Example PHP (checkout.php)

<?php

require_once dirname(__FILE__).'/omise-php/lib/Omise.php';

define('OMISE_PUBLIC_KEY', 'pkey_test_52jyu0r8o4307z0zz00');
define('OMISE_SECRET_KEY', 'skey_test_52jyu0r8mim84ylp454');

$charge = OmiseCharge::create(array(
  'amount'   => 10025,
  'currency' => 'thb',
  'card'     => $_POST["omiseToken"]
));

if ($charge['status'] == 'successful') {
  // Update order status to 'successful'.
} else {
  // Update order status to 'failed'.
}

Learn more about Collecting Cards.

Use Omise pre-built payment form

Omise.js also provides a pre-built payment form which you can easily integrate to your checkout page. The form handles data collection and sends it to Omise server; you won't have to implement HTML and JavaScript code to handle the event by yourself.

Omise.js will create a button inside your <form></form> element provided with the pre-built form. This button will trigger the payment form once it's clicked.

Note: Previously, the payment form was separated in a library called Card.js. We recently made an update, and it is now part of Omise.js

The following documents will guide you through the steps in integrating Omise pre-built payment form into your checkout page.

Implementation

To use Omise pre-built payment form inside your <form></form> element, insert Omise.js with some data attributes to config an output of the pre-built payment form.

Not that you must only insert Omise.js under <form></form> element, or else Omise.js will raise an error Missing form element for omise script tag (see how to prevent this error in Customization).

Example

<html>
<body>
  <form class="checkout-form" name="checkoutForm" method="POST" action="/checkout">
    <script type="text/javascript" src="https://cdn.omise.co/omise.js"
            data-key="YOUR_PUBLIC_KEY"
            data-amount="10025"
            data-button-label="Click to see an example">
    </script>
  </form>
</body>
</html>

Omise.js automatically renders a 'Click to see an example' button and <input type="hidden" name="omiseToken"> element under your form element.

The following are data attributes that you can config with Omise.js pre-built payment form.

Data attributes

Name type default description
data-key string "" (required) the public key which can be found on your dashboard
data-amount number 0 (required) the amount to be paid in the smallest unit of the currency, e.g. Satangs (100 Satangs = THB 1)
data-currency string "THB" the currency to be displayed in the payment window (THB, USD, JPY it can be lowercase)
data-image string "" the URI to your logo image. eg. http://example.com/logo.png
data-frame-label string "Omise" the header text you want displayed in the credit card popup window
data-frame-description string "" the description text will display below header text
data-submit-label string "Checkout" the label to be displayed in the submit button in credit card popup window
data-button-label string "Pay with Omise" the label to be displayed in the button that is embeded in your form
data-location string "no" presence of this attribute with any non-blank value indicates that the popup will have the postal code and city fields included (yes or no)
data-locale string "en" language of credit card form. (en, ja, th)

Customization

You can use the approach below to customize the button in forms that have complex structures where the Omise.js script cannot be inserted into the

element directly (for example, Ajax forms), or to attach a specific configuration into your own buttons.

configure(config)

Set default configuration for every button that triggers the credit card form.

Name type default description
config object {} Default config for every button. Please see configurations that are available below.

Examples

<script>
  // Set default config.
  OmiseCard.configure({
    publicKey:        'YOUR_PUBLIC_KEY',
    amount:           99500,
    currency:         'thb',
    image:            'YOUR_LOGO_URL',
    frameLabel:       'Merchant name',
    frameDescription: 'Merchant description',
    submitLabel:      'Pay',
    buttonLabel:      'Pay with Omise',
    location:         'no',
    submitFormTarget: null,
  });
</script>

configureButton(selector, config)

Sets configuration for specific buttons. This is applicable when there are more than one button which triggers the credit card form.

Name type default description
selector string {} Selector for target button.
config object {} Configure for button. (You can using config same as default.)

Examples

<script>
  // Default configure
  OmiseCard.configure(/* ...config */);


  // Button configure will merged and override with default configure.
  // And has effect with this button only.
  OmiseCard.configureButton('#checkout-button', {
    amount:           99500,
    currency:         'thb',
    image:            'YOUR_LOGO_URL',
    frameLabel:       'Merchant name',
    frameDescription: 'Merchant description',
    submitLabel:      'Pay',
    buttonLabel:      'Pay with Omise',
    location:         'no',
    submitFormTarget: null,
  });
</script>

attach()

Attach configuration to all target buttons that have been configured using configureButton.

Examples

<script>
  OmiseCard.configure({
    publicKey: 'YOUR_PUBLIC_KEY',
    amount: 99500
  });

  OmiseCard.configureButton('#checkout-button', {
    frameLabel: 'Merchant name',
    submitLabel: 'PAY RIGHT NOW !',
  });

  OmiseCard.attach();
</script>

Sample code

There are various use cases in order to customize the button to match with your requirement. Please have a look on our code example repository on GitHub from the link below to learn more on how to integrate Omise.js pre-built payment form with your checkout page.

Link: https://github.com/omise/examples/tree/master/omise.js