Skip to main content

Workflow

  1. Use the following URL: https://api.2checkout.com/rpc/6.0
  2. Authenticate using the login method and create a session (connection).
  3. Throughout the lifetime of the session (max 10 minutes), you can invoke all 2Checkout API methods. To invoke methods you need to send a request to 2Checkout. Read more on the request object below.
  4. The 2Checkout system provides responses to all requests. Read more on the response object below.

Response

Whenever you call an API method, 2Checkout replies with a response. The response is a single object serialized using JSON.

There are two types of response, with the properties detailed below.

Valid response

{
"id" : <int identifier>,
"jsonrpc" : 6.0,
"response" : {<return object>}
}
Valid response object
Properties Type/Description
jsonrpc Required (string)
  JSON-RPC protocol version. Must be 6.0.
id Required (int)
  Mandatory identifier that you control, used to identify the request and the response. Use only integer values.
response Required (object)
  Provided on success (is not included if there was an error invoking the method). Actual value depends on the method invoked.

Invalid response

{
"id" : <int identifier>,
"jsonrpc" : 6.0,
"error" : { "code" : <int error code>, "message" : "<error message>"}
}
Invalid response object
Properties Type/Description
jsonrpc Required (string)
  JSON-RPC protocol version. Must be 6.0.
id Required (int)
  Mandatory identifier that you control, used to identify the request and the response. Use only integer values.
error Required (object)
 

Code - Integer identifying the error.

Message - Error description (string).

Request

Calling API methods involves sending an API request to Avangate. The request object is detailed below. 

{ 
"jsonrpc" : 6.0, 
"id" : <int identifier>, 
"method" : "<methodName>", 
"params" : [<parameters array>] 
}
Request object
Properties Type/Description
jsonrpc Required (string)
  JSON-RPC protocol version. Must be 6.0.
id Required (int)
  Mandatory identifier that you control, used to identify the request and the response. Use only integer values.
method Required (string)
  The name of the method invoked. Case sensitive.
params Optional (object)
 

An object/structure containing the parameters valid for invoking the method used.

 

Parameters structure:

 

Parameters included into the RPC call need to be provided by-position using an Array. (structured value)

 

by-position: include all parameters into an Array. The values must be in order expected by Avangate.

 

At this point we don't support by-name parameters.

 

Authentication

Overview

Use the login method for the authentication process in the 2Checkout system.

Parameters

Parameters Type/Description
merchantCode required (string)
  Your merchant identification code.
date required (string)
  GMT ISO Date format (e.g. 2010-01-01 12:13:14)
hash required (string)
  Calculated HMAC_SHA256 signature based on merchantCode and date, using your secret key.

Request

To create the HMAC_SHA256 source string use your merchant code and the date of the request, prefixing them with the length in bytes of each respective value, along with your account’s secret key (for UTF-8 characters the length in bytes might be longer than the string length). For example:

Parameters Type/Description
MerchantCode Your merchant account code.
 

8AVANGATE

 

Date 2010-05-13 12:12:12
 

192010-05-13 12:12:12

 

HMAC source string

8AVANGATE192010-05-13 12:12:12

 

Secret key SECRET_KEY
Calculated HMAC_SHA256 signature based on MerchantCode and Date, using your secret key:
bf763db7d333e9c3038698cf59ada3e6
<?php

$host   = "https://api.2checkout.com";

$merchantCode = "YOURCODE123";
//your account's merchant code available in the 'System settings' area of the cPanel:
//https://secure.2checkout.com/cpanel/account_settings.php

$key          = "SECRET_KEY";
//your account's secret key available in the 'System settings' area of the cPanel:
//https://secure.2checkout.com/cpanel/account_settings.php

$now          = gmdate('Y-m-d H:i:s'); //GMT date format)
$algo = "sha256";
$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash = hash_hmac($algo, $string, $key);

try {
    $client = new SoapClient($host . "/soap/6.0/?wsdl", array(
        'location' => $host . "/soap/6.0/",
        "stream_context" => stream_context_create(array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false
            )
        ))
    ));
    $sessionID = $client->login($merchantCode, $now, $hash, $algo);
    echo("Auth token: {$sessionID}" . PHP_EOL);
}
catch (SoapFault $e) {
    echo "Authentication: " . $e->getMessage() . PHP_EOL;
    exit;
} 

Response

Parameter Type/Description
sessionID string
  Session identifier, the output of the Login method. Include sessionID into all your requests. 2Checkout throws an exception if the values are incorrect.
The sessionID expires in 10 minutes.

Preload InLine Cart to increase loading speed

Overview

To reduce checkout load time, you can preload the InLine Checkout in the background on page load or when the customer selects a product.

Use case

  1. Add an HTML link or button to your page like the one below.
  2. Create a JavaScript click handler to execute the InLine Client desired methods.
  3. Use the TwoCoInlineCart.products.add({code, quantity, options}) method to prepare your products.
  4. Use the TwoCoInlineCart.cart.preload() method to load the cart in the background.
  5. Use the TwoCoInlineCart.cart.reloadCart() method to show the cart on your page.

Sample request

HTML

<a href="#" class="btn btn-success" id="buy-button">Buy now!</a>

Javascript


window.addEventListener("load", (event) => {
  TwoCoInlineCart.products.add({
    code: "2CO3MONTHS",
    qty: 1
  });
  TwoCoInlineCart.cart.preload();
});
window.document.getElementById('buy-button').addEventListener('click', function() {
  TwoCoInlineCart.cart.reloadCart();
});

Demo (Using Test Mode)

Place manual renewal order in InLine Cart

Overview

Place a manual renewal order using the inline checkout.

Use case

  1. Add an HTML link or button in your page like the one below.
  2. Create a JavaScript click handler to execute the Inline Client desired methods.
  3. Use the TwoCoInlineCart.products.add({code, quantity, options}) method to prepare your catalog product.
  4. Set the license code as the subscription reference on the cart TwoCoInlineCart.cart.setSubscription('IMKNNVEY13').
  5. Set the customer's email address on the cart (the email must match the subscription) TwoCoInlineCart.billing.setEmail('john.doe@company.com').
  6. Set the renewal flag on the cart TwoCoInlineCart.cart.setRenewalFlag(true).
  7. Use the TwoCoInlineCart.cart.checkout() method to show the cart on your page.

Sample request

HTML

<a href="#" class="btn btn-success" id="buy-button">Buy now!</a>

Javascript

window.document.getElementById('buy-button').addEventListener('click', function() {
  TwoCoInlineCart.products.add({
    code: "74B8E17CC0"
  });
  TwoCoInlineCart.cart.setSubscription('IMKNNVEY13');
  TwoCoInlineCart.billing.setEmail('john.doe@company.com');
  TwoCoInlineCart.cart.setRenewalFlag(true);
  TwoCoInlineCart.cart.checkout();
});

Demo (Using Test Mode)

Preload iframe to increase loading speed

Overview

If you are not displaying the card form on page load, you can preload the iframe in the background to speed up the loading time when you mount the componet.

Use case

1. Create a form with id="payment-form":

<form type="post" id="payment-form">
 <div class="form-group">
   <label for="name" class="label control-label">Name</label>
   <input type="text" id="name" class="field form-control">
 </div>
 <button class="btn btn-primary" type="submit">Generate token</button>
</form>


2. Inside the form add an element with id="card-element". The form should now look like this:

<form type="post" id="payment-form">
 <div class="form-group">
   <label for="name" class="label control-label">Name</label>
   <input type="text" id="name" class="field form-control">
 </div>
 <div id="card-element">
   <!-- A TCO IFRAME will be inserted here. -->
 </div>
 <button class="btn btn-primary" type="submit">Generate token</button>
</form>


3. Include the 2Pay.js drop-in payment client JavaScript:

<script type="text/javascript" src="https://2pay-js.2checkout.com/v1/2pay.js"></script>


4. Insert the following configuration JavaScript to preload the iframe in the background on page load.

window.component = null;
window.addEventListener('load', function() {
 // Initialize the JS Payments SDK client.
 let jsPaymentClient = new  TwoPayClient('YOUR_MERCHANT_CODE');
 
 // Create the component that will hold the card fields.
 let component = jsPaymentClient.components.create('card');
 
 // Preload the card fields component in the desired HTML tag. This is where the iframe will be located.
 component.preload('#card-element');
});


5. Display or hide the card form when you are ready

function show() {
   component.mount('#card-element');
}
function hide() {
   component.hide();
}

 

Demo

After performing the steps above, your implementation should look like this:

 

Cancel refund

Overview

Use the cancelRefund method to issue a total refund for an order processed by 2Checkout.

Requested parameters

This method allows you to cancel a refund initiated from the cPanel or to decline a refund initiated by the shopper from myAccount.

The status of the refund needs to be PENDING or APPROVED.

The refund can be cancelled in up to 2 hours from the initiation. 

Request sample 

<?php

declare(strict_types=1);

class Configuration
{
    public const MERCHANT_CODE = 'AVANGATE';
    public const MERCHANT_KEY = 'SECRET_KEY';
    public const URL = 'https://api.2checkout.com/soap/6.0';
    public const ACTION = 'cancelRefund';
    public const ADDITIONAL_OPTIONS = null;
    public const ORDER_REF = '73152889';
    //array or JSON
    public const PAYLOAD = null;

}

class Client
{
    public function call(
        string $url = Configuration::URL,
        $payload = Configuration::PAYLOAD,
        string $action = Configuration::ACTION
    ): ?object {
        if (is_array($payload)) {
            $payload = json_encode($payload);
        }
        if (!empty($payload)) {
            // SoapClient works with objects(StdClass)
            $payload = json_decode($payload);
        }
        $soapClient = $this->getClient($url);
        $sessionId = $this->getSession($soapClient);
        $args = array_filter([$sessionId, Configuration::ORDER_REF, $payload]);

        return $soapClient->$action(...$args);
    }

    public function getClient(string $url): SoapClient
    {
        return new SoapClient(
            $url . '?wsdl',
            [
                'location'   => $url,
                'cache_wsdl' => WSDL_CACHE_NONE,
            ]
        );
    }

    public function getSession(SoapClient $client)
    {
        $date = gmdate('Y-m-d H:i:s');
        $merchantCode = Configuration::MERCHANT_CODE;
        $key = Configuration::MERCHANT_KEY;
        $string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
        $algo = 'sha256';
        $hash = hash_hmac($algo, $string, $key);
        $client->__setCookie('XDEBUG_SESSION', 'PHPSTORM');

        return $client->login($merchantCode, $date, $hash, $algo);
    }
}

try {
    $client = new Client();
    var_dump($client->call());
} catch (Exception $ex) {
    var_dump($ex);
}

Response

Response Type/Description
RefundID The ID generated for this refund.

Cancel refund

Overview

Use the cancelRefund method to issue a total refund for an order processed by 2Checkout.

Requested parameters

This method allows you to cancel a refund initiated from the cPanel or to decline a refund initiated by the shopper from myAccount.

The status of the refund needs to be PENDING or APPROVED.

The refund can be cancelled in up to 2 hours from the initiation. 

Request sample

<?php

declare(strict_types=1);

class Configuration
{
    public const MERCHANT_CODE = 'AVANGATE';
    public const MERCHANT_KEY = 'SECRET_KEY';
    public const URL = 'https://api.2checkout.com/rpc/6.0';
    public const ACTION = 'cancelRefund';
    public const ADDITIONAL_OPTIONS = null;
    public const ORDER_REF = '73152889';
    //array or JSON
    public const PAYLOAD = null;
}

class Client
{
    private const LOGIN_METHOD = 'login';
    private $calls = 1;
    private $sessionId;

    private function generateAuth(): array
    {
        $merchantCode = Configuration::MERCHANT_CODE;
        $key = Configuration::MERCHANT_KEY;
        $date = gmdate('Y-m-d H:i:s');
        $string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
        $hash = hash_hmac('md5', $string, $key);

        return compact('merchantCode', 'date', 'hash');
    }

    public function login(string $url)
    {
        $payload = $this->generateAuth();
        $response = $this->call($url, array_values($payload), self::LOGIN_METHOD);
        $this->sessionId = $response['result'];
    }

    public function call(
        string $url = Configuration::URL,
        $payload = Configuration::PAYLOAD,
        string $action = Configuration::ACTION
    ): ?array {
        if (empty($this->sessionId) && $action !== self::LOGIN_METHOD) {
            $this->login($url);
        }

        if (is_string($payload)) {
            $payload = json_decode($payload, true);
        }
        if (!empty($this->sessionId)) {
            $payload = [$this->sessionId, Configuration::ORDER_REF, $payload];
        }
        $payload = array_filter($payload);

        $request = json_encode([
            'jsonrpc' => '2.0',
            'method'  => $action,
            'params'  => $payload,
            'id'      => $this->calls++,
        ]);

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_SSLVERSION, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt(
            $curl,
            CURLOPT_HTTPHEADER,
            ['Content-Type: application/json', 'Accept: application/json', 'Cookie: XDEBUG_SESSION=PHPSTORM']
        );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
        $response = curl_exec($curl);
        if (empty($response)) {
            die('Server unavailable');
        }
        echo $response . '</br>';

        return json_decode($response, true);;
    }
}

$client = new Client();
$result = $client->call();
var_dump($result);

Response

Response Type/Description
RefundID The ID generated for this refund.

Workflow

  1. Use the following URL: https://api.2checkout.com/soap/6.0
  2. Authenticate using the login method and create a session (connection).
  3. Set partner
  4. Throughout the lifetime of the session (max 10 minutes), you can invoke all 2Checkout API methods. To invoke methods you need to send a request to 2Checkout. Read more on the request object below.
  5. The 2Checkout system provides responses to all requests. 

 

 

Authentication

Overview

Use the login method for the authentication process in the 2Checkout system.

Parameters

Parameters Type/Description
merchantCode required (string)
  Your merchant identification code.
date required (string)
  GMT ISO Date format (e.g. 2010-01-01 12:13:14)
hash required (string)
  Calculated HMAC_SHA256 signature based on merchantCode and date, using your secret key.

 

Request

To create the HMAC_SHA256 source string use your merchant code and the date of the request, prefixing them with the length in bytes of each respective value, along with your account’s secret key (for UTF-8 characters the length in bytes might be longer than the string length). For example:

Parameters Type/Description
MerchantCode Your merchant account code.
 

8AVANGATE

 

Date 2010-05-13 12:12:12
 

192010-05-13 12:12:12

 

HMAC source string

8AVANGATE192010-05-13 12:12:12

 

Secret key SECRET_KEY
Calculated HMAC_SHA256 signature based on MerchantCode and Date, using your secret key:
bf763db7d333e9c3038698cf59ada3e6
<?php

$host   = "https://api.2checkout.com";

$merchantCode = "YOURCODE123";
//your account's merchant code available in the 'System settings' area of the cPanel:
//https://secure.2checkout.com/cpanel/account_settings.php

$key          = "SECRET_KEY";
//your account's secret key available in the 'System settings' area of the cPanel:
//https://secure.2checkout.com/cpanel/account_settings.php

$now          = gmdate('Y-m-d H:i:s'); //GMT date format)
$algo = "sha256";
$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash = hash_hmac($algo, $string, $key);

try {
    $client = new SoapClient($host . "/soap/6.0/?wsdl", array(
        'location' => $host . "/soap/6.0/",
        "stream_context" => stream_context_create(array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false
            )
        ))
    ));
    $sessionID = $client->login($merchantCode, $now, $hash, $algo);
    echo("Auth token: {$sessionID}" . PHP_EOL);
}
catch (SoapFault $e) {
    echo "Authentication: " . $e->getMessage() . PHP_EOL;
    exit;
} 

Response

Parameter Type/Description
sessionID string
  Session identifier, the output of the Login method. Include sessionID into all your requests. 2Checkout throws an exception if the values are incorrect.
The sessionID expires in 10 minutes.

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