Skip to main content

Detail Sale

Overview

The detail_sale call is used to retrieve information about a specific sale or invoice.

URL: https://www.2checkout.com/api/sales/detail_sale

HTTP Method: GET


Input Parameters

Parameter Description
sale_id The order number of the requested sale. Optional if invoice_id is specified.
invoice_id The invoice number of the requested invoice (specify to include only the requested invoice. Omit and use sale_id to include all invoices).  Optional if sale_id is specified.

Data Returned

 

sale

Parameter Description
sale_id Order Number/Sale Number
ip_address Buyer IP Address
date_placed Date and time the order was placed
total Sale total amount
language Language sale was placed in (values: en,it,fr,no,es_ib,es_la,gr,nl,zh,da,jp,pt,sl,sv,el)
pay method Buyer Payment Method
cardholder_name Buyer full name
first_six_digits First 6 digits of credit card
last_two_digits Last 2 digits of credit card
method Method of sale payment (values: ach, credit card, amex, atmd, bill_me_later, fxsource, paypal_int, paypal_pl, acculynk)
avs AVS match
cvv CVV match

 

comment

Parameter Description
username User that entered the comment
timestamp Date and time the comment was entered
ip IP address of the user
comment_text Comment text

 

customer

Parameter Description
customer_id Customer ID
first_name Buyer first name
middle_initial Buyer middle initial
last_name Buyer last name
card_holder_name Buyer full name
email Buyer email address
phone Buyer phone number
phone_extension Buyer phone extension

 

address

Parameter Description
address_1 Billing address line 1
address_2 Billing address line 2
city Billing city
state Billing state
postal_code Billing postal code
country_code Billing country code
country Billing country

 

invoices

Parameter Description
invoice_id Invoice ID
sale_id Sale ID
status Sale Status (values: deposited, approved, declined, pending)
usd_total Invoice total in USD
vendor_total Invoice total in account pricing currency
customer_total Invoice total in buyer pricing currency
fees_2co 2CO transaction fees applied to invoice
recurring Recurring (values: 1=yes, 0=no)
recurring_decline Recurring (values: 1=yes, 0=no, NULL)
date_placed Date and time the invoice was placed
date_shipped Date and time invoice was shipped
date_vendor_paid Date paid
referrer Invoice referrer url
vendor_order_id Merchant Order ID

 

lineitems

Parameter Description
lineitem_id Line item ID
vendor_product_id Merchant assigned product ID
affiliate_vendor_id Affiliate ID
product_description Product short description
product_handling Product handling fee
product_name Product Name
product_price Line item price
product_recurrence Product Recurrence (values: A number followed by a space followed by “day”, “week”, “month” or “year”)
product_duration Recurring duration (values: “Forever” or a number followed by a space followed by “day”, “week”, “month” or “year”)
product_startup_fee Startup fee
product_tangible Tangible or Intangible (values: 1=intangible, 0=intangible)
product_is_cart Third Party Cart ID or “0” if none
installment Current installment for recurring billing items
type Line item type (values: null = products including 2Checkout Signup, signup fee, affiliate, shipping, partial, chargeback, coupon)
flat rate Flat rate commission amount of line item affiliate commission (VA Affiliate Program)
percentage Percentage of line item affiliate commission (VA Affilate Program)
lc_affiliate_vendor_id ID of affiliate credited for line item commission (VA Affiliate Program)
lc_usd_amount Amount of line item affiliate commission (VA Affiliate Program)
commission Global Affiliates commission amount
commission_affiliate_vendor_id Global Affiliates affiliate credited for line item commission
commission_flat_rate Global Affiliates flat rate commission amount
commission_percentage Global Affiliates commission percentage
commission_type Global Affiliates commission type (amount or percentage)
commission_usd_amount Global Affiliates commission USD amount

 

option

Parameter Description
lineitem_id Line item ID used with option
lineitem_option_id Product option ID
option_name Product option name
option_value Product option value
usd_surcharge surcharge in USD
vendor_surcharge Surcharge in account pricing currency
customer_surcharge Surcharge in buyer currency

 

billing

Parameter Description
billing_id Billing ID
usd_amount Billing amount in USD
vendor_amount Billing amount in account pricing currency
customer_amount Billing amount in buyer currency
customer_id 2Checkout system buyer ID
installment current installment for recurring billing items
product_recurrence Billing Recurrence (values: A number followed by a space followed by “day”, “week”, “month” or “year”)
product_duration Billing duration (values: “Forever” or a number followed by a space followed by “day”, “week”, “month” or “year”)
date_next Next lineitem recurring billing date
date_start Lineitem recurring date started.
date_end Recurring lineitem duration end date.
date_fail Last lineitem declined date
date_pending Lineitem billing date pending
date_deposited Lineitem billing date deposited
recurring_status Lineitem recurring status
status Bill Status (values: bill, refund)
bill_method Billing method (values: NULL, ach, credit_card, amex, atmd, bill_me_later, fxsource, paypal_int, paypal_pl, acculynk)

 

shipping

Parameter Description
shipping_id Shipment ID for invoice
date_shipped Date and time the invoice was shipped
tracking_number Tracking number entered on invoice
tracking_url Tracking url listed on shipping method
shipping_method_id Shipping method ID
shipping_method Shipping method name
shipping_name Recipient name
address_1 Shipping address line 1
address_2 Shipping address line 2
city Shipping city
state Shipping state
postal_code Shipping postal code
country_code Shipping country code
country Shipping country

 

Example API Call

curl -G https://www.2checkout.com/api/sales/detail_sale \
    -H 'Accept: application/json' -d 'sale_id=4647892238' -u 'username:password'

 

Example Successful Response

{
   "response_code" : "OK",
   "response_message" : "Sale detail retrieved",
   "sale" : {
      "comments" : [
         {
            "changed_by_ip" : "192.168.0.1",
            "comment" : "[* Sent: Vendor *] Refund Issued On Sale: test sale",
            "timestamp" : "2012-03-31 10:56:31",
            "username" : "api_user"
         },
         {
            "changed_by_ip" : "192.168.0.1",
            "comment" : "[* Sent: Vendor *] Recurring billing stopped for test",
            "timestamp" : "2012-03-31 10:56:30",
            "username" : "api_user"
         }
      ],
      "customer" : {
         "address_1" : "123 test st",
         "address_2" : null,
         "address_id" : "4647892310",
         "cardholder_name" : "Testing  Tester",
         "city" : "test",
         "country_code" : "USA",
         "country_name" : "United States",
         "customer_id" : "4647892244",
         "email_address" : "api_user@fake-company.com",
         "first_name" : "Testing",
         "lang" : "en",
         "last_name" : "Tester",
         "middle_initial" : null,
         "pay_method" : {
            "avs" : null,
            "cvv" : null,
            "first_six_digits" : null,
            "last_two_digits" : null,
            "method" : "paypal ec"
         },
         "phone" : "123465789",
         "phone_ext" : "",
         "postal_code" : "43123",
         "prefix" : null,
         "state" : "OH"
      },
      "date_placed" : "2012-02-29 13:29:28",
      "detail_ip" : {
         "address" : "66.194.132.135",
         "area_code" : 740,
         "city" : "Galena",
         "country" : "United States",
         "country_code" : "US",
         "region" : "OH",
         "zip" : "43021"
      },
      "invoices" : [
         {
            "customer_total" : "1.00",
            "date_placed" : "2012-02-29 13:29:28",
            "date_shipped" : null,
            "date_vendor_paid" : null,
            "fees_2co" : "0.54",
            "invoice_id" : "4647892247",
            "lineitems" : [
               {
                  "affiliate_vendor_id" : null,
                  "billing" : {
                     "amount" : "1.53",
                     "bill_method" : "paypal_int",
                     "billing_id" : "4647892307",
                     "customer_amount" : "1.00",
                     "customer_id" : "4647892244",
                     "date_deposited" : "2012-02-29",
                     "date_end" : null,
                     "date_fail" : "2012-03-07",
                     "date_next" : "2012-03-29",
                     "date_pending" : "2012-02-29",
                     "date_start" : "2012-03-02",
                     "lineitem_id" : "4647892301",
                     "recurring_status" : "completed",
                     "status" : "bill",
                     "usd_amount" : "1.53",
                     "vendor_amount" : "1.00"
                  },
                  "commission" : null,
                  "commission_affiliate_vendor_id" : null,
                  "commission_flat_rate" : null,
                  "commission_percentage" : null,
                  "commission_type" : null,
                  "commission_usd_amount" : null,
                  "customer_amount" : "1.00",
                  "flat_rate" : null,
                  "installment" : "1",
                  "invoice_id" : "4647892247",
                  "lc_affiliate_vendor_id" : null,
                  "lc_usd_amount" : null,
                  "lineitem_id" : "4647892301",
                  "linked_id" : null,
                  "options" : [],
                  "percentage" : null,
                  "product_description" : "test",
                  "product_duration" : "Forever",
                  "product_handling" : "0.00",
                  "product_id" : "4647888428",
                  "product_is_cart" : "0",
                  "product_name" : "test",
                  "product_price" : "1.00",
                  "product_recurrence" : "1 Month",
                  "product_startup_fee" : null,
                  "product_tangible" : "0",
                  "sale_id" : "4647892238",
                  "status" : "bill",
                  "type" : null,
                  "usd_amount" : "1.53",
                  "usd_commission" : null,
                  "vendor_amount" : "1.00",
                  "vendor_product_id" : "1178646973"
               },
               {
                  "affiliate_vendor_id" : null,
                  "billing" : {
                     "amount" : "1.53",
                     "bill_method" : "paypal_int",
                     "billing_id" : "4672854535",
                     "customer_amount" : "1.00",
                     "customer_id" : "4647892244",
                     "date_deposited" : "2012-03-31",
                     "date_end" : null,
                     "date_fail" : "2012-04-05",
                     "date_next" : null,
                     "date_pending" : "2012-03-31",
                     "date_start" : "2012-03-31",
                     "lineitem_id" : "4672854532",
                     "recurring_status" : null,
                     "status" : "refund",
                     "usd_amount" : "1.53",
                     "vendor_amount" : "1.00"
                  },
                  "commission" : null,
                  "commission_affiliate_vendor_id" : null,
                  "commission_flat_rate" : null,
                  "commission_percentage" : null,
                  "commission_type" : null,
                  "commission_usd_amount" : null,
                  "customer_amount" : "1.00",
                  "flat_rate" : null,
                  "installment" : "1",
                  "invoice_id" : "4647892247",
                  "lc_affiliate_vendor_id" : null,
                  "lc_usd_amount" : null,
                  "lineitem_id" : "4672854532",
                  "linked_id" : "4647892301",
                  "options" : [],
                  "percentage" : null,
                  "product_description" : "test",
                  "product_duration" : "Forever",
                  "product_handling" : "0.00",
                  "product_id" : "4647888428",
                  "product_is_cart" : "0",
                  "product_name" : "test",
                  "product_price" : "1.00",
                  "product_recurrence" : "1 Month",
                  "product_startup_fee" : null,
                  "product_tangible" : "0",
                  "sale_id" : "4647892238",
                  "status" : "refund",
                  "type" : null,
                  "usd_amount" : "1.53",
                  "usd_commission" : null,
                  "vendor_amount" : "1.00",
                  "vendor_product_id" : "1178646973"
               }
            ],
            "recurring" : "1",
            "referrer" : "http://fake-company.com/buy.php",
            "sale_id" : "4647892238",
            "shipping" : null,
            "status" : "deposited",
            "usd_total" : "1.53",
            "vendor_id" : "532001",
            "vendor_order_id" : "1",
            "vendor_total" : "1.00"
         },
         {
            "customer_total" : "1.00",
            "date_placed" : "2012-03-29 02:32:58",
            "date_shipped" : null,
            "date_vendor_paid" : null,
            "fees_2co" : "0.54",
            "invoice_id" : "4671118593",
            "lineitems" : [
               {
                  "affiliate_vendor_id" : null,
                  "billing" : {
                     "amount" : "1.53",
                     "bill_method" : "paypal_int",
                     "billing_id" : "4671118602",
                     "customer_amount" : "1.00",
                     "customer_id" : "4647892244",
                     "date_deposited" : "2012-03-28",
                     "date_end" : "1999-01-01",
                     "date_fail" : "2012-04-05",
                     "date_next" : "2012-04-29",
                     "date_pending" : "2012-03-29",
                     "date_start" : "2012-03-31",
                     "lineitem_id" : "4671118599",
                     "recurring_status" : "stopped",
                     "status" : "bill",
                     "usd_amount" : "1.53",
                     "vendor_amount" : "1.00"
                  },
                  "commission" : null,
                  "commission_affiliate_vendor_id" : null,
                  "commission_flat_rate" : null,
                  "commission_percentage" : null,
                  "commission_type" : null,
                  "commission_usd_amount" : null,
                  "customer_amount" : "1.00",
                  "flat_rate" : null,
                  "installment" : "2",
                  "invoice_id" : "4671118593",
                  "lc_affiliate_vendor_id" : null,
                  "lc_usd_amount" : null,
                  "lineitem_id" : "4671118599",
                  "linked_id" : null,
                  "options" : [],
                  "percentage" : null,
                  "product_description" : "test",
                  "product_duration" : "Forever",
                  "product_handling" : "0.00",
                  "product_id" : "4647888428",
                  "product_is_cart" : "0",
                  "product_name" : "test",
                  "product_price" : "1.00",
                  "product_recurrence" : "1 Month",
                  "product_startup_fee" : null,
                  "product_tangible" : "0",
                  "sale_id" : "4647892238",
                  "status" : "bill",
                  "type" : null,
                  "usd_amount" : "1.53",
                  "usd_commission" : null,
                  "vendor_amount" : "1.00",
                  "vendor_product_id" : "1178646973"
               },
               {
                  "affiliate_vendor_id" : null,
                  "billing" : {
                     "amount" : "1.53",
                     "bill_method" : "paypal_int",
                     "billing_id" : "4672854541",
                     "customer_amount" : "1.00",
                     "customer_id" : "4647892244",
                     "date_deposited" : "2012-03-31",
                     "date_end" : null,
                     "date_fail" : "2012-04-05",
                     "date_next" : null,
                     "date_pending" : "2012-03-31",
                     "date_start" : "2012-03-31",
                     "lineitem_id" : "4672854538",
                     "recurring_status" : null,
                     "status" : "refund",
                     "usd_amount" : "1.53",
                     "vendor_amount" : "1.00"
                  },
                  "commission" : null,
                  "commission_affiliate_vendor_id" : null,
                  "commission_flat_rate" : null,
                  "commission_percentage" : null,
                  "commission_type" : null,
                  "commission_usd_amount" : null,
                  "customer_amount" : "1.00",
                  "flat_rate" : null,
                  "installment" : "2",
                  "invoice_id" : "4671118593",
                  "lc_affiliate_vendor_id" : null,
                  "lc_usd_amount" : null,
                  "lineitem_id" : "4672854538",
                  "linked_id" : "4671118599",
                  "options" : [],
                  "percentage" : null,
                  "product_description" : "test",
                  "product_duration" : "Forever",
                  "product_handling" : "0.00",
                  "product_id" : "4647888428",
                  "product_is_cart" : "0",
                  "product_name" : "test",
                  "product_price" : "1.00",
                  "product_recurrence" : "1 Month",
                  "product_startup_fee" : null,
                  "product_tangible" : "0",
                  "sale_id" : "4647892238",
                  "status" : "refund",
                  "type" : null,
                  "usd_amount" : "1.53",
                  "usd_commission" : null,
                  "vendor_amount" : "1.00",
                  "vendor_product_id" : "1178646973"
               }
            ],
            "recurring" : "1",
            "referrer" : "http://www.fake-company.com/buy.php",
            "sale_id" : "4647892238",
            "shipping" : null,
            "status" : "deposited",
            "usd_total" : "1.53",
            "vendor_id" : "532001",
            "vendor_order_id" : "1",
            "vendor_total" : "1.00"
         }
      ],
      "ip_address" : "66.194.132.135",
      "ip_country" : "United States",
      "recurring_decline" : null,
      "sale_id" : "4647892238"
   }
}

 

Common Error Codes

Code Description
PARAMETER_MISSING Required parameter missing:
PARAMETER_INVALID Invalid value for parameter:
RECORD_NOT_FOUND Unable to find record.
FORBIDDEN Access denied to sale.

Admin API

Overview

(Formally known as Back Office API)

2Checkout’s Admin API provides a way to automate both account and order management processes. Using the Admin API along with the Instant Notification Service alleviates the necessity of logging into the standard GUI account interface on a day-to-day basis.

The Admin API system works by first having the user create an API username in their 2Checkout account which has the appropriate permissions to access the Admin API. This API username can be used to authenticate the supported methods described below to call our Admin API by HTTP POST or GET to update or return sale information. To create a username, please log in to your account, click on the Account tab and User Management sub-tab. From here, please click the Create Username link and create a new username with API Access and API Updating selected for the Access type. Our Admin API can then be accessed with this new username and password you created.

api user

The Admin API will return XML by default unless the Accept: header is passed in the call to define the content type. The Admin API is capable of returning data in the following formats:

  • XML (application/xml) - default
  • JSON (application/json)
  • HTML XOXO microformat (text/html)

Simple bindings for each method are provided through our community supported libraries.

You can also call each method without using our libraries. Below is an example script that makes a detail_sale call.

var tco = new Twocheckout({
    apiUser: "APIuser1817037,
    apiPass: "APIpass1817037
});

args = {
    lineitem_id: "4774380224"
};

tco.sales.stop(args, function (error, data) {
    if (error) {
        console.log(error);
    } else {
        console.log(data.response_code);
    }
});

Errors

If a request cannot be completed successfully, the response from the Admin API will contain information that can be used to determine what went wrong. There are several ways to determine that the request was unsuccessful. Either the HTTP Status header will contain a status code of 400 or higher (typically 400, 404, or 500). Or There will be one or more errors elements in the response. Each of these elements will contain an error code, message, and (if applicable) other informative values to assist in debugging the problem such as the offending parameter name.

Example response:

{
      "code" : "PARAMETER_MISSING",
      "message" : "Required parameter missing: vendor_id",
      "parameter" : "vendor_id"
    }

 

2Checkout Payment API Node.js Tutorial

Overview

In this tutorial, we will walk through integrating the 2Checkout Payment API to securely tokenize and charge a credit card using the 2Checkout Node Library.

Application Setup

For our example application, we will be using node v0.10.26 and the express framework (4.x). You can install the dependencies below.

npm install express body-parser http

We will also need to install the twocheckout library which provides us with a simple binding to the API, INS, and Checkout process so that we can integrate each feature with only a few lines of code. In this example, we will only be using the Payment API functionality of the library.

git clone https://github.com/2Checkout/2checkout-node.git
npm install 2checkout-node

To start off, let's set up the file structure for our example application.

└── payment-api
    ├── app.js
    └── public
        └── index.html

Here we created a new directory for our application named 'payment-api' with a new file 'app.js' for our node script. We also created a sub-directory 'public' with an 'index.html' file to display our credit card form.

Create a Token

Open the 'index.html' file under the public directory and create a basic HTML skeleton.

<!DOCTYPE html>
<html>
    <head>
        <title>Node Example</title>
    </head>
    <body>

    </body>
</html>

Next add a basic credit card form that allows our buyers to enter in their card number, expiration month and year, and CVC.

<form id="myCCForm" action="/order" method="post">
    <input id="token" name="token" type="hidden" value="">
    <div>
        <label>
            <span>Card Number</span>
        </label>
        <input id="ccNo" type="text" size="20" value="" autocomplete="off" required />
    </div>
    <div>
        <label>
            <span>Expiration Date (MM/YYYY)</span>
        </label>
        <input type="text" size="2" id="expMonth" required />
        <span> / </span>
        <input type="text" size="2" id="expYear" required />
    </div>
    <div>
        <label>
            <span>CVC</span>
        </label>
        <input id="cvv" size="4" type="text" value="" autocomplete="off" required />
    </div>
    <input type="submit" value="Submit Payment">
</form>

Notice that we have a no 'name' attributes on the input elements that collect the credit card information. This will ensure that no sensitive card data touches your server when the form is submitted. Also, we include a hidden input element for the token which we will submit to our server to make the authorization request.

Now we can add our JavaScript to make the token request call. Replace 'seller-id' and 'publishable-key' with your credentials.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://www.2checkout.com/checkout/api/2co.min.js"></script>

<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) {
        if (data.errorCode === 200) {tokenRequest();} else {alert(data.errorMsg);}
    };

    var tokenRequest = function() {
        // Setup token request arguments
        var args = {
            sellerId: "seller-id",
            publishableKey: "private-key",
            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();

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

            // Prevent form from submitting
            return false;
        });
    });
</script>

Let's take a second to look at what we did here. First, we pulled in a jQuery library to help us with manipulating the document. (The 2co.js library does NOT require jQuery.)

Next, we pulled in the 2co.js library so that we can make our token request with the card details.

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

This library provides us 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. In this example, we are going to call this as soon as the document is ready so it is not necessary to provide a callback.

TCO.loadPubKey();

The 'TCO.requestToken(Function callback, Function callback, Object arguments)' function is used 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.
    • 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
TCO.requestToken(successCallback, errorCallback, args);

In our example, we created 'tokenRequest' function to set up our arguments by pulling the values entered on the credit card form and we make the token request.

var tokenRequest = function() {
    // Setup token request arguments
    var args = {
        sellerId: "seller-id",
        publishableKey: "publishable-key",
        ccNo: $("#ccNo").val(),
        cvv: $("#cvv").val(),
        expMonth: $("#expMonth").val(),
        expYear: $("#expYear").val()
    };

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

We then call this function from a submit handler function that we set up on the form.

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

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

The 'successCallback' function is called if the token request is successful. In this function, we set the token as the value for our 'token' hidden input element and we submit the form to our server.

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();
};

The 'errorCallback' function is called if the token request fails. In our example function, we check for error code 200, which indicates that the ajax call has failed. If the error code was 200, we automatically re-attempt the tokenization, otherwise, we alert with the error message.

var errorCallback = function(data) {
    if (data.errorCode === 200) {tokenRequest();} else {alert(data.errorMsg);}
};

Create the Sale

Open 'app.js' and add require the modules we need.

var Twocheckout = require('2checkout-node');
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');

Next, let's create our new express instance, define routes for '/' and '/order' and instruct our application to start on port 3000.

var app = express();
app.use(express.static(__dirname + '/public'));
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.urlencoded());


app.get('/', function(request, response) {

});


app.post('/order', function(request, response) {

});

http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

In the '/' route, we will render our 'index.html' and display it to the buyer.

app.get('/', function(request, response) {response.render('index')});

In the order route, we will use the token passed from our credit card form to submit the authorization request and display the response. Replace 'seller-id' and 'private-key' with your credentials.

app.post('/order', function(request, response) {
    var tco = new Twocheckout({
        sellerId: "seller-id",                                  // Seller ID, required for all non Admin API bindings
        privateKey: "private-key"                              // Payment API private key, required for checkout.authorize binding
    });

    var params = {
        "merchantOrderId": "123",
        "token": request.body.token,
        "currency": "USD",
        "total": "10.00",
        "billingAddr": {
            "name": "Testing Tester",
            "addrLine1": "123 Test St",
            "city": "Columbus",
            "state": "Ohio",
            "zipCode": "43123",
            "country": "USA",
            "email": "example@2co.com",
            "phoneNumber": "5555555555"
        }
    };

    tco.checkout.authorize(params, function (error, data) {
        if (error) {response.send(error.message);} else {response.send(data.response.responseMsg);}
    });
});

Let's break down this method a bit and explain what we're doing here.

First, we set up our credentials and the environment by creating a new 'Twocheckout({})' instance. This function accepts an object as the argument containing the following attributes.

  • privateKey: Your Payment API private key
  • sellerId: 2Checkout account number

Next, we create an object with our authorization attributes. In our example, we are using hard-coded strings for each required attribute except for the token which is passed in from the credit card form.

Important Note: A token can only be used for one authorization call, and will expire after 30 minutes if not used.

var params = {
    "merchantOrderId": "123",
    "token": request.body.token,
    "currency": "USD",
    "total": "10.00",
    "billingAddr": {
        "name": "Testing Tester",
        "addrLine1": "123 Test St",
        "city": "Columbus",
        "state": "Ohio",
        "zipCode": "43123",
        "country": "USA",
        "email": "example@2co.com",
        "phoneNumber": "5555555555"
    }
};

Finally, we submit the charge using the 'tco.checkout.authorize(object, function (error, data)' function and display the result to the buyer. It is important that your callback function accepts 2 arguments to ensure that you handle both the 'failure' and 'success' scenarios.

tco.checkout.authorize(params, function (error, data) {
    if (error) {response.send(error.message);} else {response.send(data.response.responseMsg);}
});

Run the example application

In your console, navigate to the 'payment-api' directory and start up the application

node app.js

In your browser, navigate to 'http://localhost:3000', and you should see a payment form where you can enter credit card information.

For your testing, you can use these values for a successful authorization:

  • Credit Card Number: 4000000000000002
  • Expiration date: 10/2020
  • cvv: 123

And these values for a failed authorization:

  • Credit Card Number: 4333433343334333
  • Expiration date: 10/2020
  • cvv:123

The complete example application for this tutorial can be accessed on our public Github repository.

PayPal Direct

Overview

To process PayPal payments, we provide API users with our PayPal Direct checkout flow which can be accessed by simply adding an additional parameter paypal_direct with a value of “Y” to a standard Standard Checkout payment form or link. As long as all of the required parameters are passed, the user will be redirected directly to PayPal to complete their payment.

Example PayPal Direct Form

<form action="https://www.2checkout.com/checkout/purchase" method="post">
  <input name="sid" type="hidden" value="1817037">
  <input name="mode" type="hidden" value="2CO">
  <input name="return_url" type="hidden" value="https://www.example.com/cart/">
  <input name="li_0_name" type="hidden" value="invoice123">
  <input name="li_0_price" type="hidden" value="25.99">
  <input name="card_holder_name" type="hidden" value="Checkout Shopper">
  <input name="street_address" type="hidden" value="123 Test Address">
  <input name="street_address2" type="hidden" value="Suite 200">
  <input name="city" type="hidden" value="Columbus">
  <input name="state" type="hidden" value="OH">
  <input name="zip" type="hidden" value="43228">
  <input name="country" type="hidden" value="USA">
  <input name="email" type="hidden" value="example@2co.com">
  <input name="phone" type="hidden" value="614-921-2450">
  <input name="ship_name" type="hidden" value="Gift Receiver">
  <input name="ship_street_address" type="hidden" value="1234 Address Road">
  <input name="ship_street_address2" type="hidden" value="Apartment 123">
  <input name="ship_city" type="hidden" value="Columbus">
  <input name="ship_state" type="hidden" value="OH">
  <input name="ship_zip" type="hidden" value="43235">
  <input name="ship_country" type="hidden" value="USA">
  <input name="paypal_direct" type="hidden" value="Y">
  <input type="submit" value="Submit Payment">
</form>

If you use this example on your webpage, you need to change “1817037” to your 2Checkout Seller ID and “https://www.example.com/cart/” to your return URL (URL for unsuccessful purchase).

Note: PayPal direct cannot be used with demo sales, either from passing in a demo parameter or setting your account to demo mode.

Return Process

If the sale is successful, the buyer will be returned to your approved URL through the return method that you have defined in your 2Checkout account like any normal 2Checkout sale.

If the user cancels the PayPal payment or the payment fails, they will be brought back to the URL that you define using the `return_url` parameter with the `paypal_direct` parameter appended to the query string indicating whether the payment failed for was canceled. This way you can handle your response to the user appropriately.

Example PayPal Direct failure URL

https://www.example.com/cart?paypal_direct=fail

Example PayPal Direct cancel URL

https://www.example.com/cart?paypal_direct=cancel

Note: PayPal Direct is only available 2Checkout accounts that are using the Payment API.

Create a sale

Overview

Once you have passed the token to your server, you can use it along with your private key to charge the credit card and create a new sale using the authorization API call. The authorization will capture and deposit automatically within 48 hours of being placed.

Each of our community-supported libraries provides a method to perform authorization and create a new sale.

Attributes

The authorization API call must be passed a JSON string with the customer's billing information, an order identifier through the `merchantOrderId` parameter, your seller ID, private key, and either lineItem(s) data or just a sale total on all requests. The API will always return a JSON response body that includes a `response` sub-object on successful authorizations and an `exception` sub-object on failed authorizations that provide the result and transaction details.

API URL: https://www.2checkout.com/checkout/api/1/(seller_id)/rs/authService

Replace (seller_id) with your 2Checkout seller ID.

Content-Type: application/json

Returns: JSON response

HTTP Method: POST

Authorization Request Object

Base Attributes

Attribute Description
sellerId Your 2Checkout account number. Required
privateKey Your 2Checkout Private Key.  Required
merchantOrderId Your custom order identifier. Required.
token The credit card token. Required.
currency AFN, ALL, DZD, ARS, AUD, AZN, BSD, BDT, BBD, BZD, BMD, BOB, BWP, BRL, GBP, BND, BGN, CAD, CLP, CNY, COP, CRC, n n requCZK, DKK, DOP, XCD, EGP, EUR, FJD, GTQ, HKD, HNL, HUF, INR, IDR, ILS, JMD, JPY, KZT, KES, LAK, MMK, LBP, LRD, MOP, MYR, MVR, MRO, MUR, MXN, MAD, NPR, TWD, NZD, NIO, NOK, PKR, PGK, PEN, PHP, PLN, QAR, RON, RUB, WST, SAR, SCR, SGD, SBD, ZAR, KRW, LKR, SEK, CHF, SYP, THB, TOP, TTD, TRY, UAH, AED, USD, VUV, VND, XOF, YER. Use to specify the currency for the sale. Required.
total The Sale Total. Format: 0.00-99999999.99, defaults to 0 if a value isn’t passed in or if value is incorrectly formatted, no negatives (Only Use if you are not passing in lineItems.)
demo Test Order. Pass value as true to place a test order. Optional.

Lineitem Attributes

Attribute Description
lineItems Array of lineitem objects using the attributes specified below.

Will be returned in the order that they are passed in.

(Passed as a sub object to the Authorization Object.)

(Only Use if you are not passing in total.)
type The type of line item that is being passed in. (Always Lower Case, ‘product’, ‘shipping’, ‘tax’ or ‘coupon’, defaults to ‘product’) Required
name Name of the item passed in. (128 characters max, cannot use ‘<' or '>’, defaults to capitalized version of ‘type’.) Required
quantity Quantity of the item passed in. (0-999, defaults to 1 if not passed in or incorrectly formatted.) Optional
price Price of the line item. Format: 0.00-99999999.99, defaults to 0 if a value isn’t passed in or if value is incorrectly formatted, no negatives (use positive values for coupons). Required
tangible Y or N. Will default to Y if the type is shipping. Optional
productId Your custom product identifier. Optional
recurrence Sets billing frequency. Ex. ‘1 Week’ to bill order once a week. (Can use # Week, # Month or # Year) Required for recurring lineitems.
duration Sets how long to continue billing. Ex. ‘1 Year’. (Forever or # Week, # Month, # Year) Required for recurring lineitems.
startupFee Any start up fees for the product or service. Can be negative to provide discounted first installment pricing, but cannot equal or surpass the product price. Optional

Lineitem Option Attributes

Attribute Description
options Array of option objects using the attributes specified below. Optional

Will be returned in the order that they are passed in.

(Passed as a sub object of a lineItem object.)
optName Name of product option. Ex. Size (64 characters max – cannot include ‘<' or '>’) Required
optValue Option selected. Ex. Small (64 characters max, cannot include ‘<' or '>’) Required
optSurcharge Option price in seller currency. (0.00 for no cost options) Required

Billing Address Attributes

Attribute Description
billingAddr Object that defines the billing address using the attributes specified below. Required

(Passed as a sub object to the Authorization Object.)
name Card holder’s name. (128 characters max) Required
addrLine1 Card holder’s street address. (64 characters max) Required
addrLine2 Card holder’s street address line 2. (64 characters max) Required if “country” value is: CHN, JPN, RUS - Optional for all other “country” values.
city Card holder’s city. (64 characters max) Required
state Card holder’s state. (64 characters max) Required if “country” value is ARG, AUS, BGR, CAN, CHN, CYP, EGY, FRA, IND, IDN, ITA, JPN, MYS, MEX, NLD, PAN, PHL, POL, ROU, RUS, SRB, SGP, ZAF, ESP, SWE, THA, TUR, GBR, USA - Optional for all other “country” values.
zipCode Card holder’s zip. (16 characters max) Required if “country” value is ARG, AUS, BGR, CAN, CHN, CYP, EGY, FRA, IND, IDN, ITA, JPN, MYS, MEX, NLD, PAN, PHL, POL, ROU, RUS, SRB, SGP, ZAF, ESP, SWE, THA, TUR, GBR, USA - Optional for all other “country” values.
country Card holder’s country. (64 characters max) Required
email Card holder’s email. (64 characters max) Required
phoneNumber Card holder’s phone. (16 characters max) Required
phoneExt Card holder’s phone extension. (9 characters max) Optional

Shipping Address Attributes

Attribute Description
shippingAddr Object that defines the shipping address using the attributes specified below. Optional

Only required if a shipping lineitem is passed.

(Passed as a sub object to the Authorization Object.)
name Card holder’s name. (128 characters max) Required
addrLine1 Card holder’s street address. (64 characters max) Required
addrLine2 Card holder’s street address line 2. (64 characters max) Required if “country” value is: CHN, JPN, RUS - Optional for all other “country” values.
city Card holder’s city. (64 characters max) Required
state Card holder’s state. (64 characters max) Required if “country” value is ARG, AUS, BGR, CAN, CHN, CYP, EGY, FRA, IND, IDN, ITA, JPN, MYS, MEX, NLD, PAN, PHL, POL, ROU, RUS, SRB, SGP, ZAF, ESP, SWE, THA, TUR, GBR, USA - Optional for all other “country” values.
zipCode Card holder’s zip. (16 characters max) Required if “country” value is ARG, AUS, BGR, CAN, CHN, CYP, EGY, FRA, IND, IDN, ITA, JPN, MYS, MEX, NLD, PAN, PHL, POL, ROU, RUS, SRB, SGP, ZAF, ESP, SWE, THA, TUR, GBR, USA - Optional for all other “country” values.
country Card holder’s country. (64 characters max) Optional

Example Authorization Request

var tco = new Twocheckout({
    sellerId: "901248156",
    privateKey: "3508079E-5383-44D4-BF69-DC619C0D9811"
});

var params = {
    "merchantOrderId": "123",
    "token": "MWQyYTI0ZmUtNjhiOS00NTIxLTgwY2MtODc3MWRlNmZjY2Jh",
    "currency": "USD",
    "total": "10.00",
    "billingAddr": {
        "name": "Testing Tester",
        "addrLine1": "123 Test St",
        "city": "Columbus",
        "state": "Ohio",
        "zipCode": "43123",
        "country": "USA",
        "email": "example@2co.com",
        "phoneNumber": "5555555555"
    }
};

tco.checkout.authorize(params, function (error, data) {
    if (error) {
        console.log(error.message);
    } else {
        console.log(JSON.stringify(data));
    }
});

Authorization Response Object

The ‘response’ sub object is returned on successful authorizations to provide the result and transaction details.

Base Attributes

Attribute Description
type Response Object Type “AuthResponse”
merchantOrderId Your custom order identifier registered to the sale.
orderNumber 2Checkout Order Number
transactionId 2Checkout Invoice ID
responseMsg Message indicating the result of the authorization attempt.
responseCode Code indicating the result of the authorization attempt.
total The Sale Total. Format: 0.00-99999999.99.
currencyCode The sale currency code.

Lineitem Attributes

Attribute Description
lineitems Array of lineitem objects associated with the sale returned in the order that they are passed in.

(Returned as a sub object to the Response Object.)
type The type of line item that is being passed in.
name Name of the item passed in.
quantity Quantity of the item passed in.
price Price of the line item.
productId Your custom product identifier.
tangible Y or N.
recurrence Sets billing frequency.
duration Sets how long to continue billing.
startupFee Any start up fees for the product or service.

Lineitem Option Attributes

Attribute Description
options Array of option objects returned in the order that they are passed in.

(Returned as a sub object of a lineItem object.)
optName Name of product option.
optValue Option selected.
optSurcharge Option price in seller currency.

Billing Address Attributes

Attribute Description
billingAddr Object that defines the billing address.

(Returned as a sub object to the Response Object.)
name Card holder’s name.
addrLine1 Card holder’s street address.
addrLine2 Card holder’s street address line 2.
city Card holder’s city.
state Card holder’s state.
zipCode Card holder’s zip.
country Card holder’s country.
email Card holder’s email.
phone Card holder’s phone.
phoneExt Card holder’s phone extension.

Shipping Address Attributes

Attribute Description
shippingAddr Object that defines the shipping address.

(Returned as a sub object to the Response Object.)
name Recipient name.
addrLine1 Recipient’s street address.
addrLine2 Recipient’s street address line 2.
city Recipient’s city.
state Recipient’s state.
zipCode Recipient’s zip.
country Recipient’s country.

Example Response JSON Object

{
    "validationErrors": null,
    "exception": null,
    "response": {
        "type": "AuthResponse",
        "lineItems": [
            {
                "options": [],
                "price": "6.99",
                "quantity": "2",
                "recurrence": "1 Month",
                "startupFee": null,
                "productId": "123",
                "tangible": "N",
                "name": "Demo Item 1",
                "type": "product",
                "description": "",
                "duration": "1 Year"
            },
            {
                "options": [
                    {
                        "optName": "Size",
                        "optValue": "Large",
                        "optSurcharge": "1.00"
                    }
                ],
                "price": "1.99",
                "quantity": "1",
                "recurrence": null,
                "startupFee": null,
                "productId": "",
                "tangible": "N",
                "name": "Demo Item 2",
                "type": "product",
                "description": "",
                "duration": null
            },
            {
                "options": [],
                "price": "3.00",
                "quantity": "1",
                "recurrence": null,
                "startupFee": null,
                "productId": "",
                "tangible": "Y",
                "name": "Shipping Fee",
                "type": "shipping",
                "description": "",
                "duration": null
            }
        ],
        "transactionId": "205182114564",
        "billingAddr": {
            "addrLine1": "123 Test St",
            "addrLine2": null,
            "city": "Columbus",
            "zipCode": "43123",
            "phoneNumber": "5555555555",
            "phoneExtension": null,
            "email": "example@2co.com",
            "name": "Testing Tester",
            "state": "Ohio",
            "country": "USA"
        },
        "shippingAddr": {
            "addrLine1": "123 Test St",
            "addrLine2": "",
            "city": "Columbus",
            "zipCode": "43123",
            "phoneNumber": null,
            "phoneExtension": null,
            "email": null,
            "name": "Testing Tester",
            "state": "OH",
            "country": "USA"
        },
        "merchantOrderId": "123",
        "orderNumber": "205182114555",
        "recurrentInstallmentId": null,
        "responseMsg": "Successfully authorized the provided credit card",
        "responseCode": "APPROVED",
        "total": "19.97",
        "currencyCode": "USD",
        "errors": null
    }
}

Errors

If an error occurs when attempting to authorize the sale, such as a processing error or an error in the JSON request, the errorCode and errorMsg will be returned in the exception sub object in the response body.

Base Attributes

Error Code Error Message Cause
300 Unauthorized Seller unauthorized to use the API or incorrect private key.

Invalid Token
200 Unable to process the request Incorrect attributes or malformed JSON object.
400 Bad request - parameter error Missing required attributes or invalid token.
600 Authorization Failed Credit Card failed to authorize.
601 Payment Authorization Failed:  Please update your cards expiration date and try again, or try another payment method. Invalid Expiration Date.
602 Payment Authorization Failed:  Please verify your Credit Card details are entered correctly and try again, or try another payment method. Credit Card failed to authorize.
603 Your credit card has been declined because of the currency you are attempting to pay in.  Please change the currency of the transaction or use a different card and try again. Invalid Currency for card type.
604 Payment Authorization Failed: Credit is not enabled on this type of card, please contact your bank for more information or try another payment method. Credit Card failed to authorize.
605 Payment Authorization Failed: Invalid transaction type for this credit card, please use a different card and try submitting the payment again, or contact your bank for more information. Invalid transaction type for credit card.
606 Payment Authorization Failed: Please use a different credit card or payment method and try again, or contact your bank for more information. Credit Card failed to authorize.
607 Payment Authorization Failed: Please verify your information and try again, or try another payment method. Credit Card failed to authorize.

Example Exception JSON Object

{
    "validationErrors": null,
    "exception": {
        "errorMsg": "Payment Authorization Failed:  Please verify your Credit Card details are entered correctly and try again, or try another payment method.",
        "httpStatus": "400",
        "exception": false,
        "errorCode": "602"
    },
    "response": null
}

 

Create token

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.

Payment API

Overview

With 2Checkout’s Payment API, buyers can place sales directly on your website, with no redirection to our checkout. You can take credit card information with a simple HTML form, and use our 2co.js JavaScript library to convert the credit card information into a secure token. The token can then be safely passed to your server so that you can submit the transaction using our API.

payment api

   To ensure that no sensitive data touches your server, your input elements for the credit card, expiration date, and CVV must NOT contain name attributes.

Create a Token

You can use our JavaScript library to pass the buyer’s credit card information to us in the browser and generate a secure token so that no sensitive card information touches your server. You will just need to provide a payment form for the buyer to enter their card information.

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

TCO.loadPubKey('production', function() {
    TCO.requestToken(successCallback, errorCallback, args);
});​

You will then be able to use the token to create a sale, and charge your buyer. This token is only good for one sale and expires if not used within 30 minutes. For further information on creating a token, please review our Create Token documentation.

Create the Sale

Once the token has been created, you can use it to charge the customer through our server-side authorization API call.

var tco = new Twocheckout({
    sellerId: "901248156",
    privateKey: "3508079E-5383-44D4-BF69-DC619C0D9811"
});

var params = {
    "merchantOrderId": "123",
    "token": "MWQyYTI0ZmUtNjhiOS00NTIxLTgwY2MtODc3MWRlNmZjY2Jh",
    "currency": "USD",
    "total": "10.00",
    "billingAddr": {
        "name": "Testing Tester",
        "addrLine1": "123 Test St",
        "city": "Columbus",
        "state": "Ohio",
        "zipCode": "43123",
        "country": "USA",
        "email": "example@2co.com",
        "phoneNumber": "5555555555"
    }
};

tco.checkout.authorize(params, function (error, data) {
    if (error) {
        console.log(error.message);
    } else {
        console.log(JSON.stringify(data));
    }
});

Each of our community-supported libraries provides a method to perform authorization and create a new sale.

Get PCI Compliant

Important Note: The page containing your credit card form must be served over HTTPS. Although we encrypt the card data in the browser before sending a token request, you must also utilize SSL to protect yourself from man-in-the-middle attacks. Serving your checkout page over HTTPS will also instill confidence in the buyer and help to increase your conversion rate.

payment api 2

2Checkout has the right to request your PCI compliance validation documentation at any time. Your failure to provide us with this documentation may result in immediate termination of the API or Virtual Terminal access.

Legacy 2Checkout API

Overview

This section includes documentation for the old 2Checkout API.

Getting started

Integrating with 2Checkout is easy. We provide several methods of integration to best fit your needs and support 7 different server-side languages. Follow the steps below to begin your integration.

Learn how to integrate

Use our documentation to learn how you can integrate your site with our service. Test our INS (Instant Notification System), the Admin API, Shopping Cart Integration, and any one of our checkout experience offerings. Select from one of the programming languages listed below to view all specific documentation.

Data protection for custom links

Overview

2Checkout offers you the option to create custom renewal or upgrade links, that you can provide your customers with the relevant communication channel of your choice. This is an alternative to, for example, the automatically-generated renewal links that our platform sends as part of renewal reminders to your shoppers or makes available through the customer myAccount. 

If the path you choose is the one where you, as a merchant, create these links and share them with your customers, extra attention needs to be paid to make sure you distribute the links to the rightful owners of those respective subscriptions. Not only the money they spend is at stake, but also exposing personal information (which falls under strictly regulated areas both inside the EU, as well as the US). 

2Checkout has the obligation to make sure data is protected, therefore whenever the custom link path is chosen by you, shoppers will have to pass an extra validation step in the checkout process in order to confirm they are indeed the owners of the subscription they are attempting to renew/upgrade.  

Availability

This setting is available to all standard 2Checkout account types: 2Sell, 2Subscribe, and 2Monetize, for both PSP and MoR accounts created post-December 10, 2021. We will gradually enable it for all accounts created before this date.  

Benefits

2Checkout is adding an additional safety measure to make sure custom links reach the rightful owners of subscriptions without the need for you to build any additional logic on your side.

Workflow 

The same flow described below applies regardless of the shopping cart you are using, the theme, or the flow you have chosen. 

When shoppers click on a custom renewal/upgrade link you have previously sent, they will be reaching an intermediary page where they are asked to fill in their delivery email address associated with that subscription. 

Hosted Interface Default Layout

subscription renewal gdpr 8

ConvertPlus Default Theme Layout

subscription renewal gdpr 1

InLine Cart Layout

subscription renewal gdpr 2

If there is a match between the delivery email address the shopper fills in and the one stored in the 2Checkout system on the original subscription, the shopper immediately reaches the shopping cart and continues the usual renewal/upgrade flow.

The shopper has three attempts to pass this validation step. If by the third attempt, the shopper fails to enter a matching delivery email address associated with their subscription, 2Checkout will display a warning message shown in the image below.

Hosted Interface Default Layout

subscription renewal gdpr 7

ConvertPlus Default Theme Layout

subscription renewal gdpr 3

InLine Cart Layout

subscription renewal gdpr 4

The email also includes either a renewal or an upgrade link that is digitally signed by 2Checkout. This means that if the customer remembers the original email address and has access to that mailbox, they will be able to click on the relevant link once they open the email received from 2Checkout.

subscription renewal gdpr 5

To address those valid scenarios where the original email address is not available anymore (e.g., it belongs to a fellow employee that left the company), the message prompted on the intermediary screen also suggests, as an alternative, reaching out to you. At that point, you will be able to identify the customer, and, if relevant, you can modify the delivery information belonging to that subscription. It will be an informed decision on your side that will also help you store the most up-to-date and relevant information on the owners of your subscriptions.

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