Skip to main content

Create token

Last updated: 30-Dec-2021
Rate this article:

Overview

The 2co.js JavaScript library provides you with a way to securely tokenize sensitive credit card data on your website so that the data never touches your server. All you need to integrate is a simple form to collect the payment details and JavaScript functions to handle the success and error callbacks.

In this section, we will go through all of the necessary steps to tokenize your customer’s credit card details and submit the token to your server so that the sale can be created.

   This token is only good for one sale and expires if not used within 30 minutes.

Include 2co.js on your Checkout Page

<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>

This library handles the secure communication with our API by encrypting the card details and returning a non-reversible token that you can safely submit to your server. It provides you with 2 functions, one to load the public encryption key, and one to make the token request.

The TCO.loadPubKey(String environment, Function callback) function must be used to asynchronously load the public encryption key before making the token request.

The callback is optional if you are calling this function immediately when the page loads. However, if you want to pull in the public key at a different point, such as right before we make the token request, a callback function should be passed as the second argument to ensure that it is loaded before the token request is made.

TCO.loadPubKey('production', function() {
    // Execute when Public Key is available
});​

Create your payment form

The payment form provides the buyer with the appropriate fields to enter in their card details. Once entered, you will be able to grab the field values and submit a client-side token request so that the sensitive card details never touch your server.

<form id="myCCForm" action="https://www.mysite.com/examplescript.php" method="post">
  <input name="token" type="hidden" value="" />
  <div>
    <label>
      <span>Card Number</span>
      <input id="ccNo" type="text" value="" autocomplete="off" required />
    </label>
  </div>
  <div>
    <label>
      <span>Expiration Date (MM/YYYY)</span>
      <input id="expMonth" type="text" size="2" required />
    </label>
    <span> / </span>
    <input id="expYear" type="text" size="4" required />
  </div>
  <div>
    <label>
      <span>CVC</span>
      <input id="cvv" type="text" value="" autocomplete="off" required />
    </label>
  </div>
  <input type="submit" value="Submit Payment" />
</form>
   To ensure that no sensitive data touches your server, the input fields for the card number and CVC code cannot have “name” attributes. This will ensure that the credit card details are not included in the request when it is submitted to your server.

If you use this example on your webpage, you need to change “https://www.mysite.com/examplescript.php” to the URL that the token will be submitted to.

Integrate your Form with 2co.js

2co.js provides you with the TCO.requestToken(Function callback, Function callback, Object arguments) function to make the token request. This function takes 3 arguments:

  • Your success callback function which accepts one argument and will be called when the request is successful.
  • Your error callback function which accepts one argument and will be called when the request results in an error.
  • An object containing the credit card details and your credentials.
Attribute Description
sellerId 2Checkout account number
publishableKey Payment API publishable key
ccNo Credit Card Number
expMonth Card Expiration Month
expYear Card Expiration Year
cvv Card Verification Code

If you would rather not pull the values from the form yourself, you can pass the ID of your form in place of the arguments object when making the token request. Just add your seller ID and publishable key to the form as hidden input elements and use the naming conventions shown above on the input field ID’s and 2co.js will pull the values for you.

Example Functions to use with your Form

The following example JavaScript provides functions to block the submission on the example form, make the token request, and handle the success/error response so that the token can be safely passed to your server.

<script type="text/javascript">

  // Called when token created successfully.
  var successCallback = function(data) {
    var myForm = document.getElementById('myCCForm');

    // Set the token as the value for the token input
    myForm.token.value = data.response.token.token;

    // IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
    myForm.submit();
  };

  // Called when token creation fails.
  var errorCallback = function(data) {
    if (data.errorCode === 200) {
      // This error code indicates that the ajax call failed. We recommend that you retry the token request.
    } else {
      alert(data.errorMsg);
    }
  };

  var tokenRequest = function() {
    // Setup token request arguments
    var args = {
      sellerId: "1817037",
      publishableKey: "E0F6517A-CFCF-11E3-8295-A7DD28100996",
      ccNo: $("#ccNo").val(),
      cvv: $("#cvv").val(),
      expMonth: $("#expMonth").val(),
      expYear: $("#expYear").val()
    };

    // Make the token request
    TCO.requestToken(successCallback, errorCallback, args);
  };

  $(function() {
    // Pull in the public encryption key for our environment
    TCO.loadPubKey('production');

    $("#myCCForm").submit(function(e) {
      // Call our token request function
      tokenRequest();

      // Prevent form from submitting
      return false;
    });
  });

</script>

Success Response Object

When your success callback is called, a response object will be returned which provides the token and the customer’s sanitized card details.

Attribute Description
type Always TokenResponse
token Sub Object containing the `token` and `dateCreated`.
paymentMethod Sub Object containing the sanitized card details.

Response Object Example, Success Callback

{
    "exception": null,
    "response": {
        "type": "TokenResponse",
        "token": {
            "dateCreated": 1382539697848,
            "token": "OWRhYjVhNDUtYjE2NS00ZGRhLTk4MjgtNjM1ZThjNDM1NjNk"
        },
        "paymentMethod": {
            "expMonth": "01",
            "expYear": "2018",
            "cardType": "VS",
            "cardNum": "XXXX-XXXX-XXXX-3315"
        },
        "errors": null
    },
    "validationErrors": null
}

Error Response Object

If an error occurs during this process or if the buyer has not included all of the required card details, the error callback function is called. An object will be returned which provides the error message and error code so that you can display a message to your customer.

Error Code Error Message Cause
300 Unauthorized Seller unauthorized to use the API or incorrect publishable key.
400 Bad request - parameter error Payment form is missing attributes.
401 Bad request - missing data Payment form is missing required attributes.
200 Unable to process the request Ajax request failed or busy.
500 Request failed. Payment API error.

Response Object Example, Error Callback

{
    "errorCode": "300",
    "errorMsg": "Unauthorized"
}

Sending the token to your server

The token provided to your success callback can be added to the form input element you are using to hold the token value and you can submit the form to your server and charge the credit card using the “authorization” API call.

var successCallback = function(data) {
    var myForm = document.getElementById('myCCForm');

    // Set the token as the value for the token input
    myForm.token.value = data.response.token.token;

    // IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
    myForm.submit();
};

Example Complete Page

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Form</title>
  <script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form id="myCCForm" action="https://www.mysite.com/examplescript.php" method="post">
  <input name="token" type="hidden" value="" />
  <div>
    <label>
      <span>Card Number</span>
      <input id="ccNo" type="text" value="" autocomplete="off" required />
    </label>
  </div>
  <div>
    <label>
      <span>Expiration Date (MM/YYYY)</span>
      <input id="expMonth" type="text" size="2" required />
    </label>
    <span> / </span>
    <input id="expYear" type="text" size="4" required />
  </div>
  <div>
    <label>
      <span>CVC</span>
      <input id="cvv" type="text" value="" autocomplete="off" required />
    </label>
  </div>
  <input type="submit" value="Submit Payment" />
</form>

<script>
  // Called when token created successfully.
  var successCallback = function(data) {
    var myForm = document.getElementById('myCCForm');

    // Set the token as the value for the token input
    myForm.token.value = data.response.token.token;

    // IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
    myForm.submit();
  };

  // Called when token creation fails.
  var errorCallback = function(data) {
    // Retry the token request if ajax call fails
    if (data.errorCode === 200) {
       // This error code indicates that the ajax call failed. We recommend that you retry the token request.
    } else {
      alert(data.errorMsg);
    }
  };

  var tokenRequest = function() {
    // Setup token request arguments
    var args = {
      sellerId: "1817037",
      publishableKey: "E0F6517A-CFCF-11E3-8295-A7DD28100996",
      ccNo: $("#ccNo").val(),
      cvv: $("#cvv").val(),
      expMonth: $("#expMonth").val(),
      expYear: $("#expYear").val()
    };

    // Make the token request
    TCO.requestToken(successCallback, errorCallback, args);
  };

  $(function() {
    // Pull in the public encryption key for our environment
    TCO.loadPubKey('production');

    $("#myCCForm").submit(function(e) {
      // Call our token request function
      tokenRequest();

      // Prevent form from submitting
      return false;
    });
  });

</script>
</body>
</html>

Now that you have completed your client-side integration, please review our Create Sale documentation to complete your server-side integration.

Rate this article:

Need help?

Do you have a question? If you didn’t find the answer you are looking for in our documentation, you can contact our Support teams for more information. If you have a technical issue or question, please contact us. We are happy to help.

Not yet a Verifone customer?

We’ll help you choose the right payment solution for your business, wherever you want to sell, in-person or online. Our team of experts will happily discuss your needs.

Verifone logo