Skip to main content

Retrieve Single Sign On customer info by SSOToken

Overview

Use the getCustomerInformationBySSOToken method to retrieve the details of a customer entity from the Avangate system. Send the SSO token you create by generating tokenized cart payment links.

Parameters

Parameters Type/Description
sessionID Required (string)
  Session identifier, the output of the Login method. Include sessionID into all your requests. Avangate throws an exception if the values are incorrect.  The sessionID expires in 10 minutes.
SingleSignOnToken Required (string)
  The SSO token you create by generating tokenized cart payment links.

Response

Customer Object

Request


<?php
$host   = "https://api.avangate.com";
$client = new SoapClient($host . "/soap/4.0/?wsdl", array(
    'location' => $host . "/soap/4.0/",
    "stream_context" => stream_context_create(array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false
        )
    ))
));

function hmac($key, $data)
{
    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
        $key = pack("H*", md5($key));
    }
    
    $key    = str_pad($key, $b, chr(0x00));
    $ipad   = str_pad('', $b, chr(0x36));
    $opad   = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad;
    $k_opad = $key ^ $opad;
    return md5($k_opad . pack("H*", md5($k_ipad . $data)));
}
$merchantCode = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$now          = gmdate('Y-m-d H:i:s'); //date_default_timezone_set('UTC')
$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash   = hmac($key, $string);
try {
    $sessionID = $client->login($merchantCode, $now, $hash);
}
catch (SoapFault $e) {
    echo "Authentication: " . $e->getMessage();
    exit;
}
$IdCustomer = '352365983';
$CustomerType = 'AvangateCustomerReference';
$Url = 'https://store.avancart.com/order/checkout.php?PRODS=4639321&QTY=1&CART=1&CARD=2';
$ValidityTime = 50;
$ValidationIp = null;
try {
    $ssoLINK = $client->getSingleSignOnInCart($sessionID, $IdCustomer, $CustomerType, $Url, $ValidityTime, $ValidationIp);
}
catch (SoapFault $e) {
    echo "ssoLINK: " . $e->getMessage();
    exit;
}
var_dump("ssoLINK", $ssoLINK);
parse_str($ssoLINK);
try {
    $CustomerSSOInfo = $client->getCustomerInformationBySSOToken($sessionID, $logintoken);
}
catch (SoapFault $e) {
    echo "CustomerSSOInfo: " . $e->getMessage();
    exit;
}
var_dump("CustomerSSOInfo", $CustomerSSOInfo);

Retrieve subscription payment information

Overview

Use the getSubscriptionPaymentInformation method via JSON-RPC API 4.0 to retrieve information related to the payment made for a subscription.

Parameters

Parameters Type/Description
sessionID Required (String)
  Session identifier, the output of the Login method. Include sessionID into all your requests. Avangate throws an exception if the values are incorrect. The sessionID expires in 10 minutes.
subscriptionReference Required (String)
  The reference of the subscription you want to retrieve payment information for.

Response

Parameters Type/Description

Type

String

 

Payment method type.

Currency

String

 

ISO code of the order currency.

PaymentMethod

Object

 

FirstDigits

String

 

 

First 4 digits of the card used on the order.

 

LastDigits

String

 

 

Last 4 digits of the card used on the order.

 

CardType

String

 

 

Type of card used on the order.

Request

<?php
require ('PATH_TO_AUTH');

$subscriptionReference = "Subscription_Code";

$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'getSubscriptionPaymentInformation';
$jsonRpcRequest->params = array($sessionID, $subscriptionReference);
$jsonRpcRequest->id = $i++;

$paymentInformation = callRPC($jsonRpcRequest, $host);
var_dump($paymentInformation);

Retrieve specific list of subscriptions

Overview

Extract information on a specific list of subscriptions. Use the getSubscriptions method to retrieve details about a specific list of your account’s subscriptions.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

Session identifier, the output of the Login method. Include sessionID into all your requests. Avangate throws an exception if the values are incorrect.  The sessionID expires in 10 minutes.

subscriptionReference

Required (Array of strings)

 

Unique, system-generated subscription identifier.

aggregate

Required (boolean)

 

true - search will work across all your aggregated Avangate accounts.

false - default value. You limit the search to the account whose details you used for authentication.

Response

Parameters Type/Description

Subscription

Array of objects

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReferences = array('REFERENCE1', 'REFERENCE2', 'REFERENCE3');

$jsonRpcRequest = array (
'method' => 'getSubscriptions',
'params' => array($sessionID, $subscriptionReferences),
'id' => $i++,
'jsonrpc' => '2.0');

var_dump (callRPC((Object)$jsonRpcRequest, $host, true));

Retrieve VAT or sales tax

Overview

  1. Populate the Order object with information. Avangate needs the BillingDetails (object) information to calculate taxes. 
  2. Use the getContents method to get info on all the products added to cart by the shopper in the current session.
  3. The output of the getContents method is the Order session content object.
  4. Under the Price, access information including for each product purchased. Find value added tax and sales tax details under the VAT parameter. 
  5. Tax information is also available for the entire order object. Find value added tax and sales tax details under the VAT parameter.
  6. Calculate the VAT/sales tax rates using the VAT and NetPrice values

 

Parameters

Parameters Type/Description

sessionID

Required (string)

 

Session identifier, the output of the Login method. Include sessionID into all your requests. Avangate throws an exception if the values are incorrect.  The sessionID expires in 10 minutes.

Order

Required (Object)

 

Object designed to collect all data necessary for an order, including billing, product/subscription plan and payment details.

Response

OrderContents

Object

Request

<?php


function callRPC($Request, $hostUrl, $Debug = true) {
    $curl = curl_init($hostUrl);
    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, array('Content-Type: application/json', 'Accept: application/json'));
    $RequestString = json_encode($Request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString);


    if ($Debug) {
        $RequestString;
    }
    $ResponseString = curl_exec($curl);
    if ($Debug) {
        $ResponseString;
    }

    if (!empty($ResponseString)) {
        $Response = json_decode($ResponseString);
        if (isset($Response->result)) {
            return $Response->result;
        }
        if (!is_null($Response->error)) {
            var_dump($Request->method, $Response->error);
        }
    } else {
        return null;
    }
}

$host = 'https://api.avangate.com/rpc/3.0/';

$merchantCode = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php

$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');
$hash = hash_hmac('md5', $string, $key);

$i = 1; // counter for api calls
// call login
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;

$sessionID = callRPC($jsonRpcRequest, $host);

var_dump($sessionID);
$Order = new stdClass();
$Order->RefNo = NULL;
$Order->Currency = 'usd';
$Order->Country = 'US';
$Order->Language = 'en';
$Order->CustomerIP = '91.220.121.21';
$Order->ExternalReference = NULL;
$Order->Source = NULL;
$Order->AffiliateId = NULL;
$Order->CustomerReference = NULL;
$Order->Items = array();
$Order->Items[0] = new stdClass();
$Order->Items[0]->Code = 'my_subscription_1';
$Order->Items[0]->Quantity = 1;
$Order->Items[0]->PriceOptions = NULL;
$Order->Items[0]->SKU = NULL;
$Order->Items[0]->Price = NULL;
$Order->Items[0]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->Items[0]->Promotion = NULL;
$Order->BillingDetails = new stdClass();
$Order->BillingDetails->FirstName = 'FirstName';
$Order->BillingDetails->LastName = 'LastName';
$Order->BillingDetails->CountryCode = 'us';
$Order->BillingDetails->State = 'California';
$Order->BillingDetails->City = 'LA';
$Order->BillingDetails->Address1 = 'Address example';
$Order->BillingDetails->Address2 = NULL;
$Order->BillingDetails->Zip = '90210';
$Order->BillingDetails->Email = 'customer@email.com';
$Order->BillingDetails->Phone = NULL;
$Order->BillingDetails->Company = NULL;
$Order->DeliveryDetails = NULL;
$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'TEST';
$Order->PaymentDetails->Currency = 'usd';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '10.10.10.10';
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$Order->PaymentDetails->PaymentMethod->CardNumber = "4111111111111111";
$Order->PaymentDetails->PaymentMethod->CardType = 'visa';
$Order->PaymentDetails->PaymentMethod->ExpirationYear = '2019';
$Order->PaymentDetails->PaymentMethod->ExpirationMonth = '12';
$Order->PaymentDetails->PaymentMethod->HolderName = 'John';
$Order->PaymentDetails->PaymentMethod->CCID = '123';
$Order->Promotions = NULL;
$Order->AdditionalFields = NULL;
$Order->LocalTime = NULL;
$Order->GiftDetails = NULL;
$jsonRpcRequest = array (
'method' => 'getContents',
'params' => array($sessionID, $Order),
'id' => $i++,
'jsonrpc' => '2.0'
);
echo '<BR>';
echo 'The content of the current session:';
echo '<BR>';
var_dump (callRPC((Object)$jsonRpcRequest, $host, true));

Payment flow with offline payment methods

Overview

The following payment methods are supported for the offline payment flow: Purchase Order flow, Wire, Check, and Boleto/Pix

Availability

Available for all 2Checkout accounts.

How E-wallet payments work 

Offline payment methods are payment methods where the order is registered by 2Checkout, however, the shopper finalizes the payment offline. 

This type of payment methods include payments done via bank transfers (Purchase Orders, Wire) or in-store payments like Boleto/Pix

Since these payments take longer to process than online payments, once an order is placed it will remain in 'status = Pending' until the order status is updated by the payment provider. Once the payment is processed by them, then the order status will be updated to 'Complete' in the 2Checkout system.

Purchase Order flow

The Purchase Order flow payment method is available only for payments done by companies. The Purchase order (PO) flow is similar to the Wire payment method, as in the data needed for the completion of the payment will be available both in the API response, as well as in the email sent to the email address used in the Billing Details object.

Payment method object structure

Field name Type Required/Optional Description

Company

String

Required

The name of the company.

AutoApprove

Boolean

Optional

Use AutoApprove = true when you want the order to be automatically approved by the merchant. If false, the order needs to be approved manually from the Merchant Control Panel.

Default value: false.

InternalPONumber

String

Optional

Internal unique ID.

Request example

{
   "Language":"en",
   "Country":"US",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"USD",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"133685A7B4",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"US",
      "State":"California",
      "City":"San Francisco",
      "Address1":"Example Street",
      "Zip":"90210",
      "Email":"example@email.com",
      "Company":"ACME Inc."
   },
   "PaymentDetails":{
      "Type":"PURCHASEORDER",
      "Currency":"USD",
      "PaymentMethod":{
         "AutoApprove":true,
         "InternalPONumber":84864848
      }
   }
}

After the order is placed, it will remain in 'status = Pending' until the payment is completed.

The additional information needed by the shopper to finalize the payment is provided in the PaymentDetails node.

"PaymentDetails":{
      "Type":"WIRE",
      "Currency":"usd",
      "PaymentMethod":{
         "Amount":"24.65",
         "Currency":"usd",
         "PaymentReference":"130738297",
         "RoutingNumber":null,
         "BankAccounts":[
            {
               "BankName":"Silicon Valley Bank USA",
               "BankCountry":"United States of America",
               "BankCity":null,
               "BankAddress":"3003 TASMAN DRIVE, SANTA CLARA, CA  95054, USA",
               "Beneficiary":"Avangate Inc dba 2Checkout",
               "BankAccount":"ABA 121140399 #3300578784",
               "BankAccountIban":null,
               "BankAccountSwiftCode":"SVBKUS6S",
               "Currency":"USD"
            }
         ],
         "Vendor3DSReturnURL":null,
         "Vendor3DSCancelURL":null,
         "InstallmentsNumber":null
      },
      "CustomerIP":"5.12.32.22"
   },

Wire  

Payment method object structure

There are no specific payment method data that is mandatory or optional. 

Request example

{
   "Language":"en",
   "Country":"US",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"USD",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"133685A7B4",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"US",
      "State":"California",
      "City":"San Francisco",
      "Address1":"Example Street",
      "Zip":"90210",
      "Email":"example@email.com"
   },
   "PaymentDetails":{
      "Type":"WIRE",
      "Currency":"USD",
      "PaymentMethod":{

      }
   }
}

After the order is placed, it will remain in 'status = Pending' until the payment is completed.

The additional information needed by the shopper to finalize the payment is provided in the PaymentDetails node. 

"PaymentDetails":{
      "Type":"WIRE",
      "Currency":"usd",
      "PaymentMethod":{
         "Amount":"24.65",
         "Currency":"usd",
         "PaymentReference":"130738297",
         "RoutingNumber":null,
         "BankAccounts":[
            {
               "BankName":"Silicon Valley Bank USA",
               "BankCountry":"United States of America",
               "BankCity":null,
               "BankAddress":"3003 TASMAN DRIVE, SANTA CLARA, CA  95054, USA",
               "Beneficiary":"Avangate Inc dba 2Checkout",
               "BankAccount":"ABA 121140399 #3300578784",
               "BankAccountIban":null,
               "BankAccountSwiftCode":"SVBKUS6S",
               "Currency":"USD"
            }
         ],
         "Vendor3DSReturnURL":null,
         "Vendor3DSCancelURL":null,
         "InstallmentsNumber":null
      },
      "CustomerIP":"5.12.32.22"
   },

Check  

Payment method object structure

There are no specific payment method data that is mandatory or optional. 

Request example

{
   "Language":"en",
   "Country":"US",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"USD",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"133685A7B4",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"US",
      "State":"California",
      "City":"San Francisco",
      "Address1":"Example Street",
      "Zip":"90210",
      "Email":"example@email.com"
   },
   "PaymentDetails":{
      "Type":"CHECK",
      "Currency":"USD",
      "PaymentMethod":{

      }
   }
}

After the order is placed, it will remain in 'status = Pending' until the payment is completed.

The additional information needed by the shopper to finalize the payment is provided via email. 

Integration test cases

  1. Build a request with all the relevant information to place a new order. Make sure that when the order is sent in the API the response contains an order object (order was placed successfully).
  2. Make sure that you display the information needed by the shopper to finalize the payment.
  3. If you have any additional webhook integrations, make sure that the webhooks are correctly configured and that the notifications are received and processed successfully. 

Calculate and display shopping cart taxes

Overview

When selling internationally, charging the appropriate amount for taxes can be tricky, as the correct taxation can depend on the shopper's country or US state, the product type, and the order total amount. 

However, merchants on the 2Monetize package do not have to worry, as the API calculates and handles the VAT and Sales taxes based on the order information. 

Availability

Available to all 2Checkout accounts.

getContents API Method

Information about VAT and sales taxes is handled by the getContents (for JSON-RPC and SOAP protocols) or by making a PUT request to /orders/0/ on REST.

This API method will take into account the product configuration (NET or GROSS price type, product category, pricing options, etc.), any marketing campaign (like discounts) together with the shopper's location, and return all the information needed to display to the shopper.

Request object

The getContents API call accepts as an input an order object, the same object used for placing an order. However, the only required objects for calculating the taxes are the items information (what products the shopper has in their cart) and the BillingDetails (needed in order to locate the customer and retrieve the taxes that should be applied). 

Switching the currency

Switching the currency and converting prices is supported both for prices set in multiple currencies in the product configuration, as well as on the fly. 

In order to do this, the currency ISO code needs to be updated in the root object Currency element.

Request example

{
    "Country": "DE",
    "Currency": "EUR",
    "Items": [
        {
            "Code": "NIQRPI0GTU",
            "Quantity": 2
        },
        {
            "Code": "0XICS3OVDK",
            "Quantity": 1
        }
    ],
    "BillingDetails": {
        "FirstName": "Customer First Name",
        "LastName": "Customer Last Name",
        "CountryCode": "DE",
        "City": "Bucharest",
        "Address1": "Example Street",
        "Zip": "73331",
        "Email": "example@email.com"
    }
}

Response Object

The API will respond with the full order object, including the price and tax information, both on a line item (unit) level as well as on a cart level.  

{
    "Currency": "eur",
    "NetPrice": 266.71,
    "GrossPrice": 309.38,
    "NetDiscountedPrice": 266.71,
    "GrossDiscountedPrice": 309.38,
    "Discount": 0,
    "VAT": 42.67,
    "AffiliateCommission": 0,
    "Errors": null,
    "Items": [
        {
            "AdditionalFields": null,
            "Code": "NIQRPI0GTU",
            "ExternalReference": "",
            "LineItemReference": "7fe4770c0c95d44dec5c02ee1bc752b568b47808",
            "CrossSell": null,
            "Quantity": 2,
            "Price": {
                "Currency": "eur",
                "NetPrice": 169.88,
                "GrossPrice": 197.06,
                "NetDiscountedPrice": 169.88,
                "GrossDiscountedPrice": 197.06,
                "Discount": 0,
                "VAT": 27.18,
                "AffiliateCommission": 0,
                "UnitNetPrice": 84.94,
                "UnitGrossPrice": 98.53,
                "UnitVAT": 13.59,
                "UnitDiscount": 0,
                "UnitNetDiscountedPrice": 84.94,
                "UnitGrossDiscountedPrice": 98.53,
                "UnitAffiliateCommission": 0,
                "ItemUnitNetPrice": null,
                "ItemUnitGrossPrice": null,
                "ItemNetPrice": null,
                "ItemGrossPrice": null,
                "VATPercent": 16,
                "HandlingFeeNetPrice": 0,
                "HandlingFeeGrossPrice": 0
            },
            "PriceOptions": [],
            "ProductDetails": {
                "Name": "100 USD NET API Product",
                "ShortDescription": "<p>100 USD NET API Product<\/p>",
                "Tangible": false,
                "IsDynamic": false,
                "ExtraInfo": null,
                "RenewalStatus": false,
                "Subscriptions": null,
                "DeliveryInformation": {
                    "Delivery": "NO_DELIVERY",
                    "DownloadFile": null,
                    "DeliveryDescription": "",
                    "CodesDescription": "",
                    "Codes": []
                }
            },
            "Promotion": null,
            "PurchaseType": "PRODUCT",
            "RenewalInformation": null,
            "SKU": null,
            "SubscriptionStartDate": null,
            "Trial": null,
            "SubscriptionCustomSettings": null
        },
        {
            "AdditionalFields": null,
            "Code": "0XICS3OVDK",
            "ExternalReference": "",
            "LineItemReference": "7fe4770c0c95d44dec5c02ee1bc752b568b47808",
            "CrossSell": null,
            "Quantity": 1,
            "Price": {
                "Currency": "eur",
                "NetPrice": 96.83,
                "GrossPrice": 112.32,
                "NetDiscountedPrice": 96.83,
                "GrossDiscountedPrice": 112.32,
                "Discount": 0,
                "VAT": 15.49,
                "AffiliateCommission": 0,
                "UnitNetPrice": 96.83,
                "UnitGrossPrice": 112.32,
                "UnitVAT": 15.49,
                "UnitDiscount": 0,
                "UnitNetDiscountedPrice": 96.83,
                "UnitGrossDiscountedPrice": 112.32,
                "UnitAffiliateCommission": 0,
                "ItemUnitNetPrice": null,
                "ItemUnitGrossPrice": null,
                "ItemNetPrice": null,
                "ItemGrossPrice": null,
                "VATPercent": 16,
                "HandlingFeeNetPrice": 0,
                "HandlingFeeGrossPrice": 0
            },
            "PriceOptions": [],
            "ProductDetails": {
                "Name": "2nd API NET product",
                "ShortDescription": "<p>2nd API NET product<\/p>",
                "Tangible": false,
                "IsDynamic": false,
                "ExtraInfo": null,
                "RenewalStatus": false,
                "Subscriptions": null,
                "DeliveryInformation": {
                    "Delivery": "NO_DELIVERY",
                    "DownloadFile": null,
                    "DeliveryDescription": "",
                    "CodesDescription": "",
                    "Codes": []
                }
            },
            "Promotion": null,
            "PurchaseType": "PRODUCT",
            "RenewalInformation": null,
            "SKU": null,
            "SubscriptionStartDate": null,
            "Trial": null,
            "SubscriptionCustomSettings": null
        }
    ],
    "Promotions": [],
    "AdditionalFields": null,
    "BillingDetails": {
        "FirstName": "Customer First Name",
        "LastName": "Customer Last Name",
        "CountryCode": "de",
        "State": null,
        "City": "Bucharest",
        "Address1": "Example Street",
        "Address2": null,
        "Zip": "73331",
        "Email": "example@email.com",
        "Phone": null,
        "Company": null,
        "FiscalCode": null,
        "TaxOffice": null
    },
    "DeliveryDetails": {
        "FirstName": "Customer First Name",
        "LastName": "Customer Last Name",
        "CountryCode": "de",
        "State": null,
        "City": "Bucharest",
        "Address1": "Example Street",
        "Address2": null,
        "Zip": "73331",
        "Email": "example@email.com",
        "Phone": null,
        "Company": null
    },
    "DeliveryInformation": {
        "ShippingMethod": {
            "Code": null,
            "TrackingUrl": null,
            "TrackingNumber": null,
            "Comment": null
        }
    },
    "Affiliate": {
        "AffiliateCode": null,
        "AffiliateSource": null,
        "AffiliateName": null,
        "AffiliateUrl": null
    },
    "CustomParameters": null
}

Unit price information

Per Line Item, each product contains a Price object, with all relevant information for the product's price and taxes:  

Key name Type Description

Currency

String

The currency ISO 4217 code; This currency is used in all the price values for that product. Example: USD.

UnitNetPrice

Float

The value per product unit (quantity = 1), excluding sales tax/VAT. Discounts are not reflected in this price.

UnitGrossPrice

Float

Total value per product unit (quantity = 1), including sales tax/VAT.  Discounts are not reflected in this price.

UnitVAT

Int

Sales tax/VAT per product unit.

UnitNetDiscountedPrice

Float

The value per product unit,, excluding sales tax/VAT, from which 2Checkout deducts the unit discount.

UnitGrossDiscountedPrice

Float

Total costs shoppers incur per product unit. This value includes sales tax/VAT, 2Checkout, and affiliate commissions, but 2Checkout deducts the value of any discounts.

VATPercent

Int

Percentage of VAT charged on the order.

VAT

Float

Value of VAT per order line.

Discount

Float

Value of the discounts per order line expressed in the payment currency.

NetDiscountedPrice

Float

The NetPrice value per order line, excluding sales tax/VAT, from which 2Checkout deducts discounts.

GrossDiscountedPrice

Float

Total costs shoppers incur per order line. This value includes sales tax/VAT, 2Checkout, and affiliate commissions, but 2Checkout deducts the value of any discounts.

Order price information

On order level, in the response object root level, you can find all relevant information for the order's price and taxes:

Key name Type Description

NetPrice

Float

Order value excluding sales tax/VAT.

GrossPrice

Float

Total order value, including sales tax/VAT. GrossPrice does not reflect any discounts.

NetDiscountedPrice

Float

The NetPrice order value excluding sales tax/VAT, from which 2Checkout deducts discounts.

GrossDiscountedPrice

Float

Total costs shoppers incur. This value includes sales tax/VAT, 2Checkout, and affiliate commissions, but 2Checkout deducts the value of any discounts.

Discount

Float

Value of the discounts for an order.

VAT

Float

Value of sales tax/VAT.

Integration test cases

  1. Create a simple product (be it a catalog product in the Control Panel, or a dynamic product), using a round number as the price (like 100) in order to be able to easily check the calculated taxes. 
  2. Using the getContents API call, build your checkout flow, and display the taxes as needed. 
  3. As an easy comparison, you can use a catalog product and generate a buy-link in ConvertPlus and compare the way the taxes are displayed.
  4. If needed, implement the currency switching in the checkout flow.  
  • Keep in mind that, where prices in other currencies are specified in the product catalog, they will be used instead of the prices automatically converted by 2Checkout. 

Use WeChat Pay

Overview

Place an order for catalog products defined in your Control Panel and collect the payment using WeChat Pay.

Requirements

Only Chinese shoppers are able to purchase using WeChat Pay. Make sure the billing country code is set to CN.

Supported currencies

  • USD
  • HKD
  • CNY

Workflow

  1. Shoppers select WeChat as a payment option in the interface you provide to them.
  2. Create the order object. Use WE_CHAT_PAY as the type of the PaymentDetails object, and include ReturnURL and CancelURL.
  3. Use the placeOrder method to send the data to 2Checkout.
  4. Once you place the order, 2Checkout logs it into the system. At this point in time, the status of the order is PENDING.
  5. 2Checkout returns an Order object as the output of the placeOrder method. 
  6. Use the PaymentMethod object to create a redirect URL for the shoppers, concatenating the values of the Href and avng8apitoken parameters. Here's an example of the redirect URL:
    https://api.2checkout.com/4.0/scripts/we_chat_pay/authorize/?avng8apitoken=1abc7fd72d008428
  7. After being redirected to WeChat Pay, shoppers need to scan the QR code provided, using the WeChat smartphone app.
  8. After customers enter their payment password, WeChat notifies 2Checkout if the payment is approved, and the status of the order becomes COMPLETE.
  9. Shoppers are redirected to the RedirectURL from the Order information object. In case the payment fails, shoppers are redirected to the CancelURL. 

Parameters

Parameters Type/Description

sessionID

Required (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.

Order

Required (Object)

 

Object designed to collect all data necessary for an order, including billing, product/subscription plan, and payment details.

To place an order with WeChat, use WE_CHAT_PAY as the type of the PaymentDetails object and provide a ReturnURL and a CancelURL as part of the PaymentMethod object. See code sample. 

Response

Parameters Type/Description
Order information Object
  Object containing order information.

Request

<?php

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->RefNo = NULL;
$Order->Currency = 'usd';
$Order->Country = 'CN';
$Order->Language = 'en';
$Order->CustomerIP = '91.220.121.21';
$Order->ExternalReference = NULL;
$Order->Source = NULL;
$Order->AffiliateId = NULL;
$Order->CustomerReference = NULL;
$Order->Items = array();
$Order->Items[0] = new stdClass();
$Order->Items[0]->Code = 'my_subscription_1';
$Order->Items[0]->Quantity = 1;
$Order->Items[0]->PriceOptions = NULL;
$Order->Items[0]->SKU = NULL;
$Order->Items[0]->Price = NULL;
$Order->Items[0]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->Items[0]->SubscriptionStartDate = NULL; //If empty or null, subscriptions become active when purchase is made.
$Order->BillingDetails = new stdClass();
$Order->BillingDetails->FirstName = 'Test Cosmin API';
$Order->BillingDetails->LastName = 'Cosmin API';
$Order->BillingDetails->CountryCode = 'CN';
$Order->BillingDetails->State = 'California';
$Order->BillingDetails->City = 'LA';
$Order->BillingDetails->Address1 = 'Address example';
$Order->BillingDetails->Address2 = NULL;
$Order->BillingDetails->Zip = '90210';
$Order->BillingDetails->Email = 'cosmin.deftu@2checkout.com';
$Order->BillingDetails->Phone = NULL;
$Order->BillingDetails->Company = NULL;
$Order->DeliveryDetails = NULL;

$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'WE_CHAT_PAY';
$Order->PaymentDetails->Currency = 'USD';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '91.220.121.21';
$Order->PaymentDetails->PaymentMethod->ReturnURL = 'http://yourreturnurl.com';
$Order->PaymentDetails->PaymentMethod->CancelURL= 'http://yourcancelurl.com';

$Order->AdditionalFields = NULL;
$Order->LocalTime = NULL;
$Order->GiftDetails = NULL;

try {
   $newOrder = $client->placeOrder($sessionID, $Order);
}
catch (SoapFault $e) {
    echo "newOrder: " . $e->getMessage();
    exit;
}

$wechatredirect = $newOrder->PaymentDetails->PaymentMethod->Authorize->Href."/?avng8apitoken=".$newOrder->PaymentDetails->PaymentMethod->Authorize->Params->avng8apitoken;

header('Location:' . $wechatredirect);

 

Renew a subscription

Overview

Renew a subscription in the 2Checkout system on-demand, controlling the number of days, price, and currency of the extension. Use the renewSubscription method to renew a subscription.

Parameters

Parameters Type/Description

sessionID

Required (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.

subscriptionReference

Required (string)

 

Unique, system-generated subscription identifier.

 

2Checkout charges customers using the payment data attached to subscriptions. In the case of credit/debit cards, if customers update their payment information in myAccount or if you update these details on behalf of your subscribers, the 2Checkout system uses the latest card info provided to charge subscription renewals.

days

Required (int)

 

The number of days the 2Checkout system extends the lifetime of the subscription.

price

Required (double)

 

The price that 2Checkout charges the customer for the renewal. The type of price, Gross or Net, is decided by the product setting in the Merchant Control Panel.

currency

Required (string)

 

The currency associated to the renewal price - ISO 4217 code.

Response

Parameters Type/Description

Boolean

true or false depending on whether or not the operation succeeded.

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';
$days = 4;
$price = 50;
$currency = 'eur';

$jsonRpcRequest = array (
'method' => 'renewSubscription',
'params' => array($sessionID, $subscriptionReference, $days, $price, $currency),
'id' => $i++,
'jsonrpc' => '2.0');

var_dump (callRPC((Object)$jsonRpcRequest, $host, true));

Retrieve a pricing configuration by code

Overview

Use the getPricingConfigurationByCode method to extract information on a specific pricing configuration you set for a product.

Parameters

sessionID

Required (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.

ProductCode

Required (string)

 

The editable code that you control at product-level, not the unique, system-generated product ID.

PricingConfigurationCode

Required (string)

 

The code of the pricing configuration.

Response

PricingConfiguration

Object

Request

<?php

$host   = "https://api.2checkout.com";
$client = new SoapClient($host . "/soap/4.0/?wsdl", array(
    'location' => $host . "/soap/4.0/",
    "stream_context" => stream_context_create(array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false
        )
    ))
));


function hmac($key, $data)
{
    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
        $key = pack("H*", md5($key));
    }
    
    $key    = str_pad($key, $b, chr(0x00));
    $ipad   = str_pad('', $b, chr(0x36));
    $opad   = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad;
    $k_opad = $key ^ $opad;
    return md5($k_opad . pack("H*", md5($k_ipad . $data)));
}

$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'); //date_default_timezone_set('UTC')

$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash   = hmac($key, $string);

try {
    $sessionID = $client->login($merchantCode, $now, $hash);
}

catch (SoapFault $e) {
    echo "Authentication: " . $e->getMessage();
    exit;
}
 
$ProductCode = 'subscr1';
$PricingConfigurationCode = '0123456';
 
try {
    $ProductPricingConfiguration = $client-> getPricingConfigurationByCode ($sessionID, $ProductCode, $PricingConfigurationCode);
}

catch (SoapFault $e) {
    echo "Pricing Configuration: " . $e->getMessage();
    exit;
}

var_dump("Pricing Configuration", $ProductPricingConfiguration);
 
 
?>

 

Single Sign On in cart

Overview

Use the getSingleSignOnInCart method. 2Checkout attaches a unique token to links, designed to identify the returning shoppers and support the automatic extraction of payment data and billing information from the 2Checkout system. For example, you can generate single sign-on in cart links for existing customers logged into your website based on their external or 2Checkout customer IDs.

How does this work?

 

When accessing the shopping cart using tokenized payment links:

  • 2Checkout prefills automatically customer billing and delivery details associated with their 2Checkout customer accounts (linked based on their unique customer IDs).
  • 2Checkout presents shoppers with an optimized payment area featuring the credit/debit cards used to make previous purchases/transactions in the 2Checkout system. Customers have the option of selecting one of the payment methods depending on available card-on-file data.

Parameters

Parameters

Type/Description

sessionID

Required (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.

IdCustomer

Required (string)

 

Unique customer identifiers. Can be either the ExternalCustomerReference you control or the system-generated 2CheckoutCustomerReference.

CustomerType

Required (string)

 

Possible values:

  • ExternalCustomerReference
  • 2CheckoutCustomerReference

Url

Required (string)

 

The shopping cart URL. 2Checkout redirects shoppers to this URL.

 

Possible values:

 

Any buy link you generate from the cPanel or using the API. Note: For the time being, payment tokenization does not support Express Payments Checkout or the 2Checkout mobile shopping cart.

ValidityTime

Optional (int)

 

The time, in seconds, before the single sign-on URL expires. By default, the URL expires after 10 seconds. (optional)

ValidationIp

Optional (string)

 

The IP address of the shopper, necessary for security purposes. Can be an empty string or a valid IP, or null.

Response

Single sign-on URL

String

 

The generated string is the tokenized time-limited single sign-on URL pointing to 2Checkout shopping cart.

 

Note: Each SSO link cleans any previous cart sessions. Shoppers using multiple SSO links would purchase only a single product at a time.

 

If shoppers add multiple products to cart via SSO buy links and then use a non-SSO link, they’ll purchase all items using the same order.

When you use single sign-on in cart for customers without card on files in the 2Checkout system, the generated tokenized link prefills the billing information but the purchase process requires that shoppers provide payment information, such as a credit or debit card.

Example: https://store.YourCustomDomain.com/order/checkout.php?PRODS=1112233&logintoken=8b74ac97f8277654563c44da6915b054ba0d21be

 

Important! You can use the value of the logintoken to retrieve customer information by SSO token.

Request


<?php
 
 
function callRPC($Request, $hostUrl, $Debug = true) {
    $curl = curl_init($hostUrl);
    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, array('Content-Type: application/json', 'Accept: application/json'));
    $RequestString = json_encode($Request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString);
 
 
    if ($Debug) {
        $RequestString;
    }
    $ResponseString = curl_exec($curl);
    if ($Debug) {
        $ResponseString;
    }
 
    if (!empty($ResponseString)) {
        $Response = json_decode($ResponseString);
        if (isset($Response->result)) {
            return $Response->result;
        }
        if (!is_null($Response->error)) {
            var_dump($Request->method, $Response->error);
        }
    } else {
        return null;
    }
}
 
$host = 'https://api.avangate.com/rpc/3.0/';
 
$merchantCode = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.2checkout.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.2checkout.com/cpanel/account_settings.php
 
$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');
$hash = hash_hmac('md5', $string, $key);
 
$i = 1; // counter for api calls
// call login
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;
 
$sessionID = callRPC($jsonRpcRequest, $host);
 
var_dump($sessionID);
$IdCustomer = '352365983';
$CustomerType = '2CheckoutCustomerReference';
$Url = 'https://store.avancart.com/order/checkout.php?PRODS=4639321&QTY=1&CART=1&CARD=2';
$ValidityTime = 50;
$ValidationIp = null;

$jsonRpcRequest = array (
'method' => 'getSingleSignOnInCart',
'params' => array($sessionID, $IdCustomer, $CustomerType, $Url, $ValidityTime, $ValidationIp),
'id' => $i++,
'jsonrpc' => '2.0');

var_dump (callRPC((Object)$jsonRpcRequest, $host, true));

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