Skip to main content

Add a subscription plan/product

 

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

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.

Product

Required (object)

 

Use this object to configure your subscription plans/products.

 

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

Mandatory parameters

 

ProductName
ProductCode
PricingConfigurations

Response

bool(true)

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 = "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;
}

$Product                 = new stdClass();
$Product->AvangateId     = null;
$Product->ProductCode    = 'API_Imported_1234567899';
$Product->ProductType    = 'REGULAR';
$Product->ProductName    = 'API_Subscription Imported New';
$Product->ProductVersion = '1.0';

//Shipping classes

/* $Product->ShippingClass = new stdClass();
$Product->ShippingClass->Name = '2o9rlujkvg';
$Product->ShippingClass->Amount = 89.40;
$Product->ShippingClass->Currency = 'GBP';
$Product->ShippingClass->ApplyTo = 'ct29dr3fj4';
$Product->ShippingClass->Type = 'bii521vp6k'; */

$Product->GiftOption                 = false;
$Product->ShortDescription           = 'Placeat cumque necessitatibus est minus praesentium ut non quibusdam. Molestias provident tempore eligendi mollitia quia.';
$Product->LongDescription            = 'Corrupti inventore vitae nesciunt ab. Nemo cum non maiores. Non repudiandae est iste voluptatibus.';
$Product->SystemRequirements         = null;
$Product->ProductCategory            = null;
$Product->Platforms                  = array();
$Product->Platforms[0]               = new stdClass();
$Product->Platforms[0]->PlatformName = null;
$Product->Platforms[0]->Category     = null;
$Product->Platforms[1]               = new stdClass();
$Product->Platforms[1]->PlatformName = null;
$Product->Platforms[1]->Category     = null;
$Product->ProductImages              = array();
$Product->ProductImages[0]           = new stdClass();
$Product->ProductImages[0]->URL      = null;
$Product->ProductImages[0]->Default  = false;
$Product->ProductImages[1]           = new stdClass();
$Product->ProductImages[1]->URL      = null;
$Product->ProductImages[1]->Default  = true;
$Product->TrialUrl                   = null;
$Product->TrialDescription           = null;
$Product->Enabled                    = True;

//Product additional fields

/* $Product->AdditionalFields = array();
$Product->AdditionalFields[0] = new stdClass();
$Product->AdditionalFields[0]->Label = 'i44wak1dzp';
$Product->AdditionalFields[0]->Code = 'ITYAK0OEWJ';
$Product->AdditionalFields[0]->Enabled = false;
$Product->AdditionalFields[0]->Required = false;
$Product->AdditionalFields[0]->URLParameter = 'id1ktigl6d';
$Product->AdditionalFields[1] = new stdClass();
$Product->AdditionalFields[1]->Label = 'aig699lmo1';
$Product->AdditionalFields[1]->Code = 'V28TP07PQN';
$Product->AdditionalFields[1]->Enabled = false;
$Product->AdditionalFields[1]->Required = true;
$Product->AdditionalFields[1]->URLParameter = '8to9p6y54j'; */

//Product localization

/* $Product->Translations = array();
$Product->Translations[0] = new stdClass();
$Product->Translations[0]->Name = 'zsg7wtg4e5';
$Product->Translations[0]->Description = 'Voluptate iure ut quam omnis impedit. Deserunt facere id dolores doloribus quis. Minima nostrum ut possimus incidunt vel est sint. Odit tempora omnis iste nesciunt commodi accusantium placeat.';
$Product->Translations[0]->Language = 'pt';
$Product->Translations[0]->LongDescription = 'Pariatur molestiae sit dignissimos modi. Aut modi libero numquam repudiandae. Doloribus explicabo delectus fugiat amet. Excepturi quo consequatur sint adipisci.';
$Product->Translations[0]->SystemRequirements = 'c16tvyg88c';
$Product->Translations[0]->TrialUrl = 'UNCAUGHT TYPE: anyURI';
$Product->Translations[0]->TrialDescription = 'Voluptas rem sit ut voluptas molestias quidem ut. Maiores facilis tempora voluptates. Consequuntur illum recusandae hic magni iste.';
$Product->Translations[1] = new stdClass();
$Product->Translations[1]->Name = 'cv2sx15aby';
$Product->Translations[1]->Description = 'Ut distinctio asperiores et a placeat voluptatem et. Et eveniet temporibus aut vel. Nemo occaecati praesentium dolor fugiat rerum assumenda expedita.';
$Product->Translations[1]->Language = 'fr';
$Product->Translations[1]->LongDescription = 'Et ut nostrum molestiae voluptates soluta. Molestiae cum in ut qui. Voluptatem voluptates vero odit quia corporis. In impedit eligendi sed expedita nihil temporibus nobis.';
$Product->Translations[1]->SystemRequirements = 'cfv2amk25j';
$Product->Translations[1]->TrialUrl = 'UNCAUGHT TYPE: anyURI';
$Product->Translations[1]->TrialDescription = 'Voluptatem ut possimus consequatur iste. Recusandae id quia sed quibusdam aut debitis. Cupiditate harum architecto quod quia.'; */


$Product->PricingConfigurations                                     = array();
$Product->PricingConfigurations[0]                                  = new stdClass();
$Product->PricingConfigurations[0]->Default                         = false;
$Product->PricingConfigurations[0]->Code                            = null;
$Product->PricingConfigurations[0]->Name                            = 'API Pricing Configuration Test';
$Product->PricingConfigurations[0]->BillingCountries                = array();
$Product->PricingConfigurations[0]->PricingSchema                   = 'DYNAMIC';
$Product->PricingConfigurations[0]->PriceType                       = 'NET';
$Product->PricingConfigurations[0]->DefaultCurrency                 = 'USD';
$Product->PricingConfigurations[0]->Prices                          = new stdClass();
$Product->PricingConfigurations[0]->Prices->Regular                 = array();
$Product->PricingConfigurations[0]->Prices->Regular[0]              = new stdClass();
$Product->PricingConfigurations[0]->Prices->Regular[0]->Amount      = 100;
$Product->PricingConfigurations[0]->Prices->Regular[0]->Currency    = 'USD';
$Product->PricingConfigurations[0]->Prices->Regular[0]->MinQuantity = 1;
$Product->PricingConfigurations[0]->Prices->Regular[0]->MaxQuantity = 10;
$Product->PricingConfigurations[0]->Prices->Regular[0]->OptionCodes = array();
$Product->PricingConfigurations[0]->Prices->Regular[1]              = new stdClass();
$Product->PricingConfigurations[0]->Prices->Regular[1]->Amount      = 200;
$Product->PricingConfigurations[0]->Prices->Regular[1]->Currency    = 'USD';
$Product->PricingConfigurations[0]->Prices->Regular[1]->MinQuantity = 11;
$Product->PricingConfigurations[0]->Prices->Regular[1]->MaxQuantity = 100;
$Product->PricingConfigurations[0]->Prices->Regular[1]->OptionCodes = array();
$Product->PricingConfigurations[0]->Prices->Renewal                 = array();
$Product->PricingConfigurations[0]->Prices->Renewal[0]              = new stdClass();
$Product->PricingConfigurations[0]->Prices->Renewal[0]->Amount      = 50;
$Product->PricingConfigurations[0]->Prices->Renewal[0]->Currency    = 'USD';
$Product->PricingConfigurations[0]->Prices->Renewal[0]->MinQuantity = 1;
$Product->PricingConfigurations[0]->Prices->Renewal[0]->MaxQuantity = 10;
$Product->PricingConfigurations[0]->Prices->Renewal[0]->OptionCodes = array();
$Product->PricingConfigurations[0]->Prices->Renewal[1]              = new stdClass();
$Product->PricingConfigurations[0]->Prices->Renewal[1]->Amount      = 60;
$Product->PricingConfigurations[0]->Prices->Renewal[1]->Currency    = 'USD';
$Product->PricingConfigurations[0]->Prices->Renewal[1]->MinQuantity = 11;
$Product->PricingConfigurations[0]->Prices->Renewal[1]->MaxQuantity = 100;
$Product->PricingConfigurations[0]->Prices->Renewal[1]->OptionCodes = array();
$Product->PricingConfigurations[0]->PriceOptions                    = array();

/* $Product->BundleProducts = array();
$Product->BundleProducts[0] = new stdClass();
$Product->BundleProducts[0]->ProductCode = '540Q45PQBN';
$Product->BundleProducts[0]->ProductId = 48439;
$Product->BundleProducts[1] = new stdClass();
$Product->BundleProducts[1]->ProductCode = 'PA3JDB5SZ2';
$Product->BundleProducts[1]->ProductId = 46439;
*/
$Product->Fulfillment = 'NO_DELIVERY';
$Product->Prices      = array();

$Product->GeneratesSubscription                            = True;
$Product->SubscriptionInformation                          = new stdClass();
$Product->SubscriptionInformation->DeprecatedProducts      = array();
$Product->SubscriptionInformation->BundleRenewalManagement = null;
$Product->SubscriptionInformation->BillingCycle            = 1;
$Product->SubscriptionInformation->BillingCycleUnits       = 'M';
$Product->SubscriptionInformation->IsOneTimeFee            = false;

$Product->SubscriptionInformation->ContractPeriod                       = new stdClass();
$Product->SubscriptionInformation->ContractPeriod->Period               = -1;
$Product->SubscriptionInformation->ContractPeriod->PeriodUnits          = 'days';
$Product->SubscriptionInformation->ContractPeriod->IsUnlimited          = TRUE;
$Product->SubscriptionInformation->ContractPeriod->Action               = 'RESTART';
$Product->SubscriptionInformation->ContractPeriod->EmailsDuringContract = 'altenwerth.elise@gmail.com';

//$Product->SubscriptionInformation->UsageBilling = 77;

$Product->SubscriptionInformation->GracePeriod              = new stdClass();
$Product->SubscriptionInformation->GracePeriod->Type        = 'GLOBAL';
$Product->SubscriptionInformation->GracePeriod->Period      = 14;
$Product->SubscriptionInformation->GracePeriod->PeriodUnits = 'D';
$Product->SubscriptionInformation->GracePeriod->IsUnlimited = false;

$Product->SubscriptionInformation->RenewalEmails                                               = new stdClass();
$Product->SubscriptionInformation->RenewalEmails->Type                                         = 'CUSTOM';
$Product->SubscriptionInformation->RenewalEmails->Settings                                     = new stdClass();
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal                      = new stdClass();
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->Before30Days        = true;
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->Before15Days        = true;
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->Before7Days         = true;
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->Before1Day          = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->OnExpirationDate    = true;
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->After5Days          = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->ManualRenewal->After15Days         = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal                   = new stdClass();
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->Before30Days     = true;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->Before15Days     = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->Before7Days      = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->Before1Day       = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->OnExpirationDate = true;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->After5Days       = false;
$Product->SubscriptionInformation->RenewalEmails->Settings->AutomaticRenewal->After15Days      = true;

$Product->FulfillmentInformation                                = new stdClass();
$Product->FulfillmentInformation->IsStartAfterFulfillment       = false;
$Product->FulfillmentInformation->IsElectronicCode              = false;
$Product->FulfillmentInformation->IsDownloadLink                = false;
$Product->FulfillmentInformation->IsBackupMedia                 = false;
$Product->FulfillmentInformation->IsDownloadInsuranceService    = false;
$Product->FulfillmentInformation->IsInstantDeliveryThankYouPage = false;
$Product->FulfillmentInformation->IsDisplayInPartnersCPanel     = false;

/* $Product->FulfillmentInformation->CodeList = new stdClass();
$Product->FulfillmentInformation->CodeList->Code = '5C6F821DA1';
$Product->FulfillmentInformation->CodeList->Name = 'General delivery';
$Product->FulfillmentInformation->CodeList->Type = 'STATIC';  */

//$Product->FulfillmentInformation->BackupMedia = new stdClass();

//$Product->FulfillmentInformation->ProductFile = new stdClass();

/* $Product->FulfillmentInformation->AdditionalInformationByEmail = 'arlene03@hotmail.com';
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations = array();
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[0] = new stdClass();
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[0]->Name = 'kbaa1aj7po';
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[0]->Description = 'Velit delectus sed amet sunt. Sunt deserunt quos recusandae consequuntur est. Velit aut optio error eius rerum. Nihil ipsam possimus ipsum dolores consequatur adipisci.';
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[0]->Language = 'fr';
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[1] = new stdClass();
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[1]->Name = 'l4ocvz9wwa';
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[1]->Description = 'Esse voluptatem delectus officiis eos quas asperiores. Quas non hic reiciendis enim. Consequatur similique recusandae laboriosam et autem.';
$Product->FulfillmentInformation->AdditionalInformationEmailTranslations[1]->Language = 'pt';
$Product->FulfillmentInformation->AdditionalThankYouPage = 'rvlhvkmxkp';
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations = array();
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[0] = new stdClass();
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[0]->Name = 'rl981w4nua';
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[0]->Description = 'Qui explicabo molestiae dolorem consequuntur. Ullam maiores temporibus vitae. Totam eos et consequatur. Est sit minima animi nam ut aut.';
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[0]->Language = 'en';
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[1] = new stdClass();
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[1]->Name = 'qye8hlwz3e';
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[1]->Description = 'Id est rerum deserunt non et quia magnam. Minus aut nostrum dicta est officiis quia. Commodi nobis sit porro accusamus rerum quis. Fugit et asperiores eum.';
$Product->FulfillmentInformation->AdditionalThankYouPageTranslations[1]->Language = 'fr';
*/


try {
    $NewSubscriptionPlan = $client->addProduct($sessionID, $Product);
}

catch (SoapFault $e) {
    echo "AddedProductInfo: " . $e->getMessage();
    exit;
}
var_dump("AddedProductInfo", $NewSubscriptionPlan);
?>

 

Place an order with PayPal

Overview

Use the placeOrder method to create an order and collect the payment from PayPal.

Requirements

You're required to include the following text when using the 2Checkout API and to make it visible for your customers in the ordering interface. 

Order processed by 2Checkout, authorized reseller and merchant of the products and services offered within this store. 

Currency support

Check with 2Checkout support for a list of currencies available for PayPal. 

Parameters

Parameters

Type/Description

sessionID

Required (string)

 

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

Order

Required (Object)

 

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

To place an order with PayPal rather than PayPal Express, use PAYPAL as the type of the PaymentDetails object and send the shopper email and a return URL as part of the PaymentMethod object. See code sample. 

Workflow

  1. Create the order object. Use PAYPAL as the type of the PaymentDetails object and send the shopper email and a return URL as part of the PaymentMethod object. Place the order.
  2. Once you place the order, 2Checkout logs it into the system. At this point in time, the status of the order is PENDING. 2Checkout responds with the Order information object.
  3. Redirect shoppers to the RedirectURL from the Order information object you receive as response from 2Checkout.
  4. Once shoppers log in to their PayPal account and complete the transaction, they're redirected to the ReturnURL you set in the order object. 2Checkout also authorizes the order and updates the status to AUTHRECEIVED. 

Response

Parameter Type/Description

Order information

Object

Request

<?php

//The following script let's you place an new order with Credit/Debit cards as the payment method

$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.2checkout.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.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;
}
$Order = new stdClass();
$Order->RefNo = NULL;
$Order->Currency = 'usd';
$Order->Country = 'US';
$Order->Language = 'en';
$Order->CustomerIP = '91.220.121.21';
$Order->ExternalReference = NULL;
$Order->Source = NULL;
$Order->AffiliateId = NULL;
$Order->CustomerReference = NULL;
$Order->Items = array();
$Order->Items[0] = new stdClass();
$Order->Items[0]->Code = 'my_subscription_1';
$Order->Items[0]->Quantity = 1;
$Order->Items[0]->PriceOptions = NULL;
$Order->Items[0]->SKU = NULL;
$Order->Items[0]->Price = NULL;
$Order->Items[0]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->BillingDetails = new stdClass();
$Order->BillingDetails->FirstName = 'FirstName';
$Order->BillingDetails->LastName = 'LastName';
$Order->BillingDetails->CountryCode = 'us';
$Order->BillingDetails->State = 'California';
$Order->BillingDetails->City = 'LA';
$Order->BillingDetails->Address1 = 'Address example';
$Order->BillingDetails->Address2 = NULL;
$Order->BillingDetails->Zip = '90210';
$Order->BillingDetails->Email = 'customer@email.com';
$Order->BillingDetails->Phone = NULL;
$Order->BillingDetails->Company = NULL;
$Order->DeliveryDetails = NULL;
$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'PAYPAL';
$Order->PaymentDetails->Currency = 'usd';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '10.10.10.10';
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$Order->PaymentDetails->PaymentMethod->Email = 'email@avangate.com';
$Order->PaymentDetails->PaymentMethod->ReturnURL = 'http://YourReturnURL.com';
$Order->Promotions = NULL;
$Order->AdditionalFields = NULL;
$Order->LocalTime = NULL;
$Order->GiftDetails = NULL;
try {
    $newOrder = $client->placeOrder($sessionID, $Order);
}
catch (SoapFault $e) {
    echo "newOrder: " . $e->getMessage();
    exit;
}
var_dump("newOrder", $newOrder);

$url = $newOrder->PaymentDetails->PaymentMethod->RedirectURL;

header ("Location: $url");

 

Update a subscription and assign it to another customer

Overview

Move a subscription from under a customer to another customer entity.

Use the updateSubscription method. Avangate moves subscription under the customer for which you provide the Avangate customer reference or the External customer reference during the subscription update process.

update_diagram.png

Requirements

To move a subscription from a source customer to a target customer:

  • Use Avangate customer references or External customer references belonging to the target customer. Avangate re-assigns the subscription to the target customer. 
  • Customer references must be valid and associated to the target customer entity under which you move the subscription.

If you provide both the Avangate customer reference and External customer reference they need to belong to the same target customer entity.

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.

Subscription

Required (Object)

 

To only move a subscription from a source customer to a target customer, send only the Avangate customer reference or the External customer reference.

Response

Parameters Type/Description

Boolean

true or false depending on whether the changes were successful or not.

Request

<?php

require ('PATH_TO_AUTH');

$SubscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';

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

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

$updatedSubscription->AvangateCustomerReference = 'YOUR_SUBSCRIPTION_REFERENCE';

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

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

Search shipping methods

Overview

Use searchShippingMethods to retrieve information on the shipping methods currently defined on your account.

Search filters

Use the parameters below to filter the results of your search for shipping methods.

Parameter Type/Description
Name

String / Optional

Name of the shipping method.

Codes

Array of strings / Optional

Codes assigned to the shipping methods.

Countries

Array of strings / Optional

Countries to which the shipping method is assigned.

Active

Boolean / Optional

TRUE - active shipping methods

FALSE - inactive shipping methods

Pagination

Object / Optional

Control the results pagination.

  Page

Integer / Optional

Number of pages to display the results

  Limit

Integer / Optional

Limit the number of results of the search

Sample request

<?php

require ('PATH_TO_AUTH'); // authentication call

$SearchOptions = new \stdClass();
$SearchOptions->Name = 'ShippingMethodName'; // search for a specific shipping method
$SearchOptions->Codes = ['Code1', 'Code2', 'Code3']; // array of shipping method codes
$SearchOptions->Countries = ['US', 'UK', 'AU']; // array of country codes
$SearchOptions->Active = true; // only active shipping methods
$SearchOptions->Pagination = new \stdClass();
$SearchOptions->Pagination->Page = 1; // set display pages
$SearchOptions->Pagination->Limit = 200; // limit the results

try {
    $shippingMethods = $client->searchShippingMethods($sessionID, $SearchOptions);
}
catch (SoapFault $e) {
    echo "shippingMethods: " . $e->getMessage();
    exit;
}
var_dump("shippingMethods", $shippingMethods);

Response

Parameter Type/Description
ShippingMethod

Object

 

 

Retrieve shipping price

Overview

Use getShippingPrice to retrieve the shipping method and price available, based on a current cart configuration. This API call returns the available shipping methods defined in your Control Panel, together with the fees you configured based on order total amount/weight/country.

Requirements

It's mandatory to have tangible products defined in your Control Panel, to retrieve shipping method and price information.

Parameters

Parameters Type/Description
Items

Object / Required

Contains information on the tangible product added in cart.

  Code

String / Required

Product code defined in the Information tab from the Product level, in the Control Panel.

  Quantity

Integer / Optional

Quantity of the product that is being purchased.

Default value is 1.

BillingDetails

Object / Required

Contains customer billing information.

  CountryCode

String / Required

Two-digits code of customer billing country. Example: 'US'.

DeliveryDetails

Object / Required

Contains customer delivery information.

  CountryCode

String / Required

Two-digits code of customer delivery country. Example: 'US'.

Currency

String / Optional

Three-digits code of purchase currency. Example: 'USD'.

CouponCodes

Array of strings / Optional

Discount codes that can be applied to the purchase.

Sample request

<?php

require ('PATH_TO_AUTH'); // authentication call

$cartItems = [];
$cartItem = new stdClass();
$cartItem->Code = 'my_product_code_1'; // product code defined in the Information tab, at product level
$cartItem->Quantity = 2; // quantity that is being purchased
$cartItems[0] = $cartItem;
$billingDetails = new stdClass();
$billingDetails->CountryCode = 'US'; // billing country

$deliveryDetails = new stdClass();
$deliveryDetails->CountryCode = 'AU'; // delivery country

$currency = 'USD'; // purchase currency

$couponCode = ['TANGIBLEPROMO']; // apply discount to promotion

try {
    $shippingPrice = $client->getShippingPrice($sessionID, $cartItems, $billingDetails, $deliveryDetails, $currency);
}
catch (SoapFault $e) {
    echo "ShippingPrice: " . $e->getMessage();
    exit;
}
var_dump("ShippingPrice", $shippingPrice);

Response

Parameters Type/Description
ShippingPrice

Object

This method returns an object, containing the shipping price available for a certain cart configuration.

 

Search promotions

Overview

Use the searchPromotions method to extract information on promotions you set up 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.

Types

StringArray

 

Discount type:

  • REGULAR
  • GLOBAL
  • RENEWAL

Channel

String

 

Channel:

  • ECOMMERCE
  • CHANNEL_MANAGER
  • ALL

ProductCode

String

 

Unique code that you set for each of your products.

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

Parameters Type/Description
Promotion Array of objects

Request

<?php

require ('PATH_TO_AUTH');

$searchOptions = new stdClass();
$searchOptions->Types = array ('REGULAR');
$searchOptions->Channel = 'ECOMMERCE';
$searchOptions->ProductCode = 'Product_Code_1';
$searchOptions->Enabled = TRUE;
$searchOptions->Limit = 99;
$searchOptions->Page = 1;

$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'searchPromotions',
'params' => array($sessionID, $searchOptions)
);
var_dump (callRPC((Object)$jsonRpcRequest, $host));
?>

Retrieve order subscription references

Overview

List the references associated with the subscription generated for an order.

Requirements

This method requires you to set a specific partner using setPartner.

Parameters

Parameter Type/Description
sessionID Required (String)
  Session identifier, output of the Login method. An exception is thrown if the values are incorrect.
refNo Required (String)
  The unique identifier of an order from the 2Checkout system.
pageNo Optional (Int)
 

Break down the subscription information using pagination into groups of 50 items (PartnerSubscription objects) per page.

Example values:

  • 1 - the first 50
  • 2 - the next 50
  • 3 - the next 50

Can be NULL.

Response

Parameter Type/Description

PartnerSubscription

Array of objects

 

Details below

 

SubscriptionReference

String

 

 

The unique reference associated with a subscription generated for a product included in a partner order.

 

HasEndUserInformation

Boolean

 

 

True or false, depending on whether end-user information is attached to the subscription.

 

RegistrationStatus

String

 

 

Possible values:

  • Not registered
  • Registered

 

RegistrationEmails

String

 

 

The email used by the end-user in the registration process. Can be NULL.

 

FullfilmentStatus

String

 

 

Fulfillment status possible values:

  1. DELIVERED - Order was fulfilled/delivered.
  2. NOT_DELIVERED - Fulfillment is blocked due to various reasons including lack of payment/credit, missing reseller/end-user details.
  3. NO_DELIVERY_REQUIRED - No fulfillment confirmation is required.
  4. VENDOR_CONFIRMED_DELIVERY - Fulfillment has been confirmed.
  5. VENDOR_DELIVERY_CONFIRMATION_REQUIRED - You need to confirm fulfillment.

Request

<?php

require ('PATH_TO_AUTH');  // Authentication example: https://knowledgecenter.avangate.com/Integration/Channel_Manager_API/JSON-RPC/02Authentication
require ('PATH_TO_setPartner'); // setPartner example: https://knowledgecenter.avangate.com/Integration/Channel_Manager_API/JSON-RPC/06Reference/Partner/00Set_partner

$refNo = 'YOUR_ORDER_REFERENCE';

$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'getOrderSubscriptions',
'params' => array($sessionID, $refNo)
);
var_dump (callRPC((Object)$jsonRpcRequest, $host));

Errors

Error Description

NOT_FOUND_PARTNER

A partner must be set first.

EMPTY_ORDER_REFERENCE

Order reference not provided.

INVALID_REFERENCE

Invalid order reference.

 

Confirm payment for Proforma Invoices

Overview

Use this method to confirm the payment for proforma invoices issued to your partners on the Direct Payment module. To confirm the payment for a proforma invoice, you need to follow these steps before calling the confirmInvoicePayment API method:

  1. Authenticate to 2Checkout API based on these instructions.
  2. Set the partner for which you want to confirm the payment (method explained in the sample below).
  3. Set the proforma invoice  (method explained in the sample below).
  4. Confirm the payment using the instructions below.

Requirements

You can confirm payments only for partners set with Direct business model. Learn here how to set a business model to your partners.

Parameters

Parameters Type/Description
sessionID Required (String)
  Session identifier, output of the Login method. An exception is thrown if the values are incorrect.
partnerCode Required (String)
  The unique identifier that you need to specify when creating a partner in the Control Panel. You can find it under the General Information area when editing partner details.
proformaNo Required (String)
  The unique identifier of a partner invoice from the 2Checkout system.
rrn Optional (String)
  The code associated with the proforma invoice payment reference (receipt registration number).

Response

Parameters Type/Description

TRUE

FALSE

Boolean

True - method is successful

False - method is not successful

Error messages

Error code Error description
INVALID_PARTNER No partner is set or the proforma does not belong to the partner set.
PAYMENT_PROFORMA The proforma invoice has already been paid.
INVALID_PROFORMA The proforma invoice number is invalid.
INVALID_METHOD The partner set is not on the Direct business model.

Request

<?php

require ('PATH_TO_AUTH');  // Authentication example: https://knowledgecenter.avangate.com/Integration/Channel_Manager_API/JSON-RPC/02Authentication
require ('PATH_TO_SET_PARTNER'); // setPartner example: https://knowledgecenter.avangate.com/Integration/Channel_Manager_API/JSON-RPC/06Reference/Partner/00Set_partner

$partnerCode = 'partner_code'; // direct

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

$partner = callRPC($jsonRpcRequest, $host, true);

// call setPartner
$proformaNo = '6'; //  not paid reseller direct but before was reseller

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

$proforma = callRPC($jsonRpcRequest, $host, true);

$rrn = 'refnostril'; // controls payment reference
// $rrn = '';

//call confirmInvoicePayment
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'confirmInvoicePayment';
$jsonRpcRequest->params = array($sessionID, $rrn);
$jsonRpcRequest->id = $i++;

$paymentConfirmation = callRPC($jsonRpcRequest, $host, true);
print_r(json_encode($paymentConfirmation));

Update and Assign a subscription

Overview

Move a subscription from under a customer to another customer entity.

Use the updateSubscription method. 2Checkout moves subscription under the customer for which you provide the 2Checkout customer reference or the External customer reference during the subscription update process.

update_diagram.png

Requirements

To move a subscription from a source customer to a target customer:

  • Use 2Checkout customer references or External customer references belonging to the target customer. 2Checkout re-assigns the subscription to the target customer. 
  • Customer references must be valid and associated to the target customer entity under which you move the subscription.

If you provide both the 2Checkout customer reference and External customer reference they need to belong to the same target customer entity.

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.

Subscription

Required (Object)

 

To only move a subscription from a source customer to a target customer, send only the 2Checkout customer reference or the External customer reference.

Response

Parameters Type/Description

Boolean

true or false depending on whether the changes were successful or not.

Request

<?php

require ('PATH_TO_AUTH');

$SubscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';

try {
    $retrievedSubscription = $client->getSubscription($sessionID, $SubscriptionReference);
}
catch (SoapFault $e) {
    echo "retrievedSubscription: " . $e->getMessage();
    exit;
}
var_dump("retrievedSubscription", $retrievedSubscription);
var_dump ($retrievedSubscription);
$retrievedSubscription->AvangateCustomerReference = 172673064;
try {
    $updatedSubscription = $client->updateSubscription($sessionID, $retrievedSubscription);
}
catch (SoapFault $e) {
    echo "updatedSubscription: " . $e->getMessage();
    exit;
}
var_dump("updatedSubscription", $updatedSubscription);

Retrieve a promotion by code

Response

Promotion object. 

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 = "YOURCODE123"; //your account's merchant code available in the 'System settings' area of the cPanel: https://secure.2checkout.com/cpanel/account_settings.php
$key          = "SECRET_KEY"; //your account's secret key available in the 'System settings' area of the cPanel: https://secure.2checkout.com/cpanel/account_settings.php 
$now          = gmdate('Y-m-d H:i:s'); //date_default_timezone_set('UTC') 
$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash   = hmac($key, $string);
try {
    $sessionID = $client->login($merchantCode, $now, $hash);
}
catch (SoapFault $e) {
    echo "Authentication: " . $e->getMessage();
    exit;
}
$PromotionCode = '62B7F22FC5';
try {
    $Discount = $client->getPromotionByCode($sessionID, $PromotionCode);
}
catch (SoapFault $e) {
    echo "Discount: " . $e->getMessage();
    exit;
}
var_dump("Discount", $Discount);

?>

 

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