Omise.js

Topics covered on this page

Omise.js is our JavaScript library for collecting payment details on a user's browser and securely transmitting them to our servers. You are required to use Omise.js when accepting payment details on your website.

This document provides an overview of how Omise.js works and guides you through several methods of adding it to your checkout page.

Requirements

It is highly recommended that you also enable HTTPS on your entire site. Do not collect or store any card details on your server. See Security Best Practices for Merchants for more information.

How It Works

Omise.js provides a secure method of collecting credit card, debit card, and other payment method details on a user's browser.

Omise.js sends these details to designated servers, which return a one-time-use value: a token or a source. You can safely use this value on your server to create charges.

Image

Examples

The following GitHub repositories contain examples of using Omise.js.

Pre-built Payment Form

You can use Omise.js to request tokens and sources directly, or you can use our pre-built payment form. This form securely collects, validates, and sends user data to our servers. It also collects additional user browser data to help protect against fraud.

How the Pre-built Form Works

sequenceDiagram participant User participant Website participant OmiseJS participant PayJS participant Omise Server User->>Website: visits Website->>OmiseJS: loads OmiseJS->>OmiseJS: creates an iframe OmiseJS->>PayJS: loads /pay.html in an iframe PayJS->>OmiseJS: loads OmiseJS PayJS->>PayJS: loads PayJS PayJS->>Website: displays payment methods/form Website->>PayJS: sends the user payload PayJS->>PayJS: validates the payload alt validation fails PayJS->>User: displays errors else PayJS->>OmiseJS: sends the payload OmiseJS->>Omise Server: Calls either /token or /source API Omise Server-->>OmiseJS: returns token/source object OmiseJS->>PayJS: Sends API response alt API returned an error PayJS->>Website: Shows error message else PayJS->>OmiseJS: Sends result OmiseJS->>Website: Sends token or source or both end end

The integration follows this sequence:

  1. The user (customer) accesses your checkout page.
  2. The website loads OmiseJS.
  3. OmiseJS creates an iframe for secure payment collection.
  4. OmiseJS loads pay.html in the iframe.
  5. PayJS loads OmiseJS in a secure environment.
  6. PayJS loads itself and prepares the payment interface.
  7. The system displays payment methods/a form for the user.
  8. When the customer submits payment information, the payload is sent to PayJS.
  9. PayJS validates the payload.
  10. If validation fails, the system displays errors to the customer.
  11. If validation succeeds:
    1. Payload is sent to OmiseJS.
    2. OmiseJS calls either the /token or the /source API.
    3. Omise Server returns the token/source object.
    4. OmiseJS sends the API response to PayJS.
    5. If the API returns an error, the system displays an error message.
    6. If the API call is successful:
      1. PayJS sends the result to OmiseJS.
      2. OmiseJS sends the token, source, or both to the website.
      3. The website processes the data.
      4. The server initiates payment using the token/source.
      5. The server receives the payment result.
      6. The server updates the payment status.
      7. The website displays the result to the customer.

By default, Omise.js will render a Pay with Omise button. Click the following button to see an example. You should see a payment form pop up.


On the payment form, the user enters their payment details. Clicking the Pay 123.45 THB button requests a one-time use token or source directly from our servers.

The form can be configured using either HTML data attributes or JavaScript.

Using Data Attributes

When using data attributes, no custom JavaScript is required. You can configure your payment form by adding HTML to your checkout page.

Usage

On your checkout page, add the following:

<form id="checkoutForm" method="POST" action="/charge">
  <script type="text/javascript" src="https://cdn.omise.co/omise.js"
          data-key="OMISE_PUBLIC_KEY"
          data-amount="12345"
          data-currency="THB"
          data-default-payment-method="credit_card">
  </script>
</form>

Notes:

  • The action path is located on your backend server and will accept a POST request containing the token or source.
  • The <script> element must be placed within the <form> element.
  • The data-key attribute specifies your public key.
  • The data-amount attribute specifies the amount you want to be displayed on the form in the smallest unit for a given currency.
  • The data-default-payment-method attribute specifies the default payment method.
  • See parameters for additional supported parameters.

Next Steps

Configure the /charge path on your server (or wherever action points to) to accept and process the parameters omiseToken and omiseSource.

If credit or debit card details were submitted, the omiseToken parameter would be set to the generated token identifier, and omiseSource will be null.

If details for another payment method were submitted, the omiseSource parameter will be set to the generated source identifier, and omiseToken will be null.

See Processing Tokens and Sources.

Using JavaScript

You can also configure the payment form's behavior using JavaScript. Omise.js provides an OmiseCard object for this purpose.

Usage

On your checkout page, add the following:

<form id="checkoutForm" method="POST" action="/charge">
  <input type="hidden" name="omiseToken">
  <input type="hidden" name="omiseSource">
  <button type="submit" id="checkoutButton">Checkout</button>
</form>

<script type="text/javascript" src="https://cdn.omise.co/omise.js">
</script>

<script>
  OmiseCard.configure({
    publicKey: "OMISE_PUBLIC_KEY"
  });

  var button = document.querySelector("#checkoutButton");
  var form = document.querySelector("#checkoutForm");

  button.addEventListener("click", (event) => {
    event.preventDefault();
    OmiseCard.open({
      amount: 12345,
      currency: "THB",
      defaultPaymentMethod: "credit_card",
      onCreateTokenSuccess: (nonce) => {
          if (nonce.startsWith("tokn_")) {
              form.omiseToken.value = nonce;
          } else {
              form.omiseSource.value = nonce;
          };
        form.submit();
      }
    });
  });
</script>

Notes:

  • The action path is a location on your backend server that accepts a POST request containing the token or source.
  • See parameters for additional supported parameters.

Next Steps

Configure the /charge path on your server (or wherever action points to) to accept and process the parameters omiseToken and omiseSource.

If credit or debit card details were submitted, the omiseToken parameter would be set to the generated token identifier, and omiseSource will be null.

If details for another payment method were submitted, the omiseSource parameter will be set to the generated source identifier, and omiseToken will be null.

See Processing Tokens and Sources.

OmiseCard Methods

You can use the following methods on OmiseCard to customize the appearance and behavior of your form.

configure

Set the default configuration for the form. This is a good place to set your public key. Buttons configured via the configureButton method will inherit this configuration. The form opened using the open method will also inherit this configuration.

You must call this method before calling the open method.

Parameter Type Default Description
config object {} Default configuration for button(s).
OmiseCard.configure({
  publicKey: 'OMISE_PUBLIC_KEY',
});
configureButton

Set button-specific configuration for the form. If a button is outside the form, include the configuration object key submitFormTarget to point to your form.

Parameter Type Default Description
selector string - Selector for button.
config object {} Configuration for button.
OmiseCard.configure({
  publicKey: 'OMISE_PUBLIC_KEY'
});

OmiseCard.configureButton('#checkout-button', {
  amount: 3000,
  currency: 'USD',
  buttonLabel: 'Pay 30 USD'
});

OmiseCard.configureButton('#checkout-button-alt', {
  amount: 100000,
  currency: 'THB',
  buttonLabel: 'Pay 1000 THB'
});
attach

Attach set configurations to buttons that you have configured using configureButton. After attaching the configuration to all target buttons, clicking the button should trigger the form.

OmiseCard.configureButton('#checkout-button', {
  publicKey: 'OMISE_PUBLIC_KEY',
  amount: 10000,
  frameLabel: 'Merchant Name',
  submitLabel: 'Pay',
});

OmiseCard.attach();
open

Open the payment form.

You must call the configure method before calling this method.

Parameter Type Default Description
config object {} Configuration for target button.
OmiseCard.open({
  amount: 10000,
  submitFormTarget: '#checkout-form',
  onCreateTokenSuccess: (nonce) => {
    /* Handler on token or source creation.  Use this to submit a form or send an Ajax request to the server */
  },
  onFormClosed: () => {
    /* Handler on form closure. */
  },
})

Parameters

Data Attribute Parameter Description
data-amount amount (required) Amount shown on form
data-key publicKey (required) Your public key found on your dashboard
data-button-label buttonLabel Label to be displayed in the button embedded in your form. Default: Pay with Omise
data-currency currency Currency to be displayed in the payment window. Default: THB
data-default-payment-method defaultPaymentMethod Default payment method. Default: credit_card.
data-frame-description frameDescription Description text displayed below the header text
data-frame-label frameLabel Header text you want displayed in the popup window. Default: Omise
data-hide-amount hideAmount Whether to hide the amount on the submit button. Default: false
data-image image URI to your logo image. eg. https://example.com/logo.png
data-locale locale Language of form (en, ja, th). Default: en
data-location location Whether to include postal_code and city fields. Default: no
data-other-payment-methods otherPaymentMethods A comma-separated string of alternative payment method identifiers
data-submit-label submitLabel Label to be displayed in the submit button in a pop-up window. Default: Pay.
data-submit-form-target submitFormTarget Selector for payment form. Default: form selector for button parent element
- onCreateTokenSuccess Callback for token or source creation event. One parameter is provided to the callback: the token or source identifier
- onFormClosed Callback for form closure event. No parameters are provided to the callback

The following parameters are situational and only used by some payment methods.

Data Attribute Parameter Description
data-googlepay-merchant-id googlepayMerchantId For googlepay. Merchant ID for Google Pay (required when accepting live traffic).
data-googlepay-request-billing-address googlepayRequestBillingAddress For googlepay. Set to true to attach the cardholder's name and billing address to a card token. Supplying this improves your authorization rate for US, UK, and Candian cardholders.
data-googlepay-request-phone-number googlepayRequestPhoneNumber For googlepay. When the cardholder's billing address is requested, set to true to attach the cardholder’s phone number to a card token.
data-applepay-validation-url applepayValidationUrl The URL to validate your server and obtain a merchant session object for Apple Pay (required when accepting live traffic). See the Apple Pay document.
data-applepay-merchant-id applepayMerchantId Merchant ID for Apple Pay (required when accepting live traffic).
data-applepay-request-billing-address applepayRequestBillingAddress Set to true to attach the cardholder's name and billing address to a card token. Supplying this improves your authorization rate for US, UK, and Candian cardholders.

Supported Payment Methods for Pre-Built Form

While Omise.js supports all payment methods, only the pre-built form supports the following. Supported payment methods depend on your account settings and the country where your account is registered.

Alternative payment methods form example

Payment Method Documentation Supported Countries
alipay Alipay Thailand
alipay_cn Alipay CN Thailand, Singapore
alipay_hk Alipay HK Singapore
boost Boost Malaysia
convenience_store*, net_banking*, pay_easy* Convenience Store, Pay Easy, Online Banking Japan
credit_card Credit Card[Credit Card] Thailand, Singapore, Japan
dana DANA Singapore
duitnow_obw DuitNow Online Banking/Wallets Malaysia
duitnow_qr DuitNow QR Malaysia
fpx FPX Malaysia
gcash GCash Singapore
googlepay Google Pay Thailand, Singapore
applepay Apple Pay Singapore
grabpay GrabPay Thailand, Singapore, Malaysia
installment Installments Thailand
internet_banking†, internet_banking_bay, internet_banking_bbl Internet Banking Thailand
kakaopay KakaoPay Singapore
maybank_qr Maybank QR Malaysia
mobile_banking_bay Krungsri (KMA) Thailand
mobile_banking_bbl Bangkok Bank (Bualuang mBanking) Thailand
mobile_banking_kbank KBank (K PLUS) Thailand
mobile_banking_ktb Krung Thai (KTB NEXT) Thailand
mobile_banking_ocbc_pao OCBC Pay Anyone Singapore
mobile_banking_scb SCB (SCB Easy) Thailand
paynow PayNow Singapore
promptpay PromptPay Thailand
rabbit_linepay Rabbit Line Pay Thailand
shopeepay ShopeePay Thailand
touch_n_go Touch 'n Go Singapore
truemoney TrueMoney Wallet Thailand

* Created source type will be econtext.
All Internet banking sources will be presented to the user.

Contact support@omise.co if you would like to enable additional payment methods on your live account.

Requesting Tokens and Sources Directly

This approach provides the most flexibility and full support for all payment methods. However, you must create your form and handle all events.

Do not use name attributes as identifiers for your custom form <input> elements. When provided, the value of these elements is submitted with the form to your server.

Instead, use a data or id attribute as an identifier. This prevents sensitive information (like credit card numbers) from being sent to your server. See Merchant Security Best Practices

How a custom form works

sequenceDiagram participant User participant Website participant OmiseJS participant Core User->>Website: visits Website->>OmiseJS: loads Website-->>User: displays custom card form User->>Website: enters card details Website->>Website: validates the payload alt validation fails Website-->>User: displays errors else User->>Website: clicks Pay button Website->>OmiseJS: sends card details to create a token OmiseJS->>Core: Calls either /token or /source API Core-->>OmiseJS: returns token/source object OmiseJS->>Website: Sends API response alt API returned an error Website-->User: Shows error message else Website->>Website: Sends response to backend end end

The integration sequence is as follows:

  1. The user visits the website (User → Website).
  2. The website loads OmiseJS (Website → OmiseJS).
  3. The website displays a custom card form to the user (Website → User).
  4. The user enters the card details (User → Website).
  5. The website validates the payload internally (Website self-interaction).
  6. If the validation fails, the website displays errors to the user (Website → User).
  7. If the validation passes:
    1. The user clicks the Pay button (User → Website).
    2. The website sends the card details to create a token (Website → OmiseJS).
    3. OmiseJS calls either the /token or the /source API (OmiseJS → Core).
    4. Core returns the token/source object (Core → OmiseJS).
    5. OmiseJS sends the API response back to the website (OmiseJS → Website).
    6. If the API returns an error, The website shows the error message to the user (Website → User).
    7. If the API call is successful, the website sends the response to the backend (Website self-interaction).

Usage

Create a <script> element loading Omise.js.

<script type="text/javascript" src="https://cdn.omise.co/omise.js"></script>

Once loaded, the Omise object should be loaded into your environment.

Omise Methods

You can use the following methods on Omise to create a one-time-use token or source.

setPublicKey

Use your public key to authenticate.

Parameter Type Description
key string (required) Public key found on your dashboard
Omise.setPublicKey("OMISE_PUBLIC_KEY");

createToken

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

Parameter Type Description
type string (required) card
tokenParameters object (required) Request parameters for a token
callback function (required) A function that will be called when the request with the Omise server is completed. Two parameters are provided to the callback: the HTTP status code of the response and the response itself
tokenParameters = {
  "city": "New York",
  "country": "US",
  "expiration_month": 2,
  "expiration_year": 2022,
  "name": "Somchai Prasert",
  "number": "4242424242424242",
  "phone_number": "0123456789",
  "postal_code": 10320,
  "security_code": 123,
  "state": "NY",
  "street1": "476 Fifth Avenue"
};

Omise.createToken("card",
                  tokenParameters,
                  function(statusCode, response) {

  // response["id"] is token identifier

  console.log(response)
});

createSource

Create the one-time-use source object from the Omise server that you can use to create a charge. See Source API for available source types and required parameters.

Parameter Type Description
type string (required) Source type
sourceParameters object (required) Request parameters for source
callback function (required) A function that will be called when the request with the Omise server is completed. Two parameters are provided to the callback: the HTTP status code of the response and the response itself
sourceParameters = {
  "amount": 12345,
  "currency": "THB",
  "phone_number": "0123456789"
}

Omise.createSource("truemoney",
                   sourceParameters,
                   function(statusCode, response) {

  // response["id"] is source identifer

  console.log(response)
});

Processing Tokens and Sources

For tokens, see our guide to charging cards. For more detail and code examples, see the Charge API.

For sources, see the relevant guide in our API documentation under the category Payment Methods.

CDNs

You can load Omise.js from the following location:

  • https://cdn.omise.co/omise.js
Omise uses cookies to improve your overall site experience and collect information on your visits and browsing behavior. By continuing to browse our website, you agree to our Privacy Policy. Learn more