Skip to main content

Order session contents

Overview

Retrieve the current cart session content, and learn insights about your customers actions in cart.

You can obtain the VAT or sales TAX based on current cart items, prefill the customer information based on the subscription reference, or get the price applied in cart by using the API method from below.

 

Buy-link parameters

Overview

To start selling with 2Checkout, you need to redirect shoppers to 2Checkout's hosted secure checkout (ordering interface). Depending on your desired workflow, you can either generate buy-links using our dedicated interface (Generate Buy Links) or generate the parameters dynamically, in your own system.

Availability

All 2Checkout accounts. 

Requirements

Configure at least one product to generate a buy-link. 

Query parameters

When you generate a checkout link, 2Checkout automatically includes some of the parameters in the list below in the URL, depending on a number of variables, such as the purchase flow you choose, the products, discounts, currencies, cart languages, preselected payment methods and more. You can use these query parameters to generate checkout links in your own system, without having to rely on the functionality in you account. 

PARAMETER Required/Optional DESCRIPTION
PRODS Required

IDs for the products added to checkout, separated by a comma. Do not insert spaces or blanks between values. PRODS=1234567,1234568. 2Checkout automatically assigns each product added/imported into the platform a system-generated unique numeric (int) identifier. Example: Product ID = 1234567.

In the Control Panel, click to edit a product, and select the Information tab. The Product ID of the item you're editing is available at the top of the General area under Information. Product IDs are different than Product Codes, also available in this area, but which you control.

QTY Required The number of units (quantity)  for each product in checkout, separated by a commaDo not insert spaces or blanks between values. QTY=2,1
INFO1234567 Optional

Maximum length: 100 chars. Extra information that you can associate with the items in an order. 
For example: INFO1234567=free%20download orINFO1234567=technical%20support%20included. Use %20 instead of blanks for browser compatibility purposes.

In the examples above, 1234567 is the unique product identifier (Product ID) from the 2Checkout platform.

OPTIONS123456 Optional

Preselected pricing options for the corresponding product. The values used are the pricing options codes (the codes are set for each option individually). For example: OPTIONS5211=5usr,2year. Pricing options codes are case sensitive.

For scale pricing options group, you also need to send a specific value within the intervals defined. Let's assume that you created a Users scale pricing options group with the unique code: users, and two options: 1 to 10 ($99 per user) and 11 to 50 ($88 per user).

If you want to build the buy-link for a product using the Users scale pricing options group and charge customers for 35 users, the parameter should be formatted as such:OPTIONS=users=35, including both the unique code of the pricing options group and the specific value of the scale pricing interval.

COUPON Optional Promotion coupon code discounting the order. To send multiple values separate them by commas, in scenarios in which different coupons discount specific products added to cart.  
For example: [...]&COUPON=voucher1,voucher2[...]. The order of the values you send for the COUPON parameter does not need to match the order of products identifiers sent using PRODS. 
REF Optional External order reference. Add a string identifier to buy-links (max 100 char), to save extra info with the order, in addition to the system generated 2Checkout order reference. Consider using a HASH for increased security. You can validate the hash after you receive the order notification from 2Checkout. External references are visible when accessing the order details page for your orders.
CARD Optional

Possible values:

  • 1 - the link will generate a checkout page with review; displays the credit card details form in the selected landing page. Shoppers will place orders from the review page.
  • 2 - the link will generate a checkout page without review; displays the credit card details form in the selected landing page, and enables shoppers to place orders immediately after entering their payment data, excluding the review page altogether and shortening the purchase funnel.
CART Optional

Possible values:

  • CART=0 or missing - the cart contents are "read only", meaning that the customer cannot change/edit pricing options, quantity, etc. This link will be used in the "Request payment" feature from the cPanel Generate links page.  To make the contents of the cart read-only, select the Locked Express payments checkout, which contains the CART=0 parameter. 
  • CART=1 value means that the cart permits changes to the products contained in it, e.g. quantity, pricing options, add extra products from a cross-sell).
PAY_TYPE Optional

Preselected payment method for the order. The parameter can be used in both modules, "Shopping Cart" or "Checkout". By default, if the parameter is missing, the default payment method for the order is assumed to be Credit/debit card (Visa/MasterCard). 
Possible values are:

  • ALIPAY - 支付宝 (Alipay)
  • BOLETO - Boleto/Pix
  • CARTE_BLEUE - Carte Bleue
  • CCAMEX - American Express
  • CCDINERS - Diners Club
  • CCJCB - JCB
  • CCVISAMC - Visa/MasterCard/Eurocard
  • CHECK - Check
  • DIRECT_DEBIT - Direct Debit
  • DIRECT_EBANKING - DIRECTebanking.com
  • DISCOVER - Discover/Novus
  • FAX - Fax
  • FREE - Payment not required
  • IDEAL - iDEAL
  • PAYNEARME - Pay cash at 7-Eleven
  • PAYPAL - PayPal
  • PURCHASE_ORDER - Purchase order
  • SOLO - Solo (Discontinued)
  • TRIALPAY - TrialPay Checkout
  • VENDOR2VENDOR - Vendor to vendor
  • WE_CHAT_PAY - WeChat Pay
  • WIRE - Bank/Wire transfer
LANG Optional Selected language for order processing interface and emails. The parameter can be used in both modules, "Shopping Cart" or "Checkout". By default, if the parameter is missing, the used language is assumed to be English. All possible values for this moment are listed in the table below.
LANGUAGES Optional

This parameter sets the order interface language. 

  • ar العربية Arabic
  • bg български език Bulgarian
  • cs Česky Czech
  • da Dansk Danish
  • de Deutsch German
  • el Ελληνικά Greek
  • en English
  • es Español Spanish
  • fa فارسی Persian
  • fi Suomi Finnish
  • fr Français French
  • he Hebrew עִבְרִית
  • hi Hindi
  • hr Hrvatski jezik Croatian
  • hu Magyar Hungarian
  • it Italiano Italian
  • ja 日本語 Japanese
  • ko 한국어 Korean
  • nl Nederlands Dutch
  • no Norsk Norwegian
  • pl Polski Polish
  • pt Português Portuguese
  • pt-br Português do Brasil Brazilian Portuguese
  • ro Română Romanian
  • ru Русский Russian
  • sk Slovenčina Slovak
  • sl Slovène Slovenian
  • sr Serbian
  • sv Svenska Swedish
  • th ไทย Thai
  • tr Türkçe Turkish
  • zh 中文 Chinese Simplified (Cantonese)
  • zy 繁体中文 Chinese Mandarin Traditional
SRC Optional To identify the source of your sales (which links are performing better), a separate link identifier can be assigned to each link. For instance, if there are two buy-links on your website, one in the product page and another one in the download page, you can track the source page by entering the following parameters: 
SRC=prodpage for the product page or SRC=dldpage for the link on the download page
(dldpage and prodpage are example strings only, you can use any combination). Note: SRC cannot have the value "0".
CHK_CROSS Optional If cross selling products are available in the shopping cart, sending this parameter will check all products in cross-selling. This is only available for shopping cart landing pages
CROSS_SELL Optional

CROSS_SELL[cross_sell_product_ID]=main_product_ID

CROSS_SELL must be used in conjunction with CART=1 in the same buy-link. The presence of the CART=1 parameter in the buy-link is mandatory, otherwise the cross-selling campaign will not be triggered.

Let's assume there's a cross-selling campaign configured between Product A with the following Product ID=1234567, which is the main product, and Product B, the recommended product with Product ID=5566778.

1. Add the main product to cart using its buy-link:

https://secure.2checkout.com/order/checkout.php?PRODS=1234567&CART=1

Add the recommended (cross-sell) product to cart using its link, to which the &CROSS_SELL parameter is added:

https://secure.2checkout.com/order/checkout.php?PRODS=5566778&CART=1
&CROSS_SELL[5566778]=1234567 ​​​​

Result: both the main product and the cross-sell product are added to cart one after the other; any discounts impacting the recommended offering are set accordingly.

2. Build a mixt buy-link with the main and cross-sell product:

https://secure.2checkout.com/order/checkout.php?PRODS=1234567,5566778&QTY=1
&CURRENCY=USD&CROSS_SELL[5566778]=1234567

Result: both the main product and the cross-sell product are added to cart simultaneously; any discounts impacting the recommended offering are set accordingly.

CHK_BCKUP Optional If you have the Backup CD option enabled for your account, sending this parameter will check the Backup CD option available in shopping cart. This is only available for shopping cart landing pages
CHK_DIS Optional If you have the Download Insurance option enabled for your account, sending this parameter will check the Download Insurance option available in shopping cart. This is only available for shopping cart landing pages
CHK_GIFT Optional If you have enabled gift feature for the products available in the shopping cart, sending this parameter will check the option to buy the products as a gift for someone else. This is only available for shopping cart landing pages
SHOPURL Optional Custom URL used for "Back to shopping" link
CURRENCY Optional Preselected billing currency to be used in the transaction. This is the currency used to charge your customers.
DCURRENCY Optional Preselected display currency to be used in the order in order to give an estimate of the cost in the local currency detected by geolocation. See the "Tips & tricks" section below in order to learn about exchange rates used. Display currency can differ than billing currency, and in the shopping cart it's presented to customers in a more prominent position.
DOTEST Optional Set this parameter to 1 to place orders in a test environment. Dummy credit card details are provided so you can test the entire order placing process.
CLEAN_CART Optional Set this parameter to 1 to reset the cart contents or to ALL to reset the cart session. Use this parameter to remove products from the current cart session. Note: CLEAN_CART does remove production options or custom prices from the current cart session. However, it does not delete cookies and cache.
ORDERSTYLE Optional Allows you to set the corresponding template, overriding the default template assigned to the product group. Each template defined in the Interface Templates area of the Control Panel has a unique identifier associated which is visible in the browser address bar when previewing the shopping cart.
AFFILIATE Optional

A valid 2Checkout Affiliate ID that you want to credit the sale to. Affiliate identifiers can be extracted from the Active Relationships area of the Affiliate network, by clicking on names of your affiliates to access their details.

 

In case the value of the parameter is set to 0,  ‘AFFILIATE=0’, and the “Disable Affiliate Parameter” option is disabled in GAP for the vendor account, the platform will not attribute the order to any affiliate, regardless if the affiliate cookie is set.

LICENSE Optional for upgrade links

Is used with upgrade links to trigger the upgrade of a specific subscription, such as in the following example.

https://secure.2checkout.com/order/upgrade.php?LICENSE=1234567, where 1234567 represents the 2Checkout subscription reference.
CUSTOMERID Optional The external customer reference. Aggregate subscriptions under the same Customer account if the products they're associated to are purchased by the same shopper by taking advantage of the CUSTOMERID (case sensitive) parameter added to buy-links.
AV_CUSTOMERID Optional The 2Checkout customer reference. Aggregate subscriptions under the same Customer account if the products they're associated to are purchased by the same shopper by taking advantage of the AV_CUSTOMERID (case sensitive) parameter added to buy-links. The 2Checkout system generates default customer numerical (integer) IDs (AV_CUSTOMERID) automatically for all orders containing products that feature subscriptions. 
PLNKEXP Optional UTC timestamp for link expiration
PLNKID Optional Unique link identifier used to restrict access to the link only to the IP address of the first user that clicks it. 250 chars.
PHASH Required Required HMAC_SHA signature in order to prevent the request from being exploited.
TPERIOD Required (only for trials) Trial period must be at least 7 days. For example enter TPERIOD=7 for a 7-day trial, or TPERIOD=30 for a 30-day evaluation period. Can also be used as TPERIOD1234567=7, with 1234567 representing the product ID.
WS_ORDER Optional (optional) - Use the WS_ORDER parameter to control what website URL is displayed in the email messages customers receive from 2Checkout. 
BACK_REF Optional

Redirect URL. Shopper redirect will only happen after the order is placed successfully (the Thank you page is bypassed completely). 

To use the new URLs their domain needs to be whitelisted in Control Panel. For more information see the Set a redirect URL for default checkout flows documentation.

LAYOUT_TYPE Optional

LAYOUT_TYPE enables you to control which version of the shopping cart is served to shoppers. Possible values:

CLASSIC - the desktop variant of the shopping cart (using LAYOUT_TYPE=CLASSIC will always display the desktop version of the cart even to mobile device users);

MOBILE - 2Checkout mobile cart (using LAYOUT_TYPE=MOBILE will always display the mobile version of the shopping cart, even to users of desktop browsers).

AVGAFFILIATE Optional AVGAFFILIATE=12345 (for an affiliate with the 12345 affiliate ID). By including affiliate ID parameters in redirects to your website, 2Checkout enables you to better monitor the traffic generated by your affiliates. 
UPGRADEPROD Required (only for upgrades) Product to be upgraded to, the form of the product ID
UPGRADEOPT Required (only for upgrades) Options of the product to be upgraded to, in the form of the option code
RENEWAL_SRC Not required (only for subscription renewals)

RENEWAL_SRC is added automatically ONLY to the system-generated manual renewal links sent by 2Checkout to customers via manual renewal notifications (emails). Manual renewal links available in subscription details pages do not include this parameter.

RENEWAL_SRC can be used in conjunction with analytics systems to identify the notification email that acted as the source for customers to manually renew their subscription.

Possible values correspond to the Notification time settings for manual billing emails

  • 30 (30 days before the subscription expiration date)
  • 15 (15 days before the subscription expiration date)
  • 7 (7 days before the subscription expiration date)
  • 1 (1 days before the subscription expiration date)
  • 0 (on the expiration date)
  • 5 (5 days after the subscription expiration date)
  • 15 (15 days after the subscription expiration date)
NODATA Optional Value=1. Use in conjunction with PAY_TYPE=PAYPAL to trigger the Express payments checkout flow with PayPal which will circumvent 2Checkout checkout and redirect customers directly to PayPal. Expected behavior: Shoppers click on a buy-link using the NODATA=1 and PAY_TYPE=PAYPAL parameters, and are redirected to PayPal, rather than be taken to the 2Checkout shopping cart (checkout.php).
DESIGN_TYPE Optional

Value = 1. When DESIGN_TYPE=1 is used in buy-links the parameter changes the layout of the shopping cart template interface, positioning the payment methods selector in a more prominent position, above the billing details area.

Value = 2. When DESIGN_TYPE=2 is used in buy-links customers are redirected to their PayPal account, where they log in and confirm the payment. After payment confirmation, they are redirected to the shopping cart to confirm the billing and delivery data and enter their VAT ID.

We recommend using the DESIGN_TYPE parameter with value 2, as it embeds latest practices for a swift checkout experience.

AUTO_PREFILL Optional

Include AUTO_PREFILL=1 in buy-links for shopping carts.

 

When the AUTO PREFILL feature is active and AUTO_PREFILL=1 used in buy-links, the ZIP code and country pair become the only required aspects of the billing address.

 

Address, City and State details are calculated automatically by the 2Checkout system. The address can miss altogether.

 

Note: Using the AUTO_PREFILL=1 parameter without the feature being enabled for your account will result in shoppers following the classic purchase flow, where all billing address data is mandatory. 

SHORT_FORM Optional Case sensitive. Include SHORT_FORM=1 in buy-links for shopping carts. Use it to streamline the shopping cart by minimizing data entry and providing an optimized ordering experience for customers. Guidance is available here.
UPSELL_DISPLAY_TYPE Optional

Optional parameter used to define the type of up-selling page to include in the buy-links. The parameter is not required for the PHASH calculation.

Available values:

  • 1 = interstitial page
  • 2 = pop-up page
FRAUD_REVIEW Optional

Use this parameter to receive the order's fraud evaluation in the Thank You page. Possible values:

  • 1  = to receive the order fraud score in the Thank You page
  • 0 = default value; it does not trigger the fraud score evaluation.

When fraud status tracking is enabled, check the values returned in the FraudStatus variable from omnitureVars. Possible values:

  • APPROVED for orders with a low fraud risk that passed the fraud screening.
  • DENIED for orders with high score risk that were automatically rejected by the fraud engine.
  • UNDER REVIEW for orders with a high fraud risk that require manual review and approval before the charge can be collected.
  • PENDING for orders that are yet to enter the fraud screening.

Secure 'buy-links'

Use a HMAC_SHA signature to prevent links from being exploited. To calculate the HMAC_SHA signature, you need to build a string from the query parameters of the buy-link prefixed by the length of the sequence of parameters in tandem with the 2Checkout-generated SECRET KEY for your account (view secret key). 

If you're using SHA2, the parameter syntax is PHASH=sha256.[hash_value]. For SHA3, the syntax is PHASH=sha3-265.[hash_value].

PARAMETER DESCRIPTION
PRODS Required. Product IDs for which the order will be processed, separated by comma (,), with no blanks. Example: PRODS=1234567, 1234568.
QTY Required. The number or quantity for each corresponding for corresponding above object, separated by comma (,), with no blanks: Example: QTY=2,1
OPTIONS123456 Optional. List of pricing options codes separated by comma
PRICES[Product ID][Currency] Required parameter to set the price for product default currency. For example, for a product with the 2Checkout product ID: 123456, the currency EUR, and the price 99.99, this parameter would look like: PRICES123456[EUR]=99.99. If not sent for other billing currencies, 2Checkout will convert based on the submitted default price.
PLNKEXP Optional. UTC timestamp for link expiration.
PLNKID Optional. Unique link identifier used to restrict access to the link only to the IP address of the first user that clicks it. 250 chars.
PHASH Required HMAC_SHA signature in order to prevent the request from being exploited. Used when the price of products is specified statically using 'on the fly pricing' and for trials - buy-links will contain the PRICES URL parameter. If the PHASH parameter value is removed or tampered with, the system will return an "Invalid signature or link expired!" error message as long as the PRICES parameter is also used in the link. An "Invalid signature" error is always returned in scenarios in which PHASH is removed from trial links.
BACK_REF

To use the new URLs and replace the Thank you page, their domain needs to be whitelisted in Control Panel. For more information see the Set a redirect URL for default checkout flows documentation.

 

Optional. Used only if SECURE_CART parameter is set to value ‘1’ and represents the URL value in clear/raw/not encoded that is to be hashed.

 

Notes:

  1. The 2Checkout platform will perform this action by default for links generated in the Merchant Control Panel and will generate the PHASH value for you.
  2. Parameter BACK_REF should be used in clear (raw, not coded) in the PHASH calculation (ex: &BACK_REF=http://www.YourCustomRedirectURL.com/), but should be encoded when adding it to the URL (ex: &BACK_REF=http%3A%2F%2Fwww.YourCustomRedirectURL.com%2F).
  3. Parameter SECURE_CART should not be taken into consideration when calculating the PHASH.
     

Example

HTTPS GET request
https://secure.2checkout.com/order/checkout.php?CART=1&PRODS=123456&QTY…
STRING for HMAC_SHA calculation

129PRODS=123456&QTY=1&OPTIONS123456=option1,option2&PRICES123456[EUR]=10&PRICES123456[USD]=11.5&PLNKEXP=1286532283&PLNKID=4A4681F0E5

129 represents the length of the sequence of parameters.

Secret key for this example
_SECRET_KEY_
Resulting HMAC_SHA2 signature*
bfd1096dd441a7907e45671a2bd9c4347700581198c2a61c09543bf97673d78d
Resulting HMAC_SHA3 signature*
ce0bb4dac94589a5f8ba778cd2ec0b3bcfaff7ff68935ddc9204ff152f3c140c

Search methods pagination

Overview

Starting with 2Checkout API 5.0, search methods are including the option of pagination. Pagination has been developed for decreasing the request loading time, while allowing you to better handle the returning responses.

How it works?

Pagination works on all the search methods existing on 2Checkout API 5.0. The default pagination behavior is to display page 1 with 10 results. The maximum number of items displayed on a single page is 200.

Parameters

To use pagination, include the Pagination object inside the search method call, using the parameters below:

Parameters Type/Description
Pagination Object
  Details below.
  Page Int
    Set the number of pages that should be returned.
  Limit Int
    Set a limit for the number of results that should be returned.

Response

The response of search methods that are including pagination will contain a new object, with the following parameters:

Parameters Type/Description
Pagination Object
  Details below
  Page Int
    Set the number of pages that should be returned.
  Limit Int
    Set a limit for the number of results that should be returned.
  Count Int
    Number of total results returned

Sample request

The below PHP sample includes a search method for subscriptions.

<?php

require('PATH_TO_AUTH');

$SubscriptionSearch = new stdClass();
$SubscriptionSearch->CustomerEmail  = 'email@avangate.com';
$SubscriptionSearch->DeliveredCode = null;
$SubscriptionSearch->AvangateCustomerReference = null;
$SubscriptionSearch->ExternalCustomerReference = null;
$SubscriptionSearch->Aggregate = false;
$SubscriptionSearch->SubscriptionEnabled = null; //true false null
$SubscriptionSearch->RecurringEnabled = null; // true - autorenewal, false - manual renewal, null = both(default)
$SubscriptionSearch->ProductCodes = null; //array('Product_Code1', 'Product_Code2');
$SubscriptionSearch->CountryCodes = null;//array ('au')
$SubscriptionSearch->PurchasedAfter = null;
$SubscriptionSearch->PurchasedBefore = null;
$SubscriptionSearch->ExpireAfter = null;
$SubscriptionSearch->ExpireBefore = null;
$SubscriptionSearch->LifetimeSubscription = null;
$SubscriptionSearch->Type = 'regular'; //'trial', 'regular', 'regularfromtrial'
$SubscriptionSearch->TestSubscription = null; // true, false, null = both(default)
$SubscriptionSearch->Pagination = new stdClass();
$SubscriptionSearch->Pagination->Page = 1; // set the number of pages for the response
$SubscriptionSearch->Pagination->Limit = 200; // set the limit for the values from the response

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

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


Add sources

Overview

Use the addPromotionSources method to define new sources for an existing promotion.

Parameters

Parameter Type/Description

sessionID

Required (string)

 

Output of the Login method.

promotionCode

Required (string)

 

The code corresponding to the promotion that you want to add products to.

promotionSources

Required (string array)

 

Array of strings defining the promotion sources.

Response

Parameter Type/Description

promotionSources

String array

 

Array of strings defining the promotion sources.

Request

<?php

require ('PATH_TO_AUTH');

// Promotion code corresponding to the promotion you want to add sources to
$promotionCode = '';

// Sources array with the source values 
$sources = ['source1', 'source2'];

$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'addPromotionSources',
'params' => array($sessionID, $promotionCode, $sources)
);
var_dump (callRPC($jsonRpcRequest, $host));

Add product

Overview

Use the addProduct method to create subscription plans/products for your 2Checkout account. 

Request Parameters

Parameters Type Required/Optional Description

sessionID

String

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

Product

Object

Required

Use this object to configure your subscription plans/products.

 

You can set all Product parameters except AvangateID and GroupName. The 2Checkout system sets the unique product ID. The AvangateID and GroupName are not editable.

Request Example

<?php
declare(strict_types=1);
class Configuration
{
    public const MERCHANT_CODE = '';
    public const MERCHANT_KEY = '';
    public const URL = 'http://api.2checkout.com/rpc/6.0';
    public const ACTION = 'addProduct';
    public const ADDITIONAL_OPTIONS = null;
    //array or JSON
    public const PAYLOAD = <<<JSON
{
  "Enabled": true,
  "GeneratesSubscription": true,
  "GiftOption": false,
  "LongDescription": "Some long description",
  "ProductCode": "API_Imported_Product_122",
  "ProductGroupCode": "9652CDA441",
  "TaxCategory": "5db74b57-98a5-4fc1-b559-aee8eba3f046",
  "Platforms": [
    {
      "Category": "Mobile",
      "IdPlatform": "23",
      "PlatformName": "Android"
    },
    {
      "Category": "Mobile",
      "IdPlatform": "20",
      "PlatformName": "iPhone"
    },
    {
      "Category": "Desktop",
      "IdPlatform": "32",
      "PlatformName": "Windows 10"
    }
  ],
  "Prices": [],
  "PricingConfigurations": [
    {
      "BillingCountries": [],
      "Code": "54DCBC3DC8",
      "Default": true,
      "DefaultCurrency": "USD",
      "Name": "2Checkout Subscription's Price Configuration Marius",
      "PriceOptions": [
        {
          "Code": "SUPPORT",
          "Required": true
        },
        {
          "Code": "USERS",
          "Required": true
        },
        {
          "Code": "BACKUP",
          "Required": false
        }
      ],
      "PriceType": "NET",
      "Prices": {
        "Regular": [
          {
            "Amount": 99,
            "Currency": "USD",
            "MaxQuantity": "99999",
            "MinQuantity": "1",
            "OptionCodes": []
          },
          {
            "Amount": 0,
            "Currency": "EUR",
            "MaxQuantity": "99999",
            "MinQuantity": "1",
            "OptionCodes": []
          }
        ],
        "Renewal": []
      },
      "PricingSchema": "DYNAMIC"
    }
  ],
  "ProductCategory": "Audio & Video",
  "ProductImages": [
    {
      "Default": true,
      "URL": "https://store.avancart.com/images/merchant/ef0b9a69f90b1ab0228784ccc7d52136/products/box-2.jpg"
    }
  ],
  "ProductName": "Product Name 01",
  "ProductType": "REGULAR",
  "ProductVersion": "1.0",
  "PurchaseMultipleUnits": true,

  "ShortDescription": "some short description",
  "SubscriptionInformation": {
    "BillingCycle": "1",
    "BillingCycleUnits": "M",
    "BundleRenewalManagement": "GLOBAL",
    "ContractPeriod": {
      "Action": "RESTART",
      "EmailsDuringContract": true,
      "IsUnlimited": true,
      "Period": -1
    },
    "DeprecatedProducts": [],
    "GracePeriod": {
      "IsUnlimited": false,
      "Period": "7",
      "PeriodUnits": "D",
      "Type": "CUSTOM"
    },
    "IsOneTimeFee": false,
    "RenewalEmails": {
      "Settings": {
        "AutomaticRenewal": {
          "After15Days": false,
          "After5Days": false,
          "Before15Days": false,
          "Before1Day": false,
          "Before30Days": false,
          "Before7Days": true,
          "OnExpirationDate": true
        },
        "ManualRenewal": {
          "After15Days": false,
          "After5Days": false,
          "Before15Days": false,
          "Before1Day": false,
          "Before30Days": false,
          "Before7Days": true,
          "OnExpirationDate": true
        }
      },
      "Type": "CUSTOM"
    },
    "UsageBilling": 0
  },
  "SystemRequirements": "",
  "Translations": [
    {
      "Description": "some description",
      "Language": "ZH",
      "LongDescription": "some long description",
      "Name": "some name"
    }
  ],
  "TrialDescription": "",
  "TrialUrl": ""
}
JSON;
}
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, $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, array('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

bool(true)

 

Global eCommerce strategies in local markets

Looking to expand your business in new regions? Our localization experts have prepared a new whitepaper to help with your international strategies, specifically designed to provide insight into globalization requirements.

The best markets to target, both developed and emerging, are scrutinized, along with the importance of local payment methods. A set of best practices for your localization strategy is provided in concert with additional details related to issues such as taxation and local support.

This report provides recommendations that help eCommerce/Sales /Marketing VPs with their international strategies.

Download now and receive your complimentary copy of the "Global eCommerce Strategies in Key Local Markets for Software and SaaS Companies" whitepaper from 2Checkout. Find out the key things you need to know when planning to expand into new local markets

logo-global-ecommerce.png

.

Search leads

Overview

Use the searchLeads method to retrieve leads created in the 2Checkout system.

Request Parameters

Parameters Required Type/Description
Page Required String. The page in the result set.
Limit Required Number. The number of items to be retrieved on each page.

Request Example

<?php

require ('PATH_TO_AUTH');

$LeadSearchInput = new stdClass();

$LeadSearchInput->Type = "New";
$LeadSearchInput->Language = "BG";
$LeadSearchInput->Country = "RO";
$LeadSearchInput->Page = 1;
$LeadSearchInput->Limit = 200;

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

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

Response Parameters

Response Example

class stdClass#4 (2) {
  public $Items =>
  class stdClass#5 (1) {
    public $0 =>
    class stdClass#6 (14) {
      public $LeadCode =>
      string(10) "60E6C4B574"
      public $GeneratedFrom =>
      string(3) "API"
      public $CartId =>
      string(11) "CartIdValue"
      public $Currency =>
      string(3) "EUR"
      public $Language =>
      string(2) "BG"
      public $ExternalReference =>
      string(18) "REST_API_3CHECKOUT"
      public $MachineId =>
      string(6) "123asd"
      public $LocalTime =>
      string(19) "2019-11-05 16:48:28"
      public $Items =>
      class stdClass#7 (1) {
        public $0 =>
        class stdClass#8 (15) {
          public $Code =>
          string(10) "04C26C50F8"
          public $Quantity =>
          string(1) "2"
          public $SKU =>
          NULL
          public $Name =>
          string(5) "softy"
          public $Description =>
          NULL
          public $IsDynamic =>
          bool(false)
          public $Tangible =>
          bool(false)
          public $PurchaseType =>
          string(7) "PRODUCT"
          public $PriceOptions =>
          NULL
          public $RecurringOptions =>
          class stdClass#9 (5) {
            public $CycleLength =>
            NULL
            public $CycleUnit =>
            NULL
            public $CycleAmount =>
            NULL
            public $ContractLength =>
            NULL
            public $ContractUnit =>
            NULL
          }
          public $RenewalInformation =>
          class stdClass#10 (1) {
            public $SubscriptionReference =>
            NULL
          }
          public $MarketingCampaigns =>
          class stdClass#11 (3) {
            public $Type =>
            string(2) "23"
            public $ParentCode =>
            string(1) "m"
            public $CampaignCode =>
            string(2) "23"
          }
          public $Price =>
          class stdClass#12 (2) {
            public $Amount =>
            string(2) "20"
            public $Type =>
            string(6) "CUSTOM"
          }
          public $AdditionalFields =>
          NULL
          public $SubscriptionStartDate =>
          string(19) "2019-11-05 16:48:28"
        }
      }
      public $BillingDetails =>
      class stdClass#13 (12) {
        public $FirstName =>
        string(8) "Customer"
        public $LastName =>
        string(9) "2Checkout"
        public $Phone =>
        NULL
        public $Company =>
        NULL
        public $FiscalCode =>
        string(8) "32423423"
        public $Email =>
        string(22) "customer@2checkout.com"
        public $Address1 =>
        string(12) "Test Address"
        public $Address2 =>
        NULL
        public $City =>
        string(2) "LA"
        public $Zip =>
        string(5) "12345"
        public $CountryCode =>
        string(2) "RO"
        public $State =>
        string(2) "CA"
      }
      public $DeliveryDetails =>
      class stdClass#14 (12) {
        public $FirstName =>
        string(8) "Customer"
        public $LastName =>
        string(9) "2Checkout"
        public $Phone =>
        NULL
        public $Company =>
        NULL
        public $FiscalCode =>
        string(8) "32423423"
        public $Email =>
        string(22) "customer@2checkout.com"
        public $Address1 =>
        string(12) "Test Address"
        public $Address2 =>
        NULL
        public $City =>
        string(2) "LA"
        public $Zip =>
        string(5) "12345"
        public $CountryCode =>
        string(2) "RO"
        public $State =>
        string(2) "CA"
      }
      public $DeliveryInformation =>
      class stdClass#15 (1) {
        public $ShippingMethod =>
        class stdClass#16 (1) {
          public $Code =>
          string(5) "sdfsd"
        }
      }
      public $PaymentDetails =>
      class stdClass#17 (4) {
        public $Type =>
        string(2) "CC"
        public $Currency =>
        string(3) "EUR"
        public $PaymentMethod =>
        class stdClass#18 (2) {
          public $RecurringEnabled =>
          bool(false)
          public $CardPayment =>
          class stdClass#19 (1) {
            public $InstallmentsNumber =>
            string(2) "23"
          }
        }
        public $CustomerIP =>
        string(7) "1.2.3.4"
      }
      public $Promotions =>
      array(1) {
        [0] =>
        string(0) ""
      }
    }
  }
  public $Pagination =>
  class stdClass#20 (3) {
    public $Page =>
    int(1)
    public $Limit =>
    int(200)
    public $Count =>
    int(1)
  }
}

3rd Party Apps for the 2checkout Platform

How do I build apps for the 2checkout platform?

  1. Sign-up for a 2Checkout account
  2. Contact 2Checkout with your app proposal. 
  3. 2Checkout reviews your application plan enables 3rd party apps for your account and creates a placeholder for your app. 
  4. 2Checkout supplies you with authentication credentials. 
  5. Build your application, integrate and test it with your account. 
  6. Submit your final application for review. 
  7. 2Checkout evaluates your application. Following the review process, 2Checkout can offer your app to all customers. 

Payments for mobile apps (such as applications hosted in Google Play Store ) are not currently supported.  However, our platform supports in-app integration using the 2Checkout API (you can integrate our shopping cart in your own application).

Installation

Add the following lines of code at the end of the <body> tag.


<script type="text/javascript" src="https://secure.2checkout.com/cpanel/js/third-party-apps/avangate.js"></script>
    <div id="avangate-hero" class="hide"></div>

Authentication

Contact 2Checkout directly to start building applications on top of the 2Checkout platform. 2Checkout supplies you with the public and private authentication keys for your application. 

Access requirements

Application authentication tokens work in tandem with user sessions for 2Checkout accounts. Users need to log into their account for 3rd party applications to have access to their data. Once account users log out, the application token expires and access is removed. By default, authentication tokens expire after one (1) hour.

Permanent authentication token

Contact 2Checkout to enable this functionality for your application. Once enabled, to make the auth token permanent use the 'permanentToken' parameter. This cases token expiration to grow to one (1) year.

Client side

 

1. Include the script from the Installation section in your JavaScript file you to access a global object called avangateCPanel that you can use for all the methods available in the client-side interface.

2. Next, set the PUBLIC_APP_ID and check that the scripts load in your JavaScript file.

 


var app = {
        cPanel  : false,
        appID   : 'PUBLIC_APP_ID',

        init : function()
        {
            this.cPanel = avangateCPanel;
            if (this.cPanel.init(this.appID)) {
                console.log('everything is ready to be used');
            }
        }
    };
    app.init();

3. Check 2Checkout account login by requesting the auth token via JavaScript.


    var app = {
        cPanel  : false,
        appID   : 'PUBLIC_APP_ID',

        init : function()
        {
            this.cPanel = avangateCPanel;
            if (this.cPanel.init(this.appID)) {
                console.log('everything is ready to be used');
                this.checkLogin();
            }
        },
        checkLogin : function()
        {
            this.cPanel.authentify({
                success: function(response) {
                    var authToken = response.value.authToken;
                },
                error: function(response) {
                    console.log(response.message); // something went wrong
                }
            });
        }
    };
    app.init();
 
4. Send the authToken to your server for validation.
 

var app = {
        cPanel  : false,
        appID   : 'PUBLIC_APP_ID',

        init : function()
        {
            this.cPanel = avangateCPanel;
            if (this.cPanel.init(this.appID)) {
                console.log('everything is ready to be used');
                this.checkLogin();
            }
        },
        checkLogin : function()
        {
            this.cPanel.authentify({
                success: function(response) {
                    var authToken = response.value.authToken; // object {authToken: 'the auth token string', expirationDate: 'the expiration date of the token'}
                    $.when(
                        $http('/validateToken').post(authToken)
                    ).then(
                        function() { //success
                            //user is logged
                        },
                        function() { //fail
                            // check what went wrong in the ajax call
                        }
                    );
                },
                error: function(response) {
                    console.log(response.message); // something went wrong
                }
            });
        }
    };
    app.init();
 

Server side

This example uses Laravel framework and Guzzle Http library


namespace App\Http\Controllers;

use Request;
use GuzzleHttp\Client as httpClient;
use App\Http\Controllers\Controller;

class MainController extends Controller {
    protected $authInfo   = false;
    protected $apiBaseUrl = 'https://apps.api.avangate.com/';

    // verifies and validates the auth token received via javascript
    public function validateToken()
    {
        $this->authInfo = [
            'authToken'         => Request::input('authToken'),
            'expirationDate'    => Request::input('expirationDate'),
        ];

        try {
            $httpClient = $this->getHttpClient();
            $response   = $httpClient->put('verify/');
            // to make the auth token permanent just apply the 'permanentToken' param (token expires in 1 year)
            // contact Avangate to enable this functionality for your app
            //$response = $httpClient->put('verify/', ['body' => ['permanentToken' => 1]]);
        } catch (\Exception $e) {
            $response = $e->getResponse();
        }

        return ($response->json() == true);
    }

    // http client configuration
    private function getHttpClient()
    {
        return new httpClient([
            'base_url'  => $this->apiBaseUrl,
            'timeout'  => 2.0,
            'defaults' => [
                'proxy'     => '',
                'verify'    => false,
                'headers'   => [
                    'authToken' => $this->authInfo['authToken'],
                    'secretID'  => env('APP_SECRET'), // your app secret id
                    'Accept'    => 'application/json'
                ]
            ]
        ]);
    }
}

Get logged user info

This example uses Laravel framework and Guzzle Http library

 


namespace App\Http\Controllers;

use Request;
use GuzzleHttp\Client as httpClient;
use App\Http\Controllers\Controller;

class MainController extends Controller {
    protected $authInfo   = false;
    protected $apiBaseUrl = 'https://apps.api.avangate.com/';

    // verifies and validates the auth token received via javascript
    public function validateToken()
    {
        $this->authInfo = [
            'authToken'         => Request::input('authToken'),
            'expirationDate'    => Request::input('expirationDate'),
        ];

        try {
            $httpClient = $this->getHttpClient();
            $response   = $httpClient->put('verify/');
        } catch (\Exception $e) {
            $response = $e->getResponse();
        }

        if ($response->json() == true) {
            $this->getAuthUserInfo();
        }
    }

    /*
        retrieves the logged user info
        return an array with following structure

        [
            'Email'         => (string),
            'FirstName'     => (string),
            'LastName'      => (string),
            'VendorInfo'    => [
                'ClientCode'        => (string),
                'CompanyName'       => (string),
                'CommercialName'    => (string),
                'Homepage'          => (string)
            ]
        ];
    */
    private function getAuthUserInfo()
    {
        try {
            $httpClient = $this->getHttpClient();
            $response   = $httpClient->get('user_info/');
        } catch (\Exception $e) {
            $response = $e->getResponse();
        }

        return $response->json();
    }

    // http client configuration
    private function getHttpClient()
    {
        return new httpClient([
            'base_url'  => $this->apiBaseUrl,
            'timeout'  => 2.0,
            'defaults' => [
                'proxy'     => '',
                'verify'    => false,
                'headers'   => [
                    'authToken' => $this->authInfo['authToken'],
                    'secretID'  => env('APP_SECRET'), // your app secret id
                    'Accept'    => 'application/json'
                ]
            ]
        ]);
    }
}

Get API data

The API documentation can be found here.

This example uses Laravel framework and Guzzle Http library. From the API we will use the retrieve subscriptions method. 


namespace App\Http\Controllers;

use Request;
use GuzzleHttp\Client as httpClient;
use App\Http\Controllers\Controller;

class MainController extends Controller {
    protected $authInfo   = false;
    protected $apiBaseUrl = 'https://apps.api.avangate.com/';

    // verifies and validates the auth token received via javascript
    public function validateToken()
    {
        $this->authInfo = [
            'authToken'         => Request::input('authToken'),
            'expirationDate'    => Request::input('expirationDate'),
        ];

        try {
            $httpClient = $this->getHttpClient();
            $response   = $httpClient->put('verify/');
        } catch (\Exception $e) {
            $response = $e->getResponse();
        }

        if ($response->json() == true) {
            $this->getSubscriptions();
        }
    }

    private function getSubscriptions()
    {
        try {
            $httpClient = $this->getHttpClient();
            $response   = $httpClient->get('subscriptions/');
        } catch (\Exception $e) {
            $response = $e->getResponse();
        }

        return $response->json();
    }

    // http client configuration
    private function getHttpClient()
    {
        return new httpClient([
            'base_url'  => $this->apiBaseUrl,
            'timeout'  => 2.0,
            'defaults' => [
                'proxy'     => '',
                'verify'    => false,
                'headers'   => [
                    'authToken' => $this->authInfo['authToken'],
                    'secretID'  => env('APP_SECRET'), // your app secret id
                    'Accept'    => 'application/json'
                ]
            ]
        ]);
    }
}

Get ISE data

The ISE (Instant Search Order Export) documentation can be found here.

This example uses Laravel framework and Guzzle Http library


namespace App;

use GuzzleHttp\Client as httpClient;
use Illuminate\Support\Facades\Session;

class Order
{
    private function generateQuery($data = [])
    {
        $authInfo       = Session::get('authInfo');
        $queryParams    = [
            //required
            'APP_CREDENTIALS_TOKEN'     => $authInfo['authToken'],
            'APP_CREDENTIALS_SECRET_ID' => env('APP_SECRET'),

            'STARTDATE'                 => '2015-01-21 00:00:00',
            'ENDDATE'                   => '2015-01-21 00:00:00',
            'ORDERSTATUS'               => 'ALL',
            'REQ_DATE'                  => date('YmdHis'),
            'PRODUCT_ID'                => '',
            'COUNTRY_CODE'              => '',
            'FILTER_STRING'             => '',
            'FILTER_FIELD'              => '',
            'HASH'                      => '',

            //optional
            'INCLUDE_DELIVERED_CODES'   => '',
            'INCLUDE_FINANCIAL_DETAILS' => '',
            'INCLUDE_EXCHANGE_RATES'    => '',
            'INCLUDE_PRICING_OPTIONS'   => '',
            'EXPORT_FORMAT'             => 'XML',
        ];

        $queryParams = array_merge($queryParams, $data);

        return $queryParams;
    }

    public function getOrders($searchParams = [])
    {
        if (!is_array($searchParams)) {
            $searchParams = [];
        }

        $queryParams = $this->generateQuery($searchParams);
        try {
            $httpClient = $this->getHttpClient();
            $response   = $httpClient->post('ise/', [
                'body' => $queryParams
            ]);
        } catch (\Exception $e) {
            $response = $e->getResponse();
        }

        if ($response->getBody()->getContents() != '') {
            $response = $response->xml();
            if (isset($response->RESPONSE_MSG)) {
                return ['success' => false, 'message' => (string)$response->RESPONSE_MSG];
            } else {
                return ['success' => true, 'value' => $response->Orders];
            }
        } else {
            return ['success' => false, 'message' => ''];
        }
    }

    private function getHttpClient()
    {
        return new httpClient([
            'base_url'  => 'https://secure.avangate.com/action/',
            'timeout'  => 2.0,
            'defaults' => [
                'proxy'     => '',
                'verify'    => false,
            ]
        ]);
    }
}

Download mock application

This example uses Laravel framework and Guzzle Http library

You can download the app from here.

The app uses an SQLite database for the information and it displays a list of items only if is a valid authentication session in the 2checkout Control Panel.

Download documentation and mock application 

Click here to download the full documentation, including the mock application, as an archive that you can unpack and run locally.

Accounting activity

Overview

The Accounting menu provides an easy way of keeping tabs on your 2Checkout account's financial activity.

Availability

All 2Checkout accounts. 

Metrics

The Account status section gives you an overview of the following metrics:

  • Net sales = due payments that 2Checkout will pay you after all the taxes, fees and commissions are deducted. Net Profit = Quantity * (Unit Price - Unit Discount - Affiliate Commission) - Processing Fee - Total VAT + (DIS Profit - DIS Cost)
  • Service invoices = unpaid charges you incurred for services such as marketing services, chargeback fees.
  • Disputed orders balance = amounts 2Checkout retained for all open chargebacks at the end of the reporting period.
  • Chargeback funds = the chargeback fund is retained by 2Checkout as soon as you sign the contract. 2Checkout uses this fund to settle chargebacks and refunds opened as late as six months after the termination of your 2Checkout contract. Six months after your 2Checkout contract ends, you receive the remaining chargeback fund back into your account.
  • Minimum transfer limits = the minimum payout amount that you must reach before 2Checkout pays you.

View your accounting summary

To get an overview of your payments, go to the Payments sectionThe accounting summary page aggregates financial details about your account. You can see details about the last payment received from 2Checkout and generate reports based on your account's financial activity.

Last payments

The Last payments area shows you the most recent 10 payments that you have received from 2Checkout.

More info

If you want to see detailed information about what the total amount includes, click the More info button at the right side of the table row. Once you expand the row, you can see what the total amount includes.

Export

You can also export detailed transfers lists by clicking the corresponding link.

Run financial activity reports

  1. Use the Filter transactions section to choose the type of transactions to be included in the report. You can select the transaction status, the invoice date, when it was paid and the transaction type.
  2. Once you have finished configuring your filters, click Search. The report is displayed below and it contains 10 results/page. You can extend the displayed results number to 20 results/page.
  3. Click the More info button to see more information about a specific transaction.
  4. You can also download the transaction's invoice in either HTML or XML format, by selecting the desired format from the Actions column.

Payments history

  1. Use the Transfers history tab to run reports on all the payments that you received from 2Checkout. Configure the filters in the Transfer history searchsection and click Search when you're ready to generate the report. The reports include the payment type, date and the amount.
  2. Click the More info button to see more information about a specific payment, such as the payments that are included in it.
  3. Export the report in CSV format by clicking the Export detailed transfers link.

Network cross-sell commissions

  1. The Accounting -> Payments section also provides you information related to the commissions that you have earned from network cross-selling campaigns.
  2. Go to the Network cross-sell commissions tab and use the Payment date and Payment currency filters to generate reports.
  3. Once you have finished configuring your filters, click Search. The report is displayed below and it contains 10 results/page. You can extend the displayed results number to 200 results/page.
  4. Click the More info button to see more information about a specific payment.
  5. Download the full report that includes all payments in CSV format by clicking Export as CSV. Alternately, you can download reports for each payment by clicking the Export detailed transfers link.

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