Skip to main content

Retrieve subscription deal information

Overview

Use the GetDealInfo method to retrieve information about the existing deal on a given subscription as well as what the subscription will look like with the new proposed deal being applied to it.

Request parameters

Parameter name

Type

Required/Optional

Description

Currency

String

Required

The desired output currency.

Language

String Required

The desired output language.

Items

Array

Required

Each item corresponds to a subscription.

Items.DealDate

Datetime

Required

The date when the deal is set to come into effect. Format: YYYY-MM-DD HH:MM:SS.

Items.SubscriptionReference

String

Required

The subscription code.

Items.ProductCode

String

Required

The product code.

Items.Quantity

String

Required

The product quantity.

Items.DealPriceScenario

String

Required

The upgrade scenario to be applied. Must be one of: using_last_order_price, using_last_product_price, price_total, product_price_difference.

Items.DealSubscriptionScenario

String

Required

The scenarion for price calculation. Must be on of: start_new_deal_contract_now, start_new_deal_contract_after_current_cycle.

Items.PriceOptions

Array

Optional

The array of price options.

Items.PriceOptions.Code

String

Required

The price option group code if the group is of interval type or the price option code otherwise.

Items.PriceOptions.Options

Array

Optional

The array of options that belong to this option group.

Items.PriceOptions.Options.Value

String

Required

If the group is of type “scale”, this is a value from the allowed interval, otherwise, this is the option code as defined in Merchant Control Panel under “Unique Code”.

Items.Price

Object

Required

The product price.

Items.Price.Amount

Float

Required

The actual numeric amount.

Items.Price.Type

String

Required

Describes if the price type is catalog or custom. Can be only CUSTOM.

Items.Price.AmountType

String

Required

Describes if the price is NET or GROSS. Can be one of NET, GROSS.

Items.SubscriptionCustomSettings.CycleLength

Int

Required

The length of a single billing cycle.

Items.SubscriptionCustomSettings.CycleUnit

String

Required

The unit of a single billing cycle. Can be one of MONTH, DAY. 

To perform a getDeal call towards a One Time Fee subscription, this value must be -1.

Items.SubscriptionCustomSettings.CycleAmount

Float

Required

The price of a single billing cycle.

Items.SubscriptionCustomSettings.CycleAmountType

String

Required

Describes the price type. Can be one of NET, GROSS.

Items.SubscriptionCustomSettings.ContractLength

Int

Required

The number of billing cycles contained in a single contract. To perform a getDeal call towards a One Time Fee or a Lifetime subscription, this value must be NULL.

BillingDetails

Object

Required

The billing details.

BillingDetails.FirstName

String

Required

The first name.

BillingDetails.LastName

String

Required

The last name.

BillingDetails.CountryCode

String

Required

The country code. Must be one of the seller's associated country codes.

BillingDetails.State

String

Optional

Required only if the business model requires it.

BillingDetails.City

String

Required

The city name.

BillingDetails.Address1

String

Required

The address.

BillingDetails.Zip

String

Required

The zip code.

BillingDetails.Email

String

Required

The email address.

BillingDetails.Phone

String

Required

The phone number.

BillingDetails.Company

String

Required

The company's legal name.

BillingDetails.FiscalCode

String

Required

The fiscal code.

DeliveryDetails

Object

Required

The delivery details.

DeliveryDetails.FirstName

String

Required

The first name.

DeliveryDetails.LastName

String

Required

The last name.

DeliveryDetails.CountryCode

String

Required

The country code. Must be one of the seller's associated country codes.

DeliveryDetails.State

String

Optional

Required only if the business model requires it.

DeliveryDetails.City

String

Required

The city name.

DeliveryDetails.Address1

String

Required

The address.

DeliveryDetails.Zip

String

Required

The zip code.

DeliveryDetails.Email

String

Required

The email address.

DeliveryDetails.Phone

String

Required

The phone number.

DeliveryDetails.Company

String

Required

The company's legal name.

Request sample

<?php
declare(strict_types=1);
class Configuration
{
    public const MERCHANT_CODE = '1234554321';
    public const MERCHANT_KEY = 'D+~=z5R+R4])4D5&p56%';
    public const URL = 'http://api.avangate.local/rpc/6.0';
    public const ACTION = 'getDealInfo';
    //array or JSON
    public const PAYLOAD = <<<JSON
{
  "Currency": "usd",
  "Country": "us",
  "Language": "ro",
  "CustomerIp": "91.220.121.21",
  "Source": "salesforce_cpq",
  "Items": [
    {
      "DealDate": "2021-09-20 23:59:59",
      "SubscriptionReference": "L10RV2QPFZ",
      "ProductCode": "3EGZDNNRQY",
      "Quantity": 10,
      "DealPriceScenario": "using_last_order_price",
      "DealSubscriptionScenario": "prolong1",
      "Price": {
        "Amount": 200,
        "Type": "CUSTOM",
        "AmountType": "NET"
      },
      "SubscriptionCustomSettings": {
        "CycleLength": 1,
        "CycleUnit": "MONTHS",
        "CycleAmount": 10,
        "CycleAmountType": "NET",
        "ContractLength": 12
      }
    }
  ],
  "BillingDetails": {
    "FirstName": "Oscar",
    "LastName": "McMillan",
    "CountryCode": "ro",
    "State": "Ilios",
    "City": "RE",
    "Address1": "4519 Kovar Road",
    "Zip": "645",
    "Email": "o.mcmillan@integrawealth.net",
    "Phone": "6172938133",
    "Company": "Integra Wealth",
    "FiscalCode": "98414321421"
  },
  "DeliveryDetails": {
    "FirstName": "Maria",
    "LastName": "Frederick",
    "CountryCode": "ro",
    "State": "New York",
    "City": "Buffalo",
    "Address1": "2033 Nuzum Court",
    "Zip": "14216",
    "Email": "m.frederick@integrawealth.net",
    "Phone": "7165708136",
    "Company": "Integra Wealth"
  }
}
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 

Parameter name

Type

Description

Currency

String

The currency code of all the returned price values.

DealDueNowPriceNet

Float

The NET amount that needs to be paid.

DealDueNowPriceGross

Float

The GROSS amount that needs to be paid.

DealTaxAmount

Float

The tax amount (DealDueNowPriceGross - DealDueNowPriceNet).

Items

Array

The array of response items, one for each subscription.

Items.SubscriptionReference

String

The subscription code.

Items.DealPriceScenario

String

The provided DealPriceScenario.

Items.DealSubscriptionScenario

String

The provided DealSubscriptionScenario.

Items.DealDate

Datetime

The provided DealDate. Format: YYYY-MM-DD HH:MM:SS.

Items.DealDueNowPriceNet

Float

The NET amount to be paid now.

Items.DealDueNowPriceGross

Float

The GROSS amount to be paid now.

Items.DealTaxAmount

Float

The tax amount.

Items.DealTaxPercent

Int

The percent that the tax amount is covering from the GROSS price.

Items.CurrentInfo

Object

The current subscription information.

Items.CurrentInfo.ProductCode

String

The product code.

Items.CurrentInfo.ProductName

String

The product name.

Items.CurrentInfo.ProductDescription

String

The product description.

Items.CurrentInfo.BillingPriceNet

Float

The NET price of a billing cycle.

Items.CurrentInfo.BillingPriceGross

Float

The GROSS price of a billing cycle.

Items.CurrentInfo.NoOfBillingCycles

Int

The number of billing cycles.

Items.CurrentInfo.CurrentBillingCycle

Int

The current billing cycle number.

Items.CurrentInfo.PayedBillingCycles

Int

The number of paid billing cycles.

Items.CurrentInfo.RemainingBillingCycles

Int

The number of remaining billing cycles.

Items.CurrentInfo.CurrentBillingCycleEndDate

Datetime

The end date of the current billing cycle. Format: YYYY-MM-DD HH:MM:SS.

Items.CurrentInfo.TaxAmount

Float

The tax amount.

Items.CurrentInfo.TaxPercent

Float

The percent that the tax amount is covering from the GROSS price.

Items.CurrentInfo.BillingCyclesFrequency

String

The frequency of a billing cycle for the current subscription as it is now.

Items.CurrentInfo.BillingCycleFrequencyUnit

String

The unit of a billing cycle for the current subscription as it is now.

Can be one of MONTHS, DAYS.

Items.CurrentInfo.ContractLength

Int

The contract length for the current subscription as it is now.

Items.CurrentInfo.ContractLengthUnit

Int

The unit of the contract length for the current subscription as it is now. Can be one of MONTH, DAY.

Items.CurrentInfo.ProductOptions

Array

The array of existing product options.

Items.CurrentInfo.ProductOptions.Code

String

The option group code as defined in the Merchant Control Panel under “Unique Code”.

Items.CurrentInfo.ProductOptions.Value

String

The price option value if the group is of type interval or the price option code as defined in the Merchant Control Panel under “Unique Code” otherwise.

Items.NewDealInfo

Object

The new deal information.

Items.NewDealInfo.ProductCode

String

The product code.

Items.NewDealInfo.ProductName

String

The product name.

Items.NewDealInfo.ProductDescription

String

The product description.

Items.NewDealInfo.BillingPriceNet

Float

The NET price of a billing cycle.

Items.NewDealInfo.BillingPriceGross

Float

The GROSS price of a billing cycle.

Items.NewDealInfo.NoOfBillingCycles

Int

The number of billing cycles.

Items.NewDealInfo.CurrentBillingCycle

Int

The current billing cycle number.

Items.NewDealInfo.PayedBillingCycles

Int

The number of paid billing cycles.

Items.NewDealInfo.RemainingBillingCycles

Int

The number of remaining billing cycles.

Items.NewDealInfo.CurrentBillingCycleEndDate

Datetime

The end date of the current billing cycle. Format: YYYY-MM-DD HH:MM:SS.

Items.NewDealInfo.TaxAmount

Float

The tax amount.

Items.NewDealInfo.TaxPercent

Float

The percent that the tax amount is covering from the GROSS price.

Items.NewDealInfoBillingCyclesFrequency

Int

The frequency of a billing cycle for this subscription following an eventual deal change with the provided Items.SubscriptionCustomSettings. In case of a One Time Fee subscription, this value will be -1.

Items.NewDealInfo.BillingCycleFrequencyUnit

String

The unit of a billing cycle for this subscription following an eventual deal change with the provided Items.SubscriptionCustomSettings. Can be one of MONTH, DAY.

Items.NewDealInfo.ContractLength

Int

The contract length for this subscription following an eventual deal change with the provided Items.SubscriptionCustomSettings. In case of a One Time Fee or Lifetime subscription, this value will be NULL.

Items.NewDealInfo.ContractLengthUnit

String

The unit of the contract length for this subscription following an eventual deal change with the provided Items.SubscriptionCustomSettings. Ca be one of MONTH, DAY.

Items.NewDealInfo.ProductOptions

Array

The array of existing product options.

Items.NewDealInfo.ProductOptions.Code

String

The option group code as it's defined in the Merchant Control Panel under “Unique Code”.

Items.NewDealInfo.ProductOptions.Value

String

The price option value if the group is of type interval or the price option code as defined in the Merchant Control Panel under “Unique Code” otherwise.

Items.TotalsDealInfo

Object

General statistics regarding the subscription.

Items.TotalsDealInfo.DealsNumber

Int

The total number of deals made so far.

Items.TotalsDealInfo.ContractsNumber

Int

The total number of contracts made so far.

Items.TotalsDealInfo.PaidBillingCycles

Int

The number of paid billing cycles.

Items.TotalsDealInfo.ElapsedBillingCycles

Int

The number of elapsed billing cycles.

Error handling

Situation

Error Code

Error Message

Mandatory parameter(s) not provided

MALFORMED_PARAMETER

Currency not provided, Items.SubscriptionReference not provided, Items.Price.Type not provided, ...

DealDate not provided in required format

MALFORMED_PARAMETER

Invalid format provided for Items.DealDate. Format must be Y-m-d H:i:s. Provided: 2021-0920 23:59:59.

DealDate is in the past

MALFORMED_PARAMETER

Deal date 2020-09-20 23:59:59 is in the past.

Subscription not found or not associated with seller

VALIDATION_SUBSCRIPTION_MISSING

Subscription 6D4F1S81EEB not found.

Subscription not active

VALIDATION_SUBSCRIPTION_INACTIVE

Subscription 6D4F181EEB not active.

Product not found or not associated with seller

VALIDATION_PRODUCT_MISSING

Product with code 6A4C23036C not found.

Product not active

VALIDATION_PRODUCT_INACTIVE

Product with code 6A4C23036C not active.

The subscription is not B2B due to no custom renewal settings being found on subscription

VALIDATION_SUBSCRIPTION_NOT_B2B

No custom renewal settings found for subscription 6D4F1S81EEB. This subscription may not be a B2B subscription.

Provided price option groups are not valid price options for provided product

VALIDATION_PRICE_OPTION_MISSING

Some of the provided price options not found!

Provided subscription upgrade scenario not among supported values

VALIDATION_DEAL_SUBSCRIPTION_SCENARIO

Invalid upgrade subscription scenario provided: 'WRONG_SCENARIO'. Must be one of start_new_deal_contract_now, start_new_deal_contract_after_current_cycle.

Provided subscription price scenario not among supported values

VALIDATION_DEAL_PRICE_SCENARIO

Invalid price scenario provided: 'WRONG_SCENARIO'. Must be one of: using_last_order_price, using_last_product_price, price_total, product_price_difference.

Provided subscription price scenario not among supported values

VALIDATION_FISCAL_CODE

<fiscal code validation error>

Invalid billing email provided

VALIDATION_BILLING_DETAILS

Invalid billing email provided.

Provided billing country not among seller supported countries.

VALIDATION_BILLING_DETAILS

Provided billing country not among seller supported countries.

Business model tax calculation type requires that BillingDetails.State be provided.

VALIDATION_BILLING_DETAILS

Business model tax calculation type requires that BillingDetails.State be provided.

Invalid delivery email provided

VALIDATION_DELIVERY_DETAILS

Invalid delivery email provided.

Provided delivery country not among seller supported countries.

VALIDATION_DELIVERY_DETAILS

Provided delivery country not among seller supported countries.

Business model tax calculation type requires that DeliveryDetails.State be provided.

VALIDATION_DELIVERY_DETAILS

Business model tax calculation type requires that DeliveryDetails.State be provided.

Country '{$deliveryCountryCode}' provided in two different business model distributions.

VALIDATION_BUSINESS_MODEL

Country provided in two different business model distributions.

Invalid price type detected for the next renewal price

INTERNAL_ERROR

Internal error

Unexpected error

INTERNAL_ERROR

Internal error

 

Assign additional fields

Overview

Use the assignAdditionalField method to assign additional fields to a product.

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.

FieldCode

Required (string)

 

Field identifier. Alpha-numeric chars, underscores and dashes.

Required

Boolean

 

True or False depending on whether you want make the field mandatory or not.

ProductCode

Required (string)

 

The unique product code that you control, not the system-generated product identifier.

Response

bool(true)

Request

<?php

require ('PATH_TO_AUTH');

$ProductCode = 'YOUR_PRODUCT_CODE';
$FieldCode = 'YOUR_FIELD_CODE';
$Required = true;

$jsonRpcRequest = array(
    'jsonrpc' => '2.0',
    'id' => $i++,
    'method' => 'assignAdditionalField',
    'params' => array(
        $sessionID,
        $FieldCode,        $Required,
        $ProductCode
    )
);
var_dump(callRPC((Object) $jsonRpcRequest, $host));

?>

Retrieve a specific proposal version

Overview

Use the getProposalVersion method via SOAP API 6.0 to retrieve a specific proposal version.

Request Parameters

Parameters Type Required/Optional Description
proposalId String Required The proposal identifier.
proposalVersion Integer Required The proposal version.

Request Sample

<?php
declare(strict_types=1);

class Configuration
{
    public const MERCHANT_CODE = '';
    public const MERCHANT_KEY = '';
    public const URL = 'http://api.2checkout.com/soap/6.0';
    public const ACTION = 'getProposalVersion';
    public const ADDITIONAL_OPTIONS = null;
    public const PROPOSAL_ID = "7ee02473-b60a-415b-90ae-87c6c443f684";
    public const PROPOSAL_VERSION = 3;
    //array or JSON
    public const PAYLOAD = <<<JSON
    {
    }
JSON;
}

class Client
{
    public function call(
        string $url = Configuration::URL,
        $payload = Configuration::PAYLOAD,
        string $action = Configuration::ACTION,
        string $proposalId = Configuration::PROPOSAL_ID,
        int $proposalVersion = Configuration::PROPOSAL_VERSION
    ): ?object {
        if (is_array($payload)) {
            $payload = json_encode($payload);
        }
        if (!empty($payload)) {
            // SoapClient works with objects(StdClass)
            $payload = json_decode($payload);
        }

        $soapClient = $this->getClient($url);
        $sessionId = $this->getSession($soapClient);
        $args = array_filter([$sessionId, $proposalId, $proposalVersion]);

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

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

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

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

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

Response

The getProposalVersion call via SOAP API 6.0 returns the Proposal object.

Generate a Buy-Link using the Default Flows cart

Overview

One of the options to integrate your platform with the 2Checkout systems is to generate a buy-link that you can then apply to the Buy button on your web store. In this article, we will show you how to create a buy-link both for a single product as well as for multiple selections of different products.

Availability

All merchants (on any type of account) can generate a link from the Merchant Control Panel.

Generate a buy-link for one or more products using the default flows 

   Any buy link generated using the MD5 hashing algorithm should be changed to use SHA3/SHA2, as per the Migration guide documentation.

Follow the steps below to generate a buy-link for a single product:

  1. Log in to your 2Checkout account in the Merchant Control Panel.
  2. Navigate to Setup and click on Generate links

generate buy-link_1.png

3. Click on Checkout links and the Default flows cart. Here are the two most popular templates for it:

  • One page checkout without review 
  • One page checkout with review 
  • Learn more about purchase flows/funnels here.

multi-select in generate links.png

4. Select one or more products from the dropdown list.

If you have more than 2000 products in your product catalog in your 2Checkout account, you can perform multiple selections on the Generate links page, which allows you to select more products at a time instead of using individual search. 

generate buy-link_2.png

multi-select in generate links_1.png

5. After selecting your product, a table will open under the selection field, that will allow you to modify the quantity for your product, its additional pricing options, or remove it from your selection.

generate buy-link_3.png

multi-select in generate links_2.png

6. The last step is to click on Generate Link to create your buy-link and place it on the call-to-action button on your online store.  

You can control order interface behavior with the advanced options for checkout.

generate_links_default flows.png

Retrieve SKU details by ID

Overview

Use the getSkuDetails method to retrieve SKU details based on its ID.

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.
skuCode Required (string)
  Unique identifier of the SKU.

Request Example

<?php
require ('PATH_TO_AUTH');

$sku = 'YOUR_SKU_CODE';

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

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

Response Example

{
"PricingConfigurationCode":"{PricingConfigurationCode}",
"ProductCode":"{ProductCode}",
"Currency":"{Currency}",
"PriceOptions":[{PriceOption1},{PriceOption2}],
"PurchaseType":"{PurchaseType}",
"FromQuantity":"{FromQuantity}",
"ToQuantity":"{ToQuantity}"
}

 

Add coupon

Overview

Use the addPromotionCoupon method to add single or multiple coupons to a promotion. Using the addPromotionCoupon for a promotion that is set to apply automatically will change the promotion type to the manual flow, where customers are required to enter the coupon code to receive the discount.

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 coupons to.

promotionCoupon

Required (object)

 

type

Required (string)

 

 

Coupon type. Available values:

  • SINGLE, use in conjunction with Code
  • MULTIPLE, use in conjunction with Codes

 

Code/Codes

Required (string / array of strings)

 

 

Coupon code (for SINGLE) or array of coupon codes (for MULTIPLE).

Response

Parameter Type/Description
promotionCoupon Object

Request

<?php

require ('PATH_TO_AUTH');

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

// Define single coupon object
$promotionCoupon = new stdClass;
$promotionCoupon->Type = 'SINGLE';
$promotionCoupon->Code = 'YOUR_CODE_HERE';

// Define multiple coupon object
$promotionCoupon = new stdClass;
$promotionCoupon->Type = 'MULTIPLE';
$promotionCoupon->Codes = ['YOUR_CODE_1', 'YOUR_CODE_2'];

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

Enable/Disable products

Overview

Use the setProductStatus method to enable / disable products for your account. 

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.

productCode

Required (string)

 

Use this object to configure your subscription plan/products.

 

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

Status

Required (Boolean)

 

True or False, depending on whether you want to enable or disable a subscription plan/product.

Request

<?php

require ('PATH_TO_AUTH');

$productCode = "YourProductCode";

$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'setProductStatus',
'params' => array($sessionID, $productCode, true)
);

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

?>

 

Response

bool(true)

Next renewal price

Overview

Use the methods below to set or retrieve information related to the next renewal price to be charged on a customer's subscription.

 

Add promotion coupon

Overview

Use the addPromotionCoupon method via JSON-RPC API 4.0 to add single or multiple coupons to a 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 coupons to.

promotionCoupon

Required (object)

 

type

Required (string)

 

 

Coupon type. Available values:

  • SINGLE, use in conjunction with Code
  • MULTIPLE, use in conjunction with Codes

 

Code/Codes

Required (string / array of strings)

 

 

Coupon code (for SINGLE) or array of coupon codes (for MULTIPLE).

Response

Parameter Type/Description
promotionCoupon Object

Request

<?php

function callRPC($Request, $host, $Debug = true) {
    $curl = curl_init($host);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    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)) {
        var_dump($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.1/';

$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;

$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);

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

// Define single coupon object
$promotionCoupon = new stdClass;
$promotionCoupon->Type = 'SINGLE';
$promotionCoupon->Code = 'YOUR_CODE_HERE';

// Define multiple coupon object
$promotionCoupon = new stdClass;
$promotionCoupon->Type = 'MULTIPLE';
$promotionCoupon->Codes = ['YOUR_CODE_1', 'YOUR_CODE_2'];

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

API Authentication

Overview

The 2Checkout API requires you to authenticate for any requests. Follow the steps below to learn how to authenticate in order to use the 2Checkout API.

How to authenticate

This is achieved via digest access authentication, using your Merchant Code & Secret Key. These can be found in your 2Checkout Merchant Control Panel, under Integrations → Webhooks & API.

merchant code_secret Key in control panel.png

To authenticate, you must first generate a hash code that will then be used together with your Merchant Code. The string used in the hash function is generated by concatenating the following values (in this order):

  1. Length of your Merchant Code
  2. Merchant Code
  3. Length of the current DateTime formated as Y-m-d H:i:s
  4. Current DateTime 

For example, for Merchant Code “YOURCODE123“ trying to authenticate on 2020-06-18 08:05:46 GMT, the string that needs to be hashed would look like: “11YOURCODE123192020-06-18 08:05:46”.

Once the string has been generated, this needs to be hashed using the SHA algorithm and the Secret Key available in the 2Checkout Merchant Control Panel. 

Hashing algorithms available

Starting with API 6.0, authentication in the API supports the 256-bit variant of each of the two SHA (Secure Hash Algorithm) families, meaning SHA2 and SHA3.

In PHP, this would look like:

$merchantCode = "YOUR_MERCHANT_CODE";  
$key = "YOUR_SECRET_KEY";  

$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');  

$algo = "SHA3-256"; 

$hash = hash_hmac($algo, $string, $key);

Authenticating on REST protocol

Authentication on REST is done via an X-Avangate-Authentication header provided on all requests. The X-Avangate-Authentication header value contains the Merchant Code, request DateTime, and the hash generated above. 

The format of the header is:

X-Avangate-Authentication: code="{MERCHANT_CODE}" date="{REQUEST_DATE_TIME}" hash="{HASH}" algo="{ALGO}"

Once the hash has been generated, this can be used to authenticate on any of the three protocols.

<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 

# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm , $string, $key); 
$payload = ''; 

$ch = curl_init(); 

$headerArray = [ 
"Content-Type: application/json", 
"Accept: application/json", 
"X-Avangate-Authentication: code=\"{$merchantCode}\" date=\"{$date}\" hash=\"{$hash}\" algo=\"{$hashAlgorithm}\"" 
];
 
curl_setopt($ch, CURLOPT_URL, $host); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSLVERSION, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); 

$response = curl_exec($ch);

Authenticating on SOAP protocol

Authentication on SOAP is done via the login method, using the hash generated above. Once the session id is returned by the login method, this will be used in all subsequent API requests.  

A full-working example in PHP for SOAP login looks like:

<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 

# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm, $string, $key); 

try { 
    $sessionID = $client->login($merchantCode, $date, $hash, $hashAlgorithm); 
    print_r($sessionID); 
} catch (SoapFault $e) { 
    echo $e->getMessage(); 
} 

Authenticating on RPC protocol

Authentication on RPC is done via the login method, using the hash generated above. Once the session id is returned by the login method, this will be used in all subsequent API requests.

A full-working example in PHP for RPC login looks like:

<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 
 
# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm , $string, $key); 

$i = 1; 
$jsonRpcRequest = new stdClass(); 
$jsonRpcRequest->jsonrpc = '6.0'; 
$jsonRpcRequest->method = 'login'; 
$jsonRpcRequest->params =[$merchantCode, $date, $hash, $hashAlgorithm]; 
$jsonRpcRequest->id = $i++; 
$sessionID = callRPC($jsonRpcRequest, $host);

SHA Algorithm

Generating the hash needed to authenticate using SHA-2 or SHA-3 is similar to using MD5, with the note that in the list of parameters, the hashing algorithm must be specified (the last parameter in the list). 

REST Example

<?php
$merchantCode = "YOURCODE123";
$key = "SECRET_KEY";

$apiVersion = '6.0';
$resource = 'leads';
$host = "https://api.2checkout.com/rest/".$apiVersion."/".$resource."/"; 

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

$ch = curl_init();

$headerArray = array( 
    "Content-Type: application/json", 
    "Accept: application/json", 
    "X-Avangate-Authentication: code=\"{$merchantCode}\" date=\"{$date}\" hash=\"{$hash}\" algo=\"{$algo}\"" 
);

curl_setopt($ch, CURLOPT_URL, $host); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSLVERSION, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); 
 
$response = curl_exec($ch); 

SOAP Example

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

$merchantCode = "YOURCODE123";
$key = "SECRET_KEY";
$now = gmdate('Y-m-d H:i:s');

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

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

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

JSON-RPC Example

<?php 
$host = 'https://api.2checkout.com/rpc/6.0/'; 

function callRPC($Request, $host, $Debug = true) { 
    $curl = curl_init($host); 
    curl_setopt($curl, CURLOPT_POST, 1); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($curl, CURLOPT_VERBOSE, true); 
    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)) { 
        var_dump($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; 
    }
}

$merchantCode = "YOURCODE123";  
$key = "SECRET_KEY";  
$date = gmdate('Y-m-d H:i:s'); 

$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 
$hash = hash_hmac($algo, $string, $key); 

$i = 1;

$jsonRpcRequest = new stdClass(); 
$jsonRpcRequest->jsonrpc = '2.0'; 
$jsonRpcRequest->method = 'login'; 
$jsonRpcRequest->params = array($merchantCode, $date, $hash, $algo); 
$jsonRpcRequest->id = $i++;


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

Integration test cases

Testing your integration should be straightforward:

  • For SOAP and JSON-RPC, run a request on the login method and check if you are getting a successful result with an alphanumeric session id.
  • For REST, run a GET call or search request against a simple resource like payouts or leads. While the result may be empty if you do not have any activity yet, the HTTP response should be 200 OK, letting you know that the authentication was successful.

Testing your API with Postman

   You can test your API using Postman only with the SHA256 version of the algorithm, as Postman does not support SHA3.

Postman example

Postman 2 example

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