Create price option groups
Overview
Use the addPriceOptionGroup method to create price option groups for your subscription plans/products.
- Send options for each pricing group or 2Checkout throws an exception.
- When adding an interval with no min/max values or overlapping values, 2Checkout throws an exception.
Parameters
sessionID |
Required (string) |
|
Session identifier, the output of the Login method. Include sessionID into all your requests. 2Checkout throws an exception if the values are incorrect. The sessionID expires in 10 minutes. |
PriceOptionsGroup |
Required (object) |
|
Use this object to create a new price option group for your account. |
Response
bool(true)
Request
<?php
$host = "https://api.avangate.com";
$client = new SoapClient($host . "/soap/4.0/?wsdl", array(
'location' => $host . "/soap/4.0/",
"stream_context" => stream_context_create(array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false
)
))
));
function hmac($key, $data)
{
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*", md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack("H*", md5($k_ipad . $data)));
}
$merchantCode = "YOURCODE123"; //your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "SECRET_KEY"; //your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$now = gmdate('Y-m-d H:i:s'); //date_default_timezone_set('UTC')
$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash = hmac($key, $string);
try {
$sessionID = $client->login($merchantCode, $now, $hash);
}
catch (SoapFault $e) {
echo "Authentication: " . $e->getMessage();
exit;
}
$PriceOptionGroup = new stdClass();
$PriceOptionGroup->Name = 'New Multi Users';
$PriceOptionGroup->Description = 'Quos aut ipsam ipsum omnis aut molestiae. Et quod molestias distinctio. Fugiat sit asperiores reprehenderit officia eaque quae quia. Aperiam quia quia illo eos nesciunt accusamus.';
$PriceOptionGroup->Translations = array();
$PriceOptionGroup->Translations[0] = new stdClass();
$PriceOptionGroup->Translations[0]->Name = 'xdrki7ljix';
$PriceOptionGroup->Translations[0]->Description = 'Beatae doloribus ipsam voluptatem et. Iure dignissimos non amet. Quibusdam fugiat dolor repudiandae temporibus harum.';
$PriceOptionGroup->Translations[0]->Language = 'en';
$PriceOptionGroup->Translations[1] = new stdClass();
$PriceOptionGroup->Translations[1]->Name = '37wr8ie2dj';
$PriceOptionGroup->Translations[1]->Description = 'Esse distinctio voluptatibus omnis et et quia dolor. Quibusdam dicta dolores odio consequatur velit voluptate. Laboriosam reiciendis libero vel quae molestiae ad.';
$PriceOptionGroup->Translations[1]->Language = 'ru';
$PriceOptionGroup->Type = 'RADIO';
$PriceOptionGroup->Options = array();
$PriceOptionGroup->Options[0] = new stdClass();
$PriceOptionGroup->Options[0]->Name = 'SingleUser';
$PriceOptionGroup->Options[0]->Description = 'Nisi ea autem a labore similique. Minus natus cumque nemo. Aut aliquam laboriosam dolorem ad.';
$PriceOptionGroup->Options[0]->Translations = array();
$PriceOptionGroup->Options[0]->Translations[0] = new stdClass();
$PriceOptionGroup->Options[0]->Translations[0]->Name = '0q2r3kcj0q';
$PriceOptionGroup->Options[0]->Translations[0]->Description = 'Voluptatem in vitae rerum ea tempore. Non cumque ullam optio quis. Laborum maxime sunt facere. Dolor fugit a fugiat quasi facere totam.';
$PriceOptionGroup->Options[0]->Translations[0]->Language = 'en';
$PriceOptionGroup->Options[0]->Translations[1] = new stdClass();
$PriceOptionGroup->Options[0]->Translations[1]->Name = 'dwfxuw4lrn';
$PriceOptionGroup->Options[0]->Translations[1]->Description = 'Debitis omnis maiores quia praesentium totam error corrupti. Consectetur eum magnam quam vero. Sit aperiam natus perspiciatis iusto sint ut fugit. Adipisci illum non voluptatem voluptas.';
$PriceOptionGroup->Options[0]->Translations[1]->Language = 'it';
$PriceOptionGroup->Options[0]->Code = 'singleuser1';
$PriceOptionGroup->Options[0]->SubscriptionImpact = new stdClass();
$PriceOptionGroup->Options[0]->SubscriptionImpact->Impact = 'Add';
$PriceOptionGroup->Options[0]->SubscriptionImpact->Months = 1;
$PriceOptionGroup->Options[0]->PriceImpact = new stdClass();
$PriceOptionGroup->Options[0]->PriceImpact->Method = 'FIXED';
$PriceOptionGroup->Options[0]->PriceImpact->Amounts = array();
$PriceOptionGroup->Options[0]->PriceImpact->Amounts[0] = new stdClass();
$PriceOptionGroup->Options[0]->PriceImpact->Amounts[0]->Currency = 'USD';
$PriceOptionGroup->Options[0]->PriceImpact->Amounts[0]->Amount = 90.61;
$PriceOptionGroup->Options[0]->PriceImpact->Amounts[1] = new stdClass();
$PriceOptionGroup->Options[0]->PriceImpact->Amounts[1]->Currency = 'EUR';
$PriceOptionGroup->Options[0]->PriceImpact->Amounts[1]->Amount = 6.70;
$PriceOptionGroup->Options[0]->PriceImpact->ImpactOn = 'BASE';
$PriceOptionGroup->Options[0]->PriceImpact->Impact = 'ADD';
$PriceOptionGroup->Options[0]->PriceImpact->Percent = 39;
$PriceOptionGroup->Options[0]->Default = false;
$PriceOptionGroup->Options[1] = new stdClass();
$PriceOptionGroup->Options[1]->Name = 'MultiUser';
$PriceOptionGroup->Options[1]->Description = 'Vero voluptatum fuga et repellendus sed qui. Dolores molestiae error non ad aperiam. In error quos eum quas repudiandae pariatur et suscipit.';
$PriceOptionGroup->Options[1]->Translations = array();
$PriceOptionGroup->Options[1]->Translations[0] = new stdClass();
$PriceOptionGroup->Options[1]->Translations[0]->Name = 'MultiUser';
$PriceOptionGroup->Options[1]->Translations[0]->Description = 'Debitis et saepe facere blanditiis. Tempore et nemo aut ullam possimus ipsum nisi. Ad libero et consequuntur aliquam libero. Rerum aut illum eveniet earum.';
$PriceOptionGroup->Options[1]->Translations[0]->Language = 'en';
$PriceOptionGroup->Options[1]->Translations[1] = new stdClass();
$PriceOptionGroup->Options[1]->Translations[1]->Name = 'dw5zgkcki9';
$PriceOptionGroup->Options[1]->Translations[1]->Description = 'Vel et excepturi veniam. In iusto eveniet pariatur hic labore. Et qui dolorem accusantium molestias iusto.';
$PriceOptionGroup->Options[1]->Translations[1]->Language = 'pt';
$PriceOptionGroup->Options[1]->Code = 'multiuser999';
$PriceOptionGroup->Options[1]->SubscriptionImpact = new stdClass();
$PriceOptionGroup->Options[1]->SubscriptionImpact->Impact = 'ADD';
$PriceOptionGroup->Options[1]->SubscriptionImpact->Months = 2;
$PriceOptionGroup->Options[1]->PriceImpact = new stdClass();
$PriceOptionGroup->Options[1]->PriceImpact->Method = 'FIXED';
$PriceOptionGroup->Options[1]->PriceImpact->Amounts = array();
$PriceOptionGroup->Options[1]->PriceImpact->Amounts[0] = new stdClass();
$PriceOptionGroup->Options[1]->PriceImpact->Amounts[0]->Currency = 'USD';
$PriceOptionGroup->Options[1]->PriceImpact->Amounts[0]->Amount = 65.03;
$PriceOptionGroup->Options[1]->PriceImpact->Amounts[1] = new stdClass();
$PriceOptionGroup->Options[1]->PriceImpact->Amounts[1]->Currency = 'EUR';
$PriceOptionGroup->Options[1]->PriceImpact->Amounts[1]->Amount = 64.58;
$PriceOptionGroup->Options[1]->PriceImpact->ImpactOn = 'BASE';
$PriceOptionGroup->Options[1]->PriceImpact->Impact = 'ADD';
$PriceOptionGroup->Options[1]->PriceImpact->Percent = 51;
$PriceOptionGroup->Options[1]->Default = true;
$PriceOptionGroup->Code = null;
$PriceOptionGroup->Required = false;
try {
$NewPriceOptionGroup = $client->addPriceOptionGroup($sessionID, $PriceOptionGroup);
}
catch (SoapFault $e) {
echo "NewPriceOptionGroup: " . $e->getMessage();
exit;
}
var_dump("NewPriceOptionGroup", $NewPriceOptionGroup);
?>
Pay-per-Usage
Use this option to create and assign PAYPERUSE price options to your portfolio.
For non PAYPERUSAGE cases, the Usage and UsagePricingModel fields are not required.
Request sample with PAYPERUSE
<?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 = 'addPriceOptionGroup';
public const ADDITIONAL_OPTIONS = null;
//array or JSON
public const PAYLOAD = <<<JSON
{
"Type": "INTERVAL",
"Code": "PayPerUsage-CODE",
"Required": false,
"Name": "Pay per usage pricing option group",
"Description": "Test option description",
"Usage": "PAYPERUSAGE",
"UsagePricingModel": "STEPPED",
"Options": [
{
"Code": "9876545678",
"ScaleMin": "1",
"ScaleMax": "9",
"SubscriptionImpact": {
"Months": "0.00",
"Impact": null
},
"PriceImpact": {
"Amounts": {
"USD": {
"Currency": "USD",
"Amount": "1.00"
},
"EUR": {
"Currency": "EUR",
"Amount": "6.00"
}
},
"ImpactOn": null,
"Method": "FIXED",
"Percent": null,
"Impact": null
},
"Default": false,
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Translations": [
{
"Name": "translation_5f90150268bf7",
"Description": "Translation value",
"Language": "RO"
},
{
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Language": "EN"
},
{
"Name": "translation_5f90150268bf9",
"Description": "Translation value",
"Language": "FR"
},
{
"Name": "translation_5f90150268bf5",
"Description": "Translation value",
"Language": "RU"
}
]
},
{
"Code": "98765456789",
"ScaleMin": "10",
"ScaleMax": "19",
"SubscriptionImpact": {
"Months": "0.00",
"Impact": null
},
"PriceImpact": {
"Amounts": {
"USD": {
"Currency": "USD",
"Amount": "1.00"
},
"EUR": {
"Currency": "EUR",
"Amount": "6.00"
}
},
"ImpactOn": null,
"Method": "FIXED",
"Percent": null,
"Impact": null
},
"Default": false,
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Translations": [
{
"Name": "translation_5f90150268bf7",
"Description": "Translation value",
"Language": "RO"
},
{
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Language": "EN"
},
{
"Name": "translation_5f90150268bf9",
"Description": "Translation value",
"Language": "FR"
},
{
"Name": "translation_5f90150268bf5",
"Description": "Translation value",
"Language": "RU"
}
]
}
],
"Translations": [
{
"Name": "Pay per usage pricing option group",
"Description": "Test option description",
"Language": "EN"
}
]
}
JSON;
}
class Client
{
public function call(
string $url = Configuration::URL,
$payload = Configuration::PAYLOAD,
string $action = Configuration::ACTION
): ?object {
if (is_array($payload)) {
$payload = json_encode($payload);
}
if (!empty($payload)) {
// SoapClient works with objects(StdClass)
$payload = json_decode($payload);
}
$soapClient = $this->getClient($url);
$sessionId = $this->getSession($soapClient);
$args = array_filter([$sessionId, $payload]);
return $soapClient->$action(...$args);
}
public function getClient(string $url): SoapClient
{
return new SoapClient(
$url.'?wsdl',
[
'location' => $url,
'cache_wsdl' => WSDL_CACHE_NONE,
]
);
}
public function getSession(SoapClient $client)
{
$date = gmdate('Y-m-d H:i:s');
$merchantCode = Configuration::MERCHANT_CODE;
$key = Configuration::MERCHANT_KEY;
$string = strlen($merchantCode).$merchantCode.strlen($date).$date;
$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);
}
Request sample without PAYPERUSE
<?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 = 'addPriceOptionGroup';
public const ADDITIONAL_OPTIONS = null;
//array or JSON
public const PAYLOAD = <<<JSON
{
"Type": "RADIO",
"Code": "RADIO-CODE",
"Required": false,
"Name": "Radio pricing option group",
"Description": "Test option description",
"Options": [
{
"Code": "9876545678",
"ScaleMin": "1",
"ScaleMax": "9",
"SubscriptionImpact": {
"Months": "0.00",
"Impact": null
},
"PriceImpact": {
"Amounts": {
"USD": {
"Currency": "USD",
"Amount": "1.00"
},
"EUR": {
"Currency": "EUR",
"Amount": "6.00"
}
},
"ImpactOn": null,
"Method": "FIXED",
"Percent": null,
"Impact": null
},
"Default": false,
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Translations": [
{
"Name": "translation_5f90150268bf7",
"Description": "Translation value",
"Language": "RO"
},
{
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Language": "EN"
},
{
"Name": "translation_5f90150268bf9",
"Description": "Translation value",
"Language": "FR"
},
{
"Name": "translation_5f90150268bf5",
"Description": "Translation value",
"Language": "RU"
}
]
},
{
"Code": "98765456789",
"ScaleMin": "10",
"ScaleMax": "19",
"SubscriptionImpact": {
"Months": "0.00",
"Impact": null
},
"PriceImpact": {
"Amounts": {
"USD": {
"Currency": "USD",
"Amount": "1.00"
},
"EUR": {
"Currency": "EUR",
"Amount": "6.00"
}
},
"ImpactOn": null,
"Method": "FIXED",
"Percent": null,
"Impact": null
},
"Default": false,
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Translations": [
{
"Name": "translation_5f90150268bf7",
"Description": "Translation value",
"Language": "RO"
},
{
"Name": "translation_5f90150268bef",
"Description": "Translation value",
"Language": "EN"
},
{
"Name": "translation_5f90150268bf9",
"Description": "Translation value",
"Language": "FR"
},
{
"Name": "translation_5f90150268bf5",
"Description": "Translation value",
"Language": "RU"
}
]
}
],
"Translations": [
{
"Name": "Radio pricing option group",
"Description": "Test option description",
"Language": "EN"
}
]
}
JSON;
}
class Client
{
public function call(
string $url = Configuration::URL,
$payload = Configuration::PAYLOAD,
string $action = Configuration::ACTION
): ?object {
if (is_array($payload)) {
$payload = json_encode($payload);
}
if (!empty($payload)) {
// SoapClient works with objects(StdClass)
$payload = json_decode($payload);
}
$soapClient = $this->getClient($url);
$sessionId = $this->getSession($soapClient);
$args = array_filter([$sessionId, $payload]);
return $soapClient->$action(...$args);
}
public function getClient(string $url): SoapClient
{
return new SoapClient(
$url.'?wsdl',
[
'location' => $url,
'cache_wsdl' => WSDL_CACHE_NONE,
]
);
}
public function getSession(SoapClient $client)
{
$date = gmdate('Y-m-d H:i:s');
$merchantCode = Configuration::MERCHANT_CODE;
$key = Configuration::MERCHANT_KEY;
$string = strlen($merchantCode).$merchantCode.strlen($date).$date;
$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);
}
Subscription renewal notifications
Overview
Use the setRenewalNotificationStatus method to subscribe or unsubscribe shoppers from subscription renewal notifications.
Parameters
Parameters |
Type/Description |
sessionID |
Required (string) |
|
Session identifier, the output of the Login method. Include sessionID into all your requests. Avangate throws an exception if the values are incorrect. The sessionID expires in 10 minutes. |
SubscriptionReference |
Required (string) |
Unique, system-generated subscription identifier. |
|
Status |
Required (boolean) |
|
true – enable subscription renewal notifications. false – disable subscription renewal notifications. |
Response
Boolean |
true or false depending on whether or not the operation succeeded. |
Request
<?php
$host = "https://api.avangate.com";
$client = new SoapClient($host . "/soap/3.0/?wsdl", array(
'location' => $host . "/soap/3.0/",
"stream_context" => stream_context_create(array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false
)
))
));
function hmac($key, $data)
{
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*", md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack("H*", md5($k_ipad . $data)));
}
$merchantCode = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$now = gmdate('Y-m-d H:i:s'); //date_default_timezone_set('UTC')
$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash = hmac($key, $string);
try {
$sessionID = $client->login($merchantCode, $now, $hash);
}
catch (SoapFault $e) {
echo "Authentication: " . $e->getMessage();
exit;
}
$subscriptionReference = '30E47F8699';
$Status = true;
try {
$Notifications = $client->setRenewalNotificationStatus($sessionID, $subscriptionReference, $Status);
}
catch (SoapFault $e) {
echo "Notifications: " . $e->getMessage();
exit;
}
var_dump("Notifications", $Notifications);
Top 10 myths of conversion optimization
Conversion rate optimization can be a humbling experience. You start with a hypothesis (your opinion on how to improve your website) and then run a test to see if you were right or wrong. There aren't too many professions that subject themselves to such quantifiable evaluation. But there is good news for Marketers and eCommerce Managers: "surprising" test results often increase the conversion rate, and if a test does not beat the status quo, you have still learned a valuable insight about your customers. Knowing what moves the needle, and what does not, is the key to increasing revenue consistently quarter over quarter. In this webinar, we explore the most insightful and sometimes surprising test results that often contradicted our idea of a "best practice". Shannon MacLeod, Senior Director of Conversion Optimization at 2Checkout, and Alhan Keser, Director of Optimization Strategy at WiderFunnel
|
![]() |
Unassign a product group
Overview
Use the unassignProductGroup method to unassign a product from a specific product group and assign it to the General product group instead.
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) |
|
The code of the product you wish assigned to the group. |
groupCode | Required (string) |
Unique, system-generated identifier assigned to product groups. |
Response
bool(true)
<?php
require ('PATH_TO_AUTH');
$productCode = "YOUR_PRODUCT_CODE";
$groupCode = "YOUR_PRODUCT_GROUP_CODE";
$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'unassignProductGroup',
'params' => array($sessionID, $productCode, $groupCode)
);
var_dump (callRPC($jsonRpcRequest, $host));
?>
Retrieve a product group
Overview
Use the getProductGroup method to extract information about a specific product group you created 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. |
groupCode | Required (string) |
Unique, system-generated identifier assigned to product groups. |
Response
Parameters | Type/Description |
---|---|
Array of objects |
Request
<?php
require ('PATH_TO_AUTH');
$groupCode = 'YOUR_GROUP_CODE';
$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'getProductGroup',
'params' => array($sessionID, $groupCode)
);
var_dump (callRPC((Object)$jsonRpcRequest, $host));
Mark orders as shipped
Overview
Use markShipped to programmatically confirm the delivery of an order with physical products.
Requirements
You can confirm the shipment only for orders with tangible products. You cannot mark as shipped orders that are no longer authorized (have been reversed).
Parameters
Parameters | Type/Description |
---|---|
RefNo | String / Required |
The system-generated order reference. | |
TrackingNumber | String / Optional |
Tracking number that customers can use for checking the delivery of their products. | |
Comment | String / Optional |
Additional information displayed in the delivery confirmation email sent to end-users. | |
StopCustomerNotification | Boolean / Optional |
Possible values:
|
Request
require('PATH_TO_AUTH');
$RefNo = "789527422";
$TrackingNumber = '921840912';
$StopCustomerNotification = 1;
$Comment = "We send this note to confirm the shipment of your products.";
try {
$markOrderAsShipped = $client->markShipped($sessionID, $RefNo, $TrackingNumber, $StopCustomerNotification, $Comment);
}
catch (SoapFault $e) {
echo "OrderShipped: " . $e->getMessage();
exit;
}
var_dump("OrderShipped", $markOrderAsShipped);
Response
boolean
Search cross-sell campaigns
Overview
Use the searchCrossSellCampaigns call to retrieve information on the cross-sell campaigns currently defined on your account.
Request parameters
Parameters |
Type |
Required |
Description |
---|---|---|---|
CampaignName |
String |
Optional |
The name of the campaign. |
Status |
String |
Optional |
The status of the campaign; can be ACTIVE/INACTIVE. |
Products |
Array of strings |
Optional |
Array of product codes to apply to this campaign. |
RecommendedProducts |
Array of strings |
Optional |
Array of product codes recommended to the shopper. |
StartDate |
String |
Optional |
The date when the cross-sell campaign starts, formatted as YYYY-MM-DD |
EndDate |
String |
Optional |
The date when the cross-sell campaign ends, formatted as YYYY-MM-DD |
Type | String | Optional | Can be MERCH/AFF. |
Pagination |
Object |
Optional |
|
Page |
Int |
Optional |
The page number of the results. |
Limit |
Int |
Optional |
The number of results per page. |
Response
Parameters | Type/Description |
---|---|
Items | An array of CrossSellCampaign Objects |
Pagination | Pagination Object with the following parameters: Page, Limit, Count |
Request sample
<?php
declare(strict_types=1);
// Start clear CLI
echo chr(27).chr(91).'H'.chr(27).chr(91).'J';
// End clear CLI
$executionStartTime = microtime(true);
$apiVersion = '6.0';
$apiHost = "http://api.avangate.local";
$host = $apiHost."/soap/" . $apiVersion . "/";
$client = new SoapClient(
$host."?wsdl",
[
'location' => $host,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE
]
);
$client->__setCookie('XDEBUG_SESSION', 'PHPSTORM');
// Please be aware to consider valid data
$merchantCode = 'your_merchant_code';
$key = 'your_merchant_key';
// Generate hash for login
$date = gmdate('Y-m-d H:i:s');
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
$hash = hash_hmac('md5', $string, $key);
try {
$sessionID = $client->login($merchantCode, $date, $hash);
} catch (SoapFault $e) {
echo $e->getMessage();
}
var_dump("Generated sessionID: ". $sessionID);
echo "\n\r";
// Build search parameters
$searchOptions = new \stdClass();
$searchOptions->Status = ['ACTIVE']; // Optional | Ex: ['ACTIVE']
$searchOptions->Type = null; // Optional | Ex: 'MERCH'
$searchOptions->CampaignName = null; // Optional | Ex: 'UpdatedCampaign_4'
$searchOptions->Products = []; // Optional | Ex: ["a01", "a02"]
$searchOptions->RecommendedProducts = [];// Optional | Ex: ["a03"]
$searchOptions->StartDate = null; // Optional | Ex: 'YYYY-MM-DD'
$searchOptions->EndDate = null; // Optional | Ex: 'YYYY-MM-DD'
$searchOptions->Pagination = null; // Optional | Ex: {"Page": "1", "Limit": "10"}
try {
$result = $client->searchCrossSellCampaigns($sessionID, $searchOptions);
echo "\n\rSEARCH CROSS SELL CAMPAIGNS: \n\r";
print_r(json_encode($result, JSON_PRETTY_PRINT));
} catch (SoapFault $e) {
echo $e->getMessage();
}
$executionEndTime = microtime(true);
// The duration will be displayed in seconds and milliseconds.
$seconds = round($executionEndTime - $executionStartTime, 2);
// Print it out
echo "\n\rThis script took $seconds to execute.\n\r";
Instant Order Search Export (ISE)
Overview
Export order data for your account from the 2Checkout platform.
Instant Order Search Export (ISE) works as a data portability service designed to let you export order information from your 2Checkout account packaged as either CSV or XML files.
Availability
ISE is available to all 2Checkout accounts.
Method and URL
GET or POST: https://secure.2checkout.com/action/ise?
Parameters for eStore orders
2Checkout captures the parameters you send and exports the data to the client.
Field | Description | Required | Used in HASH validation |
---|---|---|---|
MERCHANT | Your 2Checkout merchant code. The merchant code and secret key for your account are available here. | Required, cannot be empty | YES |
STARTDATE | The start date, in format Y-m-d (ex: 2010-05-22) | Required, cannot be empty | YES |
ENDDATE | The end date, in format Y-m-d (ex: 2010-05-22) | Required, cannot be empty | YES |
ORDERSTATUS |
The order status:
|
Required, cannot be empty | YES |
REQ_DATE |
The time of request (UTC), in format YmdHis: Y = year, 4 digits m = month, 2 digits d = day, 2 digits H = hour, 2 digits i = minute, 2 digits s = seconds, 2 digits |
Required, cannot be empty | YES |
PRODUCT_ID | Unique, system-generated 2Checkout product identifier | Required, can be empty | YES |
COUNTRY_CODE | Two letter country code (download a complete list from via this link) | Required, can be empty | YES |
FILTER_STRING | Query value that depends on the value of the FILTER_FIELD. See FILTER_FIELD for more info. | Required, can be empty | YES |
FILTER_FIELD |
Filter field designed to lower the search result. Use in conjunction with FILTER_STRING. Possible values:
To search only a particular order, the value of FILTER_FIELD needs to be REFNO, while the value of the FILTER_STRING should be the unique order reference from the 2Checkout system. |
Required, can be empty | YES |
HASH | The SHA256 HMAC key for the request | Required | N/A |
SIGNATURE_ALG | The hashing algorithm used to authenticate the request. To use SHA2 or SHA3 for auth, simply pass sha256 or sha3-256 as value for the SIGNATURE_ALG parameter. | Required | NO |
INCLUDE_DELIVERED_CODES | Includes delivered codes | Optional | NO |
INCLUDE_FINANCIAL_DETAILS | Includes financial details. (Net profit, DIS COST, DIS Profit) | Optional | NO |
INCLUDE_EXCHANGE_RATES | Includes exchange rates | Optional | NO |
INCLUDE_PRICING_OPTIONS | Includes pricing options (pricing option text, pricing options value) | Optional | NO |
EXPORT_FORMAT |
This parameter controls the format of file used for the export process. Possible values:
|
Optional | NO |
INCLUDE_CLIENTIP | Include end user IP address | Optional | NO |
INCLUDE_NETINCOMEPERPRODUCT | Include net income per product | Optional | NO |
USE_REPORT_MODE |
|
Optional | NO |
EXPORT_TEST_ORDERS |
Possible values:
|
Optional | NO |
EXPORT_TEMPLATE_ID |
Return order search information specific to templates configured for Order Search Export by using their unique IDs. For eStore, navigate to Order search under Orders &customers and make sure that the eStore orders tab is selected. Run a search to identify the orders you're looking for, and on the right hand side of the screen click the Export button, and the Edit templates link in the popup dialog box. The template identifier is visible in the URL as the IdTemplate parameter. When using EXPORT_TEMPLATE_ID, you can exclude INCLUDE_DELIVERED_CODES, INCLUDE_FINANCIAL_DETAILS, INCLUDE_EXCHANGE_RATES, INCLUDE_PRICING_OPTIONS, INCLUDE_CLIENTIP and INCLUDE_NETINCOMEPERPRODUCT, if the Order search Export template already contains such information. Data in the Order Search Export template takes precedence over INCLUDE_DELIVERED_CODES, INCLUDE_FINANCIAL_DETAILS, INCLUDE_EXCHANGE_RATES, INCLUDE_PRICING_OPTIONS, INCLUDE_CLIENTIP and INCLUDE_NETINCOMEPERPRODUCT - this means that these parameters are ignored if they overlap with template fields. |
Optional | NO |
INCLUDE_CHARGEBACKS_STATUS_AND_REASON |
Includes the status and reason provided for chargebacks. Available values:
|
Optional | NO |
EXPORT_TIMEZONE_REGION |
Controls the timezone provided in STARTDATE and ENDDATE fields. Example: 'Europe/London'. Check the values accepted as strings here. If not provided, the timezone used is the API timezone set up in Control Panel. If no API timezone is set, the default platform timezone is used. Daylight saving time is considered in the timezone region parameter. |
Optional | NO |
Parameters for Partner orders
Field | Description | Required | Used in HASH validation |
---|---|---|---|
MERCHANT | Your 2Checkout merchant code. The merchant code and secret key for your account are available here. | Required, cannot be empty | YES |
STARTDATE | The start date, in format Y-m-d (ex: 2010-05-22) | Required, cannot be empty | YES |
ENDDATE | The end date, in format Y-m-d (ex: 2010-05-22) | Required, cannot be empty | YES |
ORDERSTATUS |
The order status:
|
Required, cannot be empty | YES |
REQ_DATE |
The time of request (UTC), in format YmdHis: Y = year, 4 digits m = month, 2 digits d = day, 2 digits H = hour, 2 digits i = minute, 2 digits s = seconds, 2 digits |
Required, cannot be empty | YES |
PRODUCT_ID | Unique, system-generated 2Checkout product identifier. | Required, can be empty | YES |
PARTNER_CODE | Partners codes can be viewed by selecting each partner from here. | Required, can be empty. If empty, default is all. Supports multiple codes per message, separated by a comma. | NO |
SUBSCRIPTION_TYPE |
Subscription types:
|
Required, can be empty. If empty, default is all. | NO |
SOURCE |
Source of the partner order:
|
Required, can be empty. If empty, default is all. | NO |
PRICELIST_CODE | Price lists codes can be viewed by selecting each price list from here. | Required, can be empty. | NO |
COUNTRY_CODE | Two letter country code (download a complete list from this link) | Required, can be empty. | YES |
FILTER_STRING | Query value that depends on the value of the FILTER_FIELD. See FILTER_FIELD for more info. | Required, can be empty. | YES |
FILTER_FIELD |
FILTER_FIELD is designed to lower the search result. Use in conjunction with FILTER_STRING. Possible values:
To search only a particular order, the value of FILTER_FIELD needs to be REFNO, while the value of the FILTER_STRING should be the unique order reference from the 2Checkout system. |
Required, can be empty. In conjunction with FILTER_STRING. | YES |
HASH | The SHA256 HMAC key for the request. | Required | N/A |
SIGNATURE_ALG | The hashing algorithm used to authenticate the request. To use SHA2 or SHA3 for auth, simply pass sha256 or sha3-256 as value for the SIGNATURE_ALG parameter. | Required | NO |
EXPORT_FORMAT |
This parameter controls the format of file used for the export process. Possible values:
|
Optional | NO |
USE_REPORT_MODE |
|
Optional | NO |
PARTNER_INVOICE_DATE | The date in format Y-m-d (ex: 2010-05-22). It filters the results and returns orders in accordance with the date when a partner invoice was generated for these orders. | Optional | NO |
EXPORT_TEMPLATE_ID |
Return order search information specific to templates configured for Order Search Export by using their unique IDs. For Partner Orders, navigate to Order search under Orders &customers and make sure that the Partner orders tab is selected. Run a search to identify the orders you're looking for, and on the right hand side of the screen click the Export button, and the Edit templates link in the popup dialog box. The template identifier is visible in the URL as the IdTemplate parameter.
When using EXPORT_TEMPLATE_ID, you can exclude INCLUDE_DELIVERED_CODES, INCLUDE_FINANCIAL_DETAILS, INCLUDE_EXCHANGE_RATES, INCLUDE_PRICING_OPTIONS, INCLUDE_CLIENTIP, and INCLUDE_NETINCOMEPERPRODUCT, if the Order search Export template already contains such information. Data in the Order Search Export template takes precedence over INCLUDE_DELIVERED_CODES, INCLUDE_FINANCIAL_DETAILS, INCLUDE_EXCHANGE_RATES, INCLUDE_PRICING_OPTIONS, INCLUDE_CLIENTIP and INCLUDE_NETINCOMEPERPRODUCT - this means that these parameters are ignored if they overlap with template fields. |
Optional | NO |
CHANNEL_TYPE |
Specifies if the ISE should return eStore orders or Partner orders. Possible values:
|
Optional | NO |
Requirements
HASH validation
- To validate the SHA256 hash signature, you're required to include all mandatory parameters. 2Checkout throws an error if one of these parameters is missing.
- Include PRODUCT_ID and COUNTRY_CODE. Use empty values to return all results.
- The interval between STARTDATE and ENDDATE can not be greater than 45 days (for performance purposes).
- Use UTC for the time zone of REQ_DATE. The difference between the value of REQ_DATE and the moment when you send the request to 2Checkout must be smaller than 5 minutes, or 2Checkout will respond with the 'Request expired' error message.
Authentication
Authenticate requests using:
- HASH. This ia a SHA256 Hash-based message authentication code (HMAC) that you create using your account's secret key and the parameters marked as mandatory for HASH validation. To build the HMACSHA256{} source string, prepend each value with its own length in bytes. Use 0 for null or empty values without prepending their length. However, when the value is 0 (zero), you do need to prepend its length (1). Note that for UTF-8 characters the length in bytes can be longer that the string length.
- REQ_DATE. Use UTC time zone.
Optional: the authentication can be restricted by IP or range of IPs from firewall (Accounts settings ->User access -> Firewall) for the special service user. If the IP from where you make the request is not configured in 2Checkout, the authentication fails.
Response
Provided that your request is valid, you will receive the information in line, in the requested format (parameter EXPORT_FORMAT), with HTTP code 200.
Errors
2Checkout returns errors in XML format. This includes authentication errors and no results after a search message. 2Checkout throws errors with a 400 HTTP error code for the result page. Sample response XML:
<EPAYMENT>
<RESPONSE_CODE>1</RESPONSE_CODE>
<RESPONSE_MSG>Request has expired</RESPONSE_MSG>
<RESPONSE_DATE>20110209144927</RESPONSE_DATE>
<HASH>2f69dda102b2a29e077452f64f4dca1f</HASH>
</EPAYMENT>
The XML can be validated using the same SHA256 HMAC signature algorithm, using these fields: RESPONSE_CODE, RESPONSE_MSG, RESPONSE_DATE and using the account hash key.
Field | Description |
---|---|
RESPONSE_CODE | The response code (two digits) |
RESPONSE_MSG | A more explanatory response message |
RESPONSE_DATE |
The time of response (UTC), in format YmdHis: Y = year, 4 digits m = month, 2 digits d = day, 2 digits H = hour, 2 digits i = minute, 2 digits s = seconds, 2 digits |
Possible error codes and values:
Message code | Message description | Resolution |
---|---|---|
0 | No result found for the searched criteria | Check search filters. |
1 | Request has expired | Check REQ_DATE. |
2 | Not all the mandatory variables are present | See required fields above. |
3 | The selected interval is greater than 45 days | Check STARTDATE and ENDDATE. |
4 | MERCHANT is missing or incorrect | Check MERCHANT value. |
5 | ORDERSTATUS is missing or invalid | Check ORDERSTATUS value. |
6 | Ip not allowed by firewall | Check firewall rules for special service user. |
7 | HASH is missing or invalid | Double check how SHA256 hash signature is calculated. |
8 | REQ_DATE is missing or invalid | REQ_DATE is missing or not in the right format. |
9 | FILTER_FIELD is invalid | Check possible values of FILTER_FIELD. |
10 | FILTER_STRING is missing or invalid | FILTER_FIELD is set to limit search. Check FILTER_STRING value. |
11 | Module is not active for your account | Instant Search Export service is not active for your account. Please contact account manager. |
12 | EXPORT_TEMPLATE_ID is invalid | Check the EXPORT_TEMPLATE_ID value. |
13 | Country code is incorrect. | Provide a valid country code. |
14 | Provided time zone region is incorrect | Check EXPORT_TIMEZONE_REGION value. |
15 | PARTNER_CODE is invalid | Check “Partner code” in View partner section in cPanel. |
16 | PRICELIST_CODE is invalid | Check “Price list code” in Edit price list section in cPanel. |
Code sample for eStore orders
<?php
/*
Name: Example for Instant Search Export in Avangate (www.avangate.com)
GET OR POST SENT
*/
$secret_key = 'SECRET_KEY'; //secret key is available on this page https://secure.2checkout.com/cpanel/account_settings.php
$base_link = 'https://secure.avangate.local/action/ise.php';
$proxy_user = 'PROXY_USER_IF_NEEDED';
$proxy_pass = 'PROXY_PASSWORD_IF_NEEDED';
date_default_timezone_set('UTC');
//*********SETTING PARAMETERS*********
$link_params = array();
$algo = 'sha256'; // or sha3-256
$not_in_hash = array(
'HASH',
'INCLUDE_DELIVERED_CODES',
'INCLUDE_FINANCIAL_DETAILS',
'INCLUDE_EXCHANGE_RATES',
'INCLUDE_PRICING_OPTIONS',
'EXPORT_FORMAT',
'EXPORT_TIMEZONE_REGION',
'SIGNATURE_ALG',
);
//REQUIRED, CANNOT BE EMPTY:
$link_params['MERCHANT'] = 'MALWARQO'; //merchant code is available on this page https://secure.2checkout.com/cpanel/account_settings.php
$link_params['STARTDATE'] = date(
"Y-m-d",
strtotime('-1 month', strtotime(date('Y') . '/' . date('m') . '/01' . ' 00:00:00'))
); //first day from last month
$link_params['ENDDATE'] = date(
"Y-m-d",
strtotime('-1 second', strtotime(date('Y') . '/' . date('m') . '/01' . ' 00:00:00'))
); //last day from last month
$link_params['ORDERSTATUS'] = 'ALL'; // replace with any of ALL, COMPLETE, REFUNDED, UNFINISHED
$link_params['REQ_DATE'] = date('YmdHis');
//CAN BE EMPTY:
$link_params['PRODUCT_ID'] = '';
$link_params['COUNTRY_CODE'] = '';
$link_params['FILTER_STRING'] = '';
$link_params['SIGNATURE_ALG'] = $algo;
//REQUIRED, CAN BE EMPTY:
$link_params['FILTER_FIELD'] = ''; // EMPTY OR: REFNO, REFNOEXT, NAME, EMAIL, COUPONCODE
//REQUIRED:
$link_params['HASH'] = '';
//OPTIONAL:
$link_params['INCLUDE_DELIVERED_CODES'] = '';
$link_params['INCLUDE_FINANCIAL_DETAILS'] = '';
$link_params['INCLUDE_EXCHANGE_RATES'] = '';
$link_params['INCLUDE_PRICING_OPTIONS'] = '';
$link_params['EXPORT_FORMAT'] = 'XML'; //possible values CSV or XML - if you’re using this sample, please specify the desired export format
$link_params['EXPORT_TIMEZONE_REGION'] = 'Europe/London';
//*********GET Base string for HMAC_SHA256 calculation:*********
$result = '';
foreach ($link_params as $key => $val) {
$$key = $val;
/* get values */
if (!in_array($key, $not_in_hash)) {
if (is_array($val)) {
$result .= ArrayExpand($val);
} else {
$size = strlen(StripSlashes($val));
$result .= $size . StripSlashes($val);
}
}
}
//*********Calculated HMAC_SHA256 signature:*********
$hash = hash_hmac($algo, $result, $secret_key);
$link_params['HASH'] = $hash;
$get_vars = http_build_query($link_params, '', '&');
//*********MAKE POST CALL to get ISE results*********
$ch = curl_init($base_link . '?' . $get_vars);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//**use the following 3 lines only if you have a proxy set!**
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
//curl_setopt($ch, CURLOPT_PROXY, 'YOUR_PROXY_ADDRESS:PORT');
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user.':'.$proxy_pass);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN THE CONTENTS OF THE CALL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$responseData = curl_exec($ch);
$headerCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
//echo 'Curl error: '.curl_error($ch);
curl_close($ch);
//*********PROCESS RESULTS*********
if ($headerCode == 200) {
// do something with the csv or xml received
//the format of the export file is set using $link_params['EXPORT_FORMAT']
$exportType = strtolower($link_params['EXPORT_FORMAT']);
$headerType = 'Content-type: application/' . $exportType . ';charset=UTF-8';
$headerDisposition = 'Content-Disposition: attachment; filename="ise.' . $exportType . '"';
header($headerType);
header($headerDisposition);
echo $responseData;
} else {
//no valid answer received: request period is too big, etc.
if (strpos($contentType, 'xml') === false) {
echo 'Header returned: ' . $headerCode;
echo $responseData;
} else {
//YOUR CODE HERE AFTER RECEIVING the xml with one of the codes from Instant Search Export Handbook
$xml = $responseData;
$xml = simplexml_load_string($xml);
$response = array();
$i = 0;
foreach ($xml->children() as $child) {
$response[$i] = $child;
$i++;
}
echo $xml->asXML();
}
}
//*********FUNCTIONS FOR HMAC*********
function ArrayExpand($array)
{
$retval = "";
foreach ($array as $i => $value) {
if (is_array($value)) {
$retval .= ArrayExpand($value);
} else {
$size = strlen(StripSlashes($value));
$retval .= $size . StripSlashes($value);
}
}
return $retval;
}
Add products to a promotion
Overview
Use addPromotionProducts to add products to 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. |
|
promotionProducts |
Required (object) |
|
|
Code |
Required (string) |
|
|
System generated product code. |
|
pricingConfigurationCode |
Optional (string) |
|
|
System generated pricing configuration code. |
|
pricingOptionCodes |
Optional (array of strings) |
|
|
Pricing option codes that you control. |
Response
Parameter | Type/Description |
---|---|
promotionProducts | 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);
$promotionCode = '';
// Define a product to add to the promotion
$newProduct1 = new stdClass;
$newProduct1->Code = '';
$newProduct1->PricingConfigurationCode = '';
$newProduct1->PricingOptionCodes = ['',''];
// Define another product to add to the promotion
$newProduct2 = new stdClass;
$newProduct2->Code = '';
$newProduct2->PricingOptionCodes = [''];
$productPromotion = [$newProduct1, $newProduct2];
$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'addPromotionProducts',
'params' => array($sessionID, $promotionCode, $productPromotion)
);
var_dump (callRPC($jsonRpcRequest, $host));