Skip to main content

Retrieve price based on specific options

Overview

Use getPrice to extract cost information for a product/subscription plan, based on a specific list of options. 

Parameters

Parameters Type/Description

Item

Required (Object)

Details below.

 

Code

Required (string)

 

 

Unique product identifier your control. Max length 256 characters.

 

Quantity

Required (String)

 

 

Number of units.

 

PriceOptions

Optional (Array of objects)

 

 

Array of price option groups.

                   Options Optional (Array of objects)
    Array of pricing options.
                                     Value Optional (String)
    Pricing option code.

Billing details

Optional (Object)

 

Details below. Can be null. 

 

FirstName

Optional (string)

 

 

Shopper name.

 

LastName

Optional (string)

 

 

Shopper surname.

 

CountryCode

Optional (string)

 

 

Shopper country. ISO 3166 two-letter code. Include CountryCode in your request in combination with a null value for Currency, to receive the price in the default currency of the country you set. 

 

State

Optional (string) – Required for US, Brazil and Romania

 

 

The state in the shopper's country. Mandatory when you set the Billing Country to US, Brazil and Romania. Use case insensitive utf8 strings for the full name, or just the two letter code.

 

City

Optional (string)

 

 

Shopper city.

 

Address1

Optional (string)

 

 

Shopper address.

 

Address2

Optional (string)

 

 

Shopper address.

 

Zip

Optional (string)

 

 

ZIP/ Postal code.

 

Email

Optional (string)

 

 

Shopper email address.

 

Phone

Optional (string)

 

 

Shopper phone number. Mandatory when you set Brazil as the Billing Country. Can be NULL.

 

Company

Optional (string)

 

 

Company name. Can be null for end users. When present, you also need to provide the FiscalCode.

 

FiscalCode

Optional (string) – Required for Brazil

 

 

• For companies, it needs to be the VAT ID. 2Checkout will validate the value provided and throw an error if the VAT ID is invalid/incorrect when calling setPaymentDetails. When present, you also need to provide the Company name.

• Mandatory when you set Brazil as the Billing Country. For Brazilian customers it represents the Fiscal Code (CPF/CNPJ).

• Can be NULL for end users.

Currency

Required (string)

 

The currency ISO code for the payment - ISO 4217. Example: “usd.”

CouponCode

Optional (string)

 

Promotion coupon/voucher.

PayType

Optional (string)

 

The payment method:

  • CC (credit/debit card - including local Brazilian cards).
  • ENCRYPTED_PAYMENT_DATA (client-side encryption)
  • PAYPAL
  • PAYPAL_EXPRESS
  • TEST (for test orders).
  • PREVIOUS_ORDER (place new orders using the reference of a previous order).
  • EXISTING_PAYMENT_DATA  (use a card one of your customers already used to purchase from your account).
  • WIRE – the placeOrder response includes Wire payment details.
  • CHECK – the placeOrder response includes Check payment details.
  • PURCHASEORDER - use for orders with POs.
  • FREE – for 0 value orders for which you’re not requiring customers to provide payment details.

Response

Parameters Type/Description
ItemPrice

Object

Details below.

UnitNetPrice

Float

 

The value per product unit, excluding sales tax/VAT expressed in the payment currency.

UnitGrossPrice

Float

 

Total value per product unit, including sales tax/VAT expressed in the payment currency. UnitGrossPricedoes not reflect any discounts.

UnitVAT

Integer

 

Sales tax/VAT per product unit expressed in the payment currency.

UnitDiscount

Integer

 

Value of the discount per product unit expressed in the payment currency.

UnitNetDiscountedPrice

Float

 

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

UnitGrossDiscountedPrice

Float

 

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

UnitAffiliateCommission

Integer

 

Value of the affiliate commission per product unit calculated expressed in the payment currency.

 

2Checkout deducts discounts from the costs incurred by shoppers before calculating affiliate commissions.

 

2Checkout does not take into account shipping costs when calculating affiliate commissions.

 

NULL when 2Checkout does not apply an affiliate commission.

VATPercent Integer
  VAT percentage applied to purchase.
HandlingFeeNetPrice Integer
  Handling fee applied to your NET price configuration.
HandlingFeeGrossPrice Integer
  Handling fee applied to your GROSS price configuration.
AffiliateCommission Optional (double)
  Value of the affiliate commission for the order calculated from the NetDiscountedPrice expressed in the payment currency. Or NULL. 2Checkout does not take into account shipping costs when calculating affiliate commissions.
Currency Optional (string)
  The currency ISO code for the payment - ISO 4217. Example: “usd.” Use null as value when you include CountryCode in your request, to receive the price in the default currency of the country you set. 
Discount Optional (double)
  Value of the discounts for an order expressed in the payment currency.
GrossDiscountedPrice Optional (double)
  Total costs shoppers incurexpressed in the payment currencyThis value includes sales tax/VAT, 2Checkout and affiliate commissions, but 2Checkout deducts the value of any discounts.
GrossPrice Optional (double)
  Total order value, including sales tax/VAT expressed in the payment currency. GrossPrice does not reflect any discounts.
NetDiscountedPrice Optional (double)
  The NetPrice order value excluding sales tax/VAT, from which 2Checkout deducts discounts. NetDiscountedPriceis expressed in the payment currency.
NetPrice Optional (double)
  Order value excluding sales tax/VAT expressed in the payment currency.
VAT Optional (double)
  Value of sales tax/VAT expressed in the payment currency.

Request

<?php

require ('PATH_TO_AUTH');

$CartItem = new stdClass();

$CartItem->Code = 'my_subscription_1';
$CartItem->Quantity = 1;
$CartItem->PriceOptions = array();

/* $CartItem->Trial = new stdClass();
$CartItem->Trial->Period = 8;
$CartItem->Trial->Price = 0; */

$BillingDetails = NULL;
$Currency = 'USD';
$CouponCode = '123';
$PayType = 'CC';

try {
    $itemPrice = $client->getPrice($sessionID, $CartItem, $BillingDetails, $Currency, $CouponCode, $PayType);
}
catch (SoapFault $e) {
    echo "itemPrice: " . $e->getMessage();
    exit;
}
var_dump("itemPrice", $itemPrice);

 

Update product group

Overview

Use the updateProductGroup method to create a new product group 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.

ProductGroup

Required (object)

 

Use this object to update product groups.

Response

bool(true)

Request

<?php

require ('PATH_TO_AUTH');

$ProductGroup = new stdClass();
$ProductGroup->Name = 'New Product Group from API';
$ProductGroup->Code = 'DBA13A4268';
$ProductGroup->TemplateName = 'Default Template'; // the name of the cart template you want to associate with the product group
$ProductGroup->Description = 'This is a generic description';
$ProductGroup->Enabled = false;

try {
    $UpdatedProductGroup = $client->updateProductGroup($sessionID, $ProductGroup);
}

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

var_dump("UpdatedProductGroup", $UpdatedProductGroup);


?>

 

One click (1-click) purchase

Overview 

Avangate supports 1-click purchases for returning customers who paid for their previous orders with:

  • Credit/Debit cards
  • PayPal

How does this work? 

  1. Identify returning customers. 
  2. Access data on the previous purchases of returning customers.
  3. Validate previous order references for 1-click purchase scenarios using the isValidOrderReference method.
  4. Place a new order using a valid previous order reference as the payment method. 
  5. Avangate charges returning customers using their payment-on-file information, either a card or their PayPal account. 

Requirements 

  • Use only references of previous orders  with one of the following statuses AUTHRECEIVED or COMPLETE.
  • The email address of the BillingDetails object is mandatory and it needs to match the email address used as a part of the billing details of the initial order whose reference you're now using to place a new order. Avangate checks whether the email addresses are identical, and throws an error if they're not, blocking the order placement process. Note: You need to provide only the email address of the shopper, and can ignore the rest of the required customer billing information. If you enter any billing details in addition to the email address, you'll have to provide all information required in the BillingDetails object.

Parameters 

Parameters Type/Description

sessionID

Required (string)

 

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

Order

Required (Object)

 

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

Response 

Parameters Type/Description

Order information

Object

  Object containing order information.

Validate previous order reference

<?php

require('PATH_TO_AUTH');

$orderReference = '670174996';
$jsonRpcRequest = array (
'method' => 'isValidOrderReference',
'params' => array($sessionID, $orderReference),
'id' => $i++,
'jsonrpc' => '2.0'
);

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

Place an order using previous order reference 

<?php

require('PATH_TO_AUTH');

$oldOrderExistent = callRPC((Object)$jsonRpcRequest, $host, true);
$Order = new stdClass();
$Order->RefNo = NULL;
$Order->Currency = 'usd';
$Order->Country = 'US';
$Order->Language = 'en';
$Order->CustomerIP = '91.220.121.21';
$Order->ExternalReference = NULL;
$Order->Source = NULL;
$Order->AffiliateId = NULL;
$Order->CustomerReference = NULL;

$Order->Items = array();
$Order->Items[0] = new stdClass();
$Order->Items[0]->Code = 'my_subscription_1';
$Order->Items[0]->Quantity = 1;
$Order->Items[0]->PriceOptions = NULL;
$Order->Items[0]->SKU = NULL;
$Order->Items[0]->Price = NULL;
$Order->Items[0]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->Items[0]->Promotion = NULL;

$Order->BillingDetails = new stdClass();
$Order->BillingDetails->Email = $oldOrderExistent->BillingDetails->Email;;
$Order->DeliveryDetails = NULL;
$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'PREVIOUS_ORDER';
$Order->PaymentDetails->Currency = 'usd';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '10.10.10.10';
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$Order->PaymentDetails->PaymentMethod->RefNo = $orderReference;
$Order->Promotions = NULL;
$Order->AdditionalFields = NULL;
$Order->LocalTime = NULL;
$Order->GiftDetails = NULL;

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

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

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. 2Checkout 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.2checkout.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.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;
}
$subscriptionReference = '30E47F8699';
$Status = true;
try {
    $Notifications = $client->setRenewalNotificationStatus($sessionID, $subscriptionReference, $Status);
}
catch (SoapFault $e) {
    echo "Notifications: " . $e->getMessage();
    exit;
}
var_dump("Notifications", $Notifications);

 

Place a renewal order

Overview

Renew a subscription by using the 2Checkout Subscription Reference. Collect recurring revenue with one of the following payment methods:

  • Credit cards
  • PayPal
  • WeChat Pay
  • iDEAL
  • Purchase Order
  • Wire

Use the PaymentDetails object to control the payment method used in the renewal process.

Requirements

To place a renewal order, you need to provide a valid subscription reference number.

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. 

SubscriptionReference

Required (String)

2Checkout generated subscription reference number. E.q. A8C5671BFE.

Response

Edit section 
Parameters Type/Description

Order information

Object

Request

<?php

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->Currency = 'USD';
$Order->Language = "EN";
$Order->Country = 'US';
$Order->CustomerIP = '91.220.121.21';
$Order->Source = "sourceAPI.net";
$Order->LocalTime = date('Y-m-d H:i:s');
$Order->Items = array();

/**/
$Order->Items[0]->RenewalInformation = new stdClass();
$Order->Items[0]->RenewalInformation->SubscriptionReference = 'A8C5671BFE'; //subscription used in the renewal process
$Order->Items[0]->Price = new stdClass();
$Order->Items[0]->Price->Type = 'CUSTOM';
$Order->Items[0]->Price->Amount = '10';
$Order->Items[0]->PriceOptions = array('uniqscale1=4');//

$Order->MachineId = "MachineID";

$Order->BillingDetails = new stdClass();
$Order->BillingDetails->Address1 = 'Bil1ing address';
$Order->BillingDetails->Address2 = 'Billing address 2';
$Order->BillingDetails->City = 'Billing City';
$Order->BillingDetails->State = 'Billing State';
$Order->BillingDetails->CountryCode = 'US';
$Order->BillingDetails->Phone = 1231232123;
$Order->BillingDetails->Email = 'customer_details@test.com';
$Order->BillingDetails->FirstName = 'First';
$Order->BillingDetails->LastName = 'Customer';
$Order->BillingDetails->Company = 'Billing Company';
$Order->BillingDetails->Zip = '55104';

$Order->DeliveryDetails = new stdClass();
$Order->DeliveryDetails->Address1 = 'Bil1ing address';
$Order->DeliveryDetails->Address2 = 'Billing address 2';
$Order->DeliveryDetails->City = 'Billing City';
$Order->DeliveryDetails->State = 'Billing State';
$Order->DeliveryDetails->CountryCode = 'US';
$Order->DeliveryDetails->Phone = '12345';
$Order->DeliveryDetails->Email = 'customer_details@test.com';
$Order->DeliveryDetails->FirstName = 'First';
$Order->DeliveryDetails->LastName = 'Customer';
$Order->DeliveryDetails->Zip = "55104";

$Order->PaymentDetails = new stdClass();
$Order->PaymentDetails->Type = "CC";
$Order->PaymentDetails->Currency = $currency;

$Order->PaymentDetails->PaymentMethod = new stdClass();
/**/
$Order->PaymentDetails->PaymentMethod->CardNumber = "4111111111111111";
$Order->PaymentDetails->PaymentMethod->CardType = "VISA";
$Order->PaymentDetails->PaymentMethod->ExpirationYear = "2019";
$Order->PaymentDetails->PaymentMethod->ExpirationMonth = "12";
$Order->PaymentDetails->PaymentMethod->CCID = "123";
$Order->PaymentDetails->PaymentMethod->HolderName = "John Doe";
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = TRUE;
$Order->PaymentDetails->PaymentMethod->HolderNameTime = 1;
$Order->PaymentDetails->PaymentMethod->CardNumberTime = 1;
/**/


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

var_dump("newOrder", $Order);
Edit section
 

 

One click (1-click) subscription renewal

Overview

Avangate supports 1-click manual subscription renewals for returning customers who paid for their previous orders with Credit/Debit cards.

In this scenario, you can facilitate subscription renewals for subscribers who opted out of auto-renewal (recurring billing).

How does this work? 

  1. Identify returning customers. 
  2. Generate the manual renewal link.
  3. Create a tokenized manual subscription renewal link and serve it to the returning customer.
  4. Customers using the link land a hosted shopping cart, chose one of their credit cards they previously used for purchases from your account/store and place the order.

 

What do shoppers see in the cart?

Availability

Please contact Avangate to start using one click (1-click) subscription renewals.

Requirements 

  • Make sure that the subscription is eligible:
    • Status needs to be Active or Past Due
    • Subscription cannot be evergreen
  • Email address must match that from the initial order. If shoppers change the email they need to re-enter the payment details.

 

Flow comparison

  • Longer purchase funnel
  • Complex flow
  • Unused subscriber and payment on file info
  • High risk of churn
  • Shorter purchase funnel
  • Streamlined flow
  • Uses both customer and payment on file information
  • Lower risk of churn
  • Increase Customer Lifetime Value (CLTV) and recurring revenue

 

Detailed 1-click subscription renewal flow

Identify returning customers

You particularly need either the Avangate customer reference or the external customer reference you control.

Use customer information

getCustomerSubscriptions 

 

If customers log into your system and you’ve mapped unique identifiers into the Avangate platform you can easily extract their subscription information.

 

Use subscription information

searchSubscriptions 

 

You can also use subscription information to extract customer references, based on a set of filters. Validate the status of the subscription (needs to be Active or Past Due).

  • Customer email
  • Delivered codes/activation keys
  • Avangate customer reference
  • External customer reference
  • Subscription status
  • Recurring billing status
  • Product code
  • Customer country
  • Purchased date
  • Expiration/Renewal deadline
  • Subscription type

 

Create the manual renewal link

getRenewalDetails 

Retrieve information regarding subscription renewals based on Avangate Subscription References:

  • Information on the automatic renewal (recurring billing) status (enabled or disabled).
  • The link that customers access to renew the subscription though a manual payment.

 

Attach the payment token to the manual renewal link

getSingleSignOnInCart

 

Avangate attaches a unique token to links, designed to identify the returning shoppers and support the automatic extraction of payment data and billing information from the Avangate system.

 

Example


<?php
 
function callRPC($Request, $hostUrl, $Debug = true) {
    $curl = curl_init($hostUrl);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSLVERSION, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
    $RequestString = json_encode($Request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString);
 
 
    if ($Debug) {
        $RequestString;
    }
    $ResponseString = curl_exec($curl);
    if ($Debug) {
        $ResponseString;
    }
 
    if (!empty($ResponseString)) {
        $Response = json_decode($ResponseString);
        if (isset($Response->result)) {
            return $Response->result;
        }
        if (!is_null($Response->error)) {
            var_dump($Request->method, $Response->error);
        }
    } else {
        return null;
    }
}
 
$host = 'https://api.avangate.com/rpc/3.0/';
 
$merchantCode = "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 = "SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
 
$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');
$hash = hash_hmac('md5', $string, $key);
 
$i = 1; // counter for API calls
// call login
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;
 
$sessionID = callRPC($jsonRpcRequest, $host);
 
var_dump($sessionID);
$SubscriptionSearch = new stdClass();
$SubscriptionSearch->CustomerEmail  = null;
$SubscriptionSearch->DeliveredCode = '___TEST___CODE____123';
$SubscriptionSearch->AvangateCustomerReference = '123456789';
$SubscriptionSearch->ExternalCustomerReference = null;
$SubscriptionSearch->Aggregate = false;
$SubscriptionSearch->SubscriptionEnabled = null; //true false null
$SubscriptionSearch->RecurringEnabled = null; // true - autorenewal, false - manual renewal, null = both(default) 
$SubscriptionSearch->ProductCodes = null; //array('Product_Code1', 'Product_Code2');
$SubscriptionSearch->CountryCodes = null;//array ('au')
$SubscriptionSearch->PurchasedAfter = null;
$SubscriptionSearch->PurchasedBefore = null;
$SubscriptionSearch->ExpireAfter = null;
$SubscriptionSearch->ExpireBefore = null;
$SubscriptionSearch->LifetimeSubscription = null;
$SubscriptionSearch->Type = 'regular'; //'trial', 'regular', 'regularfromtrial'
$SubscriptionSearch->TestSubscription = null; // true, false, null = both(default) 
$SubscriptionSearch->Page = 1;
$SubscriptionSearch->Limit = 10;

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

$allsubscriptions = callRPC((Object)$jsonRpcRequest, $host, true);
$subscriptionReference = $allsubscriptions[0]->SubscriptionReference;
 
$jsonRpcRequest = array (
'method' => 'getRenewalDetails',
'params' => array($sessionID, $subscriptionReference),
'id' => $i++,
'jsonrpc' => '2.0');

$manualrenewallink = callRPC((Object)$jsonRpcRequest, $host, true);

$IdCustomer = $allsubscriptions[0]->AvangateCustomerReference;
$CustomerType = 'AvangateCustomerReference';
$Url = $manualrenewallink->ManualRenewalLink;
$ValidityTime = 999;
$ValidationIp = null;

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

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

Update a subscription

Overview

Change specific details about a subscription. Use the updateSubscription method to change specific details about a subscription.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

Subscription

Required (Object)

 

You need to include the entire Subscription object keeping its structure unchanged (retrieve it using getSubscription) but you can update only specific parameters enumerated below.

 

EndUser

Object

 

 

End user details.

 

ExpirationDate

String

 

 

Subscription expiration date - If you changed the time zone for the 2Checkout API by editing system settings under Account settings, then 2Checkout calculates the ExpirationDate according to your custom configuration. Note: The default 2Checkout API time zone is GMT+02:00.

You cannot set an expiration date from the past.

 

SubscriptionEnabled

Boolean

 

 

Possible values: TRUE/FALSE

 

RecurringEnabled

Boolean

 

 

Possible values: TRUE/FALSE

 

ExternalCustomerReference

String

 

 

Unique customer alphanumeric (string) identifiers that you control. Use this to 

move a subscription from under a customer to another customer entity. 2Checkout moves subscription under the customer for which you provide the External customer reference during the subscription update process. View example.

 

ProductId

Int

 

 

System-generated unique product ID. Needs to be the ID of an existing product in the 2Checkout system created under your account.

The product ID governs the product to which the subscription is associated with.

Product types must match Regular - Regular or Bundle - Bundle.

IDs must identify products with the renewal system enabled (max billing cycle 36 months).

 

ProductName

String

 

 

The name of the product for identifier used under ProductID.

 

ProductQuantity

Int

 

 

Ordered quantity.

 

PriceOptionCodes

Array

 

 

Array of product options codes. Pricing options codes are case sensitive.

To impact the renewal price, the PriceOptionsCodes need to belong to price options of pricing configurations used for the product with which the subscription is associated.

 

All other parameters of the Subscription object are non-editable.

The 2Checkout system uses the updated subscription information for:

  • Manual and automatic renewals
  • Upgrades
  • Trial conversions

Response

Parameters Type/Description

Boolean

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

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReferenceTest = 'YOUR_SUBSCRIPTION_REFERENCE';

try{
    $retrievedSubscription = $client->getSubscription($sessionID, $subscriptionReferenceTest);
}

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

var_dump ($updatedSubscription);

$retrievedSubscription->RecurringEnabled = false;
$retrievedSubscription->SubscriptionEnabled = true;
$retrievedSubscription->ExpirationDate = '2020-12-12';

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

?>

 

One click (1-click) subscription upgrade

Overview

Avangate supports 1-click manual subscription upgrades for returning customers who paid for their previous orders with Credit/Debit cards.

In this scenario, you can facilitate subscription upgrades for subscribers by enabling them to use card on file information to pay for the upgrade.

How does this work? 

  1. Identify returning customers. 
  2. Identify valid upgrade options and costs.
  3. Create a tokenized manual subscription upgrade link and serve it to the returning customer.
  4. Customers using the link land a hosted shopping cart, chose one of their credit cards they previously used for purchases from your account/store and place the order.

 

What do shoppers see in the cart?

Availability

Please contact Avangate to start using one click (1-click) subscription upgrades.

Requirements 

  • Configure the upgrade product / subscription plan in your Control Panel. 
  • Email address must match that from the initial order. If shoppers change the email they need to re-enter the payment details.

 

Flow comparison

  • Longer purchase funnel
  • Complex flow
  • Unused subscriber and payment on file info
  • High risk of churn
  • Shorter purchase funnel
  • Streamlined flow
  • Uses both customer and payment on file information
  • Lower risk of churn
  • Increase Customer Lifetime Value (CLTV) and recurring revenue

 

Detailed 1-click subscription upgrade flow

Identify returning customers

You particularly need either the Avangate customer reference or the external customer reference you control.

Use customer information

getCustomerSubscriptions 

 

If customers log into your system and you’ve mapped unique identifiers into the Avangate platform you can easily extract their subscription information.

 

Use subscription information

searchSubscriptions 

 

You can also use subscription information to extract customer references, based on a set of filters. Validate the status of the subscription (needs to be Active or Past Due).

  • Customer email
  • Delivered codes/activation keys
  • Avangate customer reference
  • External customer reference
  • Subscription status
  • Recurring billing status
  • Product code
  • Customer country
  • Purchased date
  • Expiration/Renewal deadline
  • Subscription type

 

Validate upgrade options and costs

getProductUpgradeOptions

 

 

getProductUpgradeOptionsPrice

Retrieve the possible upgrade options for a subscription.

 

 

Retrieve information about the costs a customer incurs when upgrading a specific subscription

Create the manual upgrade link

To build custom upgrade links you need the following two elements:

1. The main upgrade path: 

https://secure.avangate.com/order/upgrade.php? or https://YourStore.com/order/upgrade.php? if you use a custom domain with Avangate 

2. The unique subscription identifier from the Avangate system: LICENSE=1234567.

The simplest upgrade link you can build is 

https://secure.avangate.com/order/upgrade.php?LICENSE=1234567

Attach the payment token to the manual Upgrade link

getSingleSignOnInCart

 

Avangate attaches a unique token to links, designed to identify the returning shoppers and support the automatic extraction of payment data and billing information from the Avangate system.

 

Example


<?php
 
function callRPC($Request, $hostUrl, $Debug = true) {
    $curl = curl_init($hostUrl);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSLVERSION, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
    $RequestString = json_encode($Request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString);
 
 
    if ($Debug) {
        $RequestString;
    }
    $ResponseString = curl_exec($curl);
    if ($Debug) {
        $ResponseString;
    }
 
    if (!empty($ResponseString)) {
        $Response = json_decode($ResponseString);
        if (isset($Response->result)) {
            return $Response->result;
        }
        if (!is_null($Response->error)) {
            var_dump($Request->method, $Response->error);
        }
    } else {
        return null;
    }
}
 
$host = 'https://api.avangate.com/rpc/3.0/';
 
$merchantCode = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php

 
$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');
$hash = hash_hmac('md5', $string, $key);
 
$i = 1; // counter for API calls
// call login
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;
 
$sessionID = callRPC($jsonRpcRequest, $host);
 
$SubscriptionSearch = new stdClass();
$SubscriptionSearch->CustomerEmail  = null;
$SubscriptionSearch->DeliveredCode = '___TEST___CODE____123';
$SubscriptionSearch->AvangateCustomerReference = '449686020';
$SubscriptionSearch->ExternalCustomerReference = null;
$SubscriptionSearch->Aggregate = false;
$SubscriptionSearch->SubscriptionEnabled = null; //true false null
$SubscriptionSearch->RecurringEnabled = null; // true - autorenewal, false - manual renewal, null = both(default) 
$SubscriptionSearch->ProductCodes = null; //array('Product_Code1', 'Product_Code2');
$SubscriptionSearch->CountryCodes = null;//array ('au')
$SubscriptionSearch->PurchasedAfter = null;
$SubscriptionSearch->PurchasedBefore = null;
$SubscriptionSearch->ExpireAfter = null;
$SubscriptionSearch->ExpireBefore = null;
$SubscriptionSearch->RenewedAfter = null;
$SubscriptionSearch->RenewedBefore = null;
$SubscriptionSearch->NotificationAfter = null;
$SubscriptionSearch->NotificationBefore = null;
$SubscriptionSearch->LifetimeSubscription = null;
$SubscriptionSearch->Type = 'regular'; //'trial', 'regular', 'regularfromtrial'
$SubscriptionSearch->TestSubscription = null; // true, false, null = both(default) 
$SubscriptionSearch->Page = 1;
$SubscriptionSearch->Limit = 10;
$jsonRpcRequest = array (
        'method' => 'searchSubscriptions',
        'params' => array($sessionID, $SubscriptionSearch),
        'id' => $i++,
        'jsonrpc' => '2.0');
$allsubscriptions = callRPC((Object)$jsonRpcRequest, $host, true);
$subscriptionReference = $allsubscriptions[0]->SubscriptionReference;

//retrieve all the upgrade options for a subscription
$jsonRpcRequest = array (
        'method' => 'getProductUpgradeOptions',
        'params' => array($sessionID, $subscriptionReference),
        'id' => $i++,
        'jsonrpc' => '2.0');
$optionsforUpgrade = callRPC((Object)$jsonRpcRequest, $host, true);
//retrieve information about the costs a customer incurs when upgrading a specific subscription
$productCode = $optionsforUpgrade[1]->ProductInfo->ProductCode;
$Currency = 'usd';
$Options = 'emailsupport'.';'.'oneuser1';
$jsonRpcRequest = array (
        'method' => 'getProductUpgradeOptionsPrice',
        'params' => array($sessionID, $subscriptionReference, $productCode, $Currency, $Options),
        'id' => $i++,
        'jsonrpc' => '2.0');
callRPC((Object)$jsonRpcRequest, $host, true);
$jsonRpcRequest = array (
        'jsonrpc' => '2.0',
        'id' => $i++,
        'method' => 'getProductByCode',
        'params' => array($sessionID, $productCode)
    );
$upgrtadebleProduct = callRPC((Object)$jsonRpcRequest, $host, true);
$upgrtadebleProductID = $upgrtadebleProduct->AvangateId;
$Options = 'emailsupport'.','.'oneuser1';//Replace the ; separator with , for use with query strings
 
//$upgradelink = "https://store.avancart.com/order/upgrade.php?LICENSE=".$subscriptionReference; //This is the simplest upgrade link you can build and use to generate a tokenized upgrade checkout URL
$upgradelink = "https://store.avancart.com/order/upgrade.php?LICENSE=".$subscriptionReference."&UPGRADEPROD=".$upgrtadebleProductID."&UPGRADEOPT=".$Options; 
$IdCustomer = $allsubscriptions[0]->AvangateCustomerReference;
$CustomerType = 'AvangateCustomerReference';
$Url = $upgradelink;
$ValidityTime = 10;
$ValidationIp = null;
$jsonRpcRequest = array (
        'method' => 'getSingleSignOnInCart',
        'params' => array($sessionID, $IdCustomer, $CustomerType, $Url, $ValidityTime, $ValidationIp),
        'id' => $i++,
        'jsonrpc' => '2.0');
$upgradeSSOURL = callRPC((Object)$jsonRpcRequest, $host, true);
header("Location: $upgradeSSOURL");

Enable a subscription

Overview

Use the enableSubscription method to enable a subscription.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

subscriptionReference

Required (string)

 

Unique, system-generated subscription identifier.

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 {
    $enabledSubscription = $client->enableSubscription($sessionID, $SubscriptionReference);
}
catch (SoapFault $e) {
    echo "enabledSubscription: " . $e->getMessage();
    exit;
}
var_dump("enabledSubscription", $enabledSubscription);

 

Use PayPal

Overview

Place an order with dynamic product information, and collect the payment using 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 into 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

Order information Type/Description
Order Object containing order information.

Request 

<?php
declare(strict_types=1);

class Configuration
{
    public const MERCHANT_CODE = '';
    public const MERCHANT_KEY = '';
    public const URL = 'http://api.2checkout.com/rpc/6.0';
    public const ACTION = 'placeOrder';
    public const ADDITIONAL_OPTIONS = null;
    //array or JSON
    public const PAYLOAD = <<<JSON
{
  "Country": "us",
  "Currency": "USD",
  "CustomerIP": "91.220.121.21",
  "ExternalReference": "RPC_API_AVANGTE",
  "Language": "en",
  "Source": "testAPI.com",
  "BillingDetails": {
    "Address1": "Test Address",
    "City": "LA",
    "State": "California",
    "CountryCode": "US",
    "Email": "testcustomer@2Checkout.com",
    "FirstName": "Customer",
    "LastName": "2Checkout",
    "Zip": "12345"
  },
  "Items": [
    {
      "Name": "Dynamic product",
      "Description": "Test description",
      "Quantity": 1,
      "IsDynamic": true,
      "Tangible": false,
      "PurchaseType": "PRODUCT",
      "Price": {
        "Amount": 100,
        "Type": "CUSTOM"
      },
      "PriceOptions": [
        {
          "Name": "OPT1",
          "Options": [
            {
              "Name": "Name LR",
              "Value": "Value LR",
              "Surcharge": 7
            }
          ]
        }
      ],
      "RecurringOptions": {
        "CycleLength": 2,
        "CycleUnit": "DAY",
        "CycleAmount": 12.2,
        "ContractLength": 3,
        "ContractUnit": "DAY"
      }
    }
  ],
  "PaymentDetails": {
    "Currency": "USD",
    "CustomerIP": "91.220.121.21",
    "PaymentMethod": {
      "RecurringEnabled": false,
      "ReturnURL": "http://secure.avangate.local/test/index.php",
      "CancelURL": "http://secure.avangate.local/test/create_order.php"
    },
    "Type": "PAYPAL"
  }
}
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, Configuration::ADDITIONAL_OPTIONS];
        }
        $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);

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