Skip to content

Openpay.js

Intro

What is Openpay.js?

Openpay.js is a Javascript library designed to facilitate the creation of tokens based on credit and debit cards' data retrieved from a web page without passing any information through the source server (the server of the business).

Advantages:

  • It's safe, the card information does not pass through the source server, but is sent directly to Openpay.
  • It's the fastest and easiest way to integrate our charges module on your web page.

First Steps

The first step is to add the Openpay.js library to your page as shown below:

<script type="text/javascript" src="https://js.openpay.mx/openpay.v1.min.js"></script>

Configuration

To use Openpay.js you must configure both the ID of the business and the public key that were assigned to you when you created your account on the sandbox dashboard. With these data, Openpay can identify your operations and can assign your cards and charges.

To configure both parameters use the methods OpenPay.setId() and OpenPay.setApiKey(), respectively:

OpenPay.setId('MERCHANT_ID');
OpenPay.setApiKey('PUBLIC_API_KEY');

Note: You can obtain both MERCHANT-ID and the PUBLIC_API_KEY in the dashboard when you log in on your openpay account, in the home page or in your profile page.

Recuerda: You should never use your private key with this library, because the key is visible on the client side.

Enable sandbox mode

There is a sandbox environment for you to try on your implementation, which is enabled with the method: OpenPay.setSandboxMode ().

OpenPay.setSandboxMode(FLAG);

Parameter FLAG parameter is a true / false flag to enable or disable test mode.

If necessary, you can use the OpenPay.getSandboxMode() method to determine the status of the sandbox mode at any time:

OpenPay.getSandboxMode(); // TRUE/FALSE, dependiendo si el modo está activado o no.

Note: The sandbox environment has the same features as production, but it only allows the use of certain card numbers, chosen with testing purposes more information on the test section.

Creating tokens without a form.

Once you have installed and you set up the library, you’ll need to call the OpenPay.token.create () method in order to create a token.

OpenPay.token.create(CREATE_PARAMETERS_OBJECT, SUCCESS_CALLBACK, ERROR_CALLBACK);

The parameters for this method are:

  • Parameter CREATE_PARAMETERS_OBJECT is a Javascript object containing the card information.
  • Parameter SUCCESS_CALLBACK defines the function to be called if the operation was successful.
  • Parameter ERROR_CALLBACK defines the function to be called if the operation failed.

Example of creating a token:

OpenPay.token.create({
      "card_number":"4111111111111111",
      "holder_name":"Juan Perez Ramirez",
      "expiration_year":"20",
      "expiration_month":"12",
      "cvv2":"110",
      "address":{
         "city":"Querétaro",
         "line3":"Queretaro",
         "postal_code":"76900",
         "line1":"Av 5 de Febrero",
         "line2":"Roble 207",
         "state":"Queretaro",
         "country_code":"MX"
      }
}, onSuccess, onError);

The method returns an object type token with an id which you’ll need later. You’ll find the definition of the token object here.

Creating tokens with a form

The Openpay.js library facilitates the extraction of the card information using a form, so you can send it later through the OpenPay.token.extractFormAndCreate()

OpenPay.token.extractFormAndCreate(CREATE_FORM_OBJECT, SUCCESS_CALLBACK, ERROR_CALLBACK);

The parameters for this method are:

  • Parameter CREATE_FORM_OBJECT is a Javascript object containing the card information.
  • Parameter SUCCESS_CALLBACK defines the function to be called if the operation was successful.
  • Parameter ERROR_CALLBACK defines the function to be called if the operation failed.

To start creating tokens, you must have a form like this:

<form id="processCard" name="processCard">
    <p>Holder Name:</p><input data-openpay-card="holder_name" size="50" type="text">
    <p>Card number:</p><input data-openpay-card="card_number" size="50" type="text">
    <p>Expiration year:</p><input data-openpay-card="expiration_year" size="4" type="text">
    <p>Expiration month:</p><input data-openpay-card="expiration_month" size="4" type="text">
    <p>cvv2:</p><input data-openpay-card="cvv2" size="5" type="text">
    <p>Street:</p><input data-openpay-card-address="line1" size="20" type="text">
    <p>Number:</p><input data-openpay-card-address="line2" size="20" type="text">
    <p>References:</p><input data-openpay-card-address="line3" size="20" type="text">
    <p>Postal code:</p><input data-openpay-card-address="postal_code" size="6" type="text">
    <p>City:</p><input data-openpay-card-address="city" size="20" type="text">
    <p>State:</p><input data-openpay-card-address="state" size="20" type="text">
    <p>Country code:</p><input data-openpay-card-address="country_code" size="3" type="text">
    <input id="makeRequestCard" type="button" value="Make Card">
</form>

Note: The most important thing is to add the data-openpay-card and data-openpay-card-address on the inputs of the card information and the card address because that’s how the method knows where to get those values​​.

Later when generating the token, call the token.extractFormAndCreate()method as shown below:

OpenPay.token.extractFormAndCreate(
      $('#processCard'),
      successCard,
      errorCard,
      _customerId);

The method returns an object type token with an id which you’ll need later. You’ll find the definition of the token object here.

For an example download the sample page from the github site: openpay-js

Handling responses

The response functions are to handle the operations results. They are simple Javascript functions but they receive an object type response as parameter .

The fields of the response object are described below:

Field

Format

Description

status

Integer

Describes the HTTP status of the operation. In case of an error before sending the request, the status will be equal to zero. In case of success it is 200.

message

String

It only occurs in cases of error. Short description of the error that has occurred. It can be one of the following values: "Unknown error", "Request error", "Response error (Unknown final status)", "Empty or invalid OpenPay ID", "Empty or invalid API Key", "Browser error", " Timeout after X milliseconds ".

data

Objeto

It contains an Error Object with the information of the error in the transaction provided by the Openpay server.

In case of success, it contains a token-type object.

Notes: Although the response functions are optional, we recommend that they be implemented so that the result of the transaction can be monitored on the web page.

In case of success: SuccessCallback

This function is called when the operation was successful from start to finish. It receives a single parameter which is a Javascript object with the token data.

Complete example of implementing a SuccessCallback function:

function SuccessCallback(response) {
    alert('Operación exitosa');
    var content = '', results = document.getElementById('resultDetail');
    content .= 'Id tarjeta: ' + response.data.id+ '
';
    content .= 'A nombre de: ' + response.data.holder_name + '
';
    content .= 'Marca de tarjeta usada: ' + response.data.brand + '
';
    results.innerHTML = content;
}

In case of error: ErrorCallback

This function will be executed every time an operation has failed (for any reason, before or after sending the request). Like the SuccessCallback (), it receives a single parameter which is a Javascript object with the detail of the failure.

Complete example of implementation of an ErrorCallback function:

function ErrorCallback(response) {
    alert('Fallo en la transacción');
    var content = '', results = document.getElementById('resultDetail');
    content .= 'Estatus del error: ' + response.data.status + '
';
    content .= 'Error: ' + response.message + '
';
    content .= 'Descripción: ' + response.data.description + '
';
    content .= 'ID de la petición: ' + response.data.request_id + '
';
    results.innerHTML = content;
}

Types of error

In addition to the status field that saves the status of the transaction, it is possible to determine the error that has occurred through the message field. The message can be one of the following:

  • Empty or invalid OpenPay ID: It happens when the user ID has not been set correctly with the OpenPay.setId () method
  • Empty or invalid API Key: Like the above error, it happens when the API Key has not been set with the OpenPay.setApiKey () method
  • Browser error: It is triggered when there is an error in the browser that prevents the request from being carried out correctly. It can be caused by features that are necessary to run certain code and are missing from the browser. For more information see the section "Compatibility and requirements".
  • Request error: This error indicates that there was an error on the Openpay server. It may be due to missing parameters, formats, or some other problem that is preventing the transaction from successfully completing.
  • Response error (Unknown final status): When this error is generated, it means that the transaction request was successfully sent to the Openpay server but no response was received. This may be due to a problem in Openpay. For more information contact OpenPay.
  • Timeout after X milliseconds: It is launched when the request has taken a long time to execute and therefore the response time expires.
  • Unknown error: It is generated when there is an unknown error that prevents the request from being made. It may be due to browser or connectivity problems.

Validation functions

Besides the functions to process card charges, Openpay.js also includes some functions to validate the main data needed to carry out the transaction, specially regarding card numbers.

The available methods are:

  • OpenPay.card.validateCardNumber()
  • OpenPay.card.validateCVC()
  • OpenPay.card.validateExpiry()
  • OpenPay.card.cardType()


Card number validation

To validate a card number you can use the OpenPay.card.validateCardNumber().

This method receives a String as a parameter with the card number which will be validated and will return true / false depending if the card it’s valid and is accepted by Openpay. Example

OpenPay.card.validateCardNumber('5555555555554444');

This method is very useful for determining whether a card number is valid and if it’s able to be used with Openpay, so we recommend that you use it routinely before attempting a card charge.

Examples:

OpenPay.card.validateCardNumber('5555555555554444');
// TRUE. Número de tarjeta válido y aceptado por OpenPay (MASTERCARD)
OpenPay.card.validateCardNumber('378282246310005');
// FALSE. Número de tarjeta válido pero no aceptado por OpenPay (AMEX) 

Security Code Validation

To validate the security code use the OpenPay.card.validateCVC().

This method receives a String as a parameter and returns true / false depending if the string is valid.

Examples:

OpenPay.card.validateCVC('123'); // válido
OpenPay.card.validateCVC('1234'); // válido
OpenPay.card.validateCVC('A23'); // inválido

Additionally, the security code can be validated by passing the card number as the second parameter, to determine if the code is valid for the type of card in question.

Examples:

OpenPay.card.validateCVC('123','5555555555554444');
// válido, tarjeta MASTERCARD y CVC de longitud 3
OpenPay.card.validateCVC('1234','5555555555554444');
// inválido, tarjeta MASTERCARD y CVC de longitud 4
OpenPay.card.validateCVC('123','378282246310005');
// inválido, tarjeta AMERICAN EXPRESS y CVC de longitud 3
OpenPay.card.validateCVC('1234','378282246310005');
// válido, tarjeta AMERICAN EXPRESS y CVC de longitud 4

Expiration date Validation

For this purpose use the OpenPay.card.validateExpiry().

This method receives two strings as parameters representing the expiration month and year of the card. It returns true / false depending if the combination of both data, month and year, are a valid expiration date. Example:

OpenPay.card.validateExpiry('01', '2013'); // inválido
OpenPay.card.validateExpiry('05', '2015'); // válido

Validation of the type of card

It can be determined (most of the time) the type of card that belongs to a card number. For this, use the OpenPay.card.cardType().

The method receives a card number as a parameter and returns a String with the name of the card type.

Examples:

OpenPay.card.cardType('5555555555554444'); // Mastercard
OpenPay.card.cardType('4111111111111111'); //​ Visa
OpenPay.card.cardType('4917300800000000'); // Visa Electron
OpenPay.card.cardType('378282246310005'); // American Express
OpenPay.card.cardType('30569309025904'); // Diners Club Carte Blanche
OpenPay.card.cardType('6011111111111117'); // Discover
OpenPay.card.cardType('3530111333300000'); // JCB

Compatibility and Requirements

To use Openpay.js is necessary to have one of the following browsers:

  • Chrome 29.0+
  • Firefox 23.0+
  • Safari 5.1+
  • Opera 17.0+
  • iOS Safari 4.0+
  • Android Browser 2.1+
  • Blackberry Browser 7.0+
  • IE Mobile 10.0

It’s required that the browsers have support for the XMLHttpRequest and JSON Parser libraries.