Skip to main content

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.2checkout.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 = "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;
}
$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@2checkout.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");

 

Retrieve pricing configurations

Overview

Use the getPricingConfigurations method to extract information on the pricing configurations you set for a subscription plan/product.

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.

ProductCode

Required (string)

 

The editable code that you control at product-level, not the unique, system-generated product ID.

Response

PricingConfiguration

Array of objects

Request

<?php

$host   = "https://api.2checkout.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.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;
}

$ProductCode = 'AAA4643116';

try {
    $ProductPricingConfigurations = $client->getPricingConfigurations($sessionID, $ProductCode);
}

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

var_dump("Pricing Configurations", $ProductPricingConfigurations);


?>

 

Retrieve a customer’s subscriptions

Overview

Extract all subscriptions belonging to a customer. Use the getCustomerSubscriptions method to retrieve details about the subscriptions belonging to a specific customer.

Subscriptions can be retrieved starting with 5 minutes after their orders are generated in the 2Checkout system.

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.

avangateCustomerReference

Required (int)

 

System-generated customer reference. Required unless you prefer to use ExternalCustomerReference.

externalCustomerReference

Optional (string)

 

External customer reference that you control. Optional when you use AvangateCustomerReference. If you include it, it needs to belong to the same customer as the AvangateCustomerReference.

Response

Parameters Type/Description

Subscription

Array of objects

Request

<?php

require ('PATH_TO_AUTH');

$customerReference = YOUR_CUSTOMER_REFERENCE;

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

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

Import/Export product data using CSV files

Overview

Use CSV (Comma Separated Values) files to import new products, but also update existing details.

Availability

All 2Checkout accounts.

Requirements

  • Use UTF-8 character encoding.
  • Mandatory headers. During the import process, the system validates column headings, and matches them with actual product fields. If the mandatory headers don't exist within the CSV file, along with their respective columns and the information they are supposed to contain, the import process fails.
    • EN Product name - the product name in English.
    • Price type - there are two possible values net and gross.
    • Price - you need to enter the product price at least for the default currency - zero and negative values are not supported.
    • Default Currency - possible values in accordance to the languages available for your account.
    • Status - used to set products either as active or disabled. An empty value is the same as active.
  • Commas and double quotes. CSV files contain fields separated by commas and are used to migrate data between systems. In addition to commas, double quotes, also known as text qualifiers, are also very important when dividing the data in a CSV file. Follow this syntax rule: place values first within double quotes and then separate them by commas. For example, an enumeration of product name headings for German, English, Spanish and French - "DE Product name","EN Product name","ES Product name","FR Product name". This type of syntax is valid not just for column headers, but also for all other pieces of information in a CSV file. Make sure to use commas and double quotes only to separate values and data fields, and refrain from introducing them in the CSV document for any other purposes, as they can create problems and generate import failures when placed improperly.
  • End of line characters. Every record must be separated by new line (rn or 0x0D0x0A). What this means is that each product in a CSV file with multiple items has to have all its information on its own, separate row. At the end of this row, it's necessary to have an end of line character, such as rn or 0x0D0x0A. An end of line (EOL) character, also known as a newline, or a line break, to separate a record in a CSV file from the next.

Limitations

  • 2Checkout recommends using XML files when importing products due to the limitations of the CSV import functionality around managing advanced pricing configurations such as pricing options and pricing options groups.
  • Importing products via CSV files is best suited to items with a base price (dynamic). The value you enter under the mandatory Price column defines the base price of the product (cannot be 0 or negative).
  • For products without a base price (flat), this value (cannot be 0 or negative) will only configure the first volume interval, 1 to maximum, and set its price. You cannot define any additional intervals for products without a base price using CSV files. Consider using the Upload from CSV available on the pricing tab to update prices with a base price.
  • Consider manually editing product information of complex pricing schemes, including but not limited to volume discounts, renewals price, promotions, pricing options groups, or any other parameters that impact price.
  • When updating products without a base price using a CSV file, the system ignores the values under the Price column if the refreshed items already have pricing schemes configured, and operates no changes.
  • Exporting up to 1000 products is done on the spot.
  • Exporting more than 1000 products lasts longer and is done in the background. 2Checkout can notify you via email when your export file is ready and provides you with the download link.

Prepare the CSV product data file

  1. Check that the CSV file adheres to all the requirements. The 2Checkout system matches details in the CSV files with actual product fields in relation to column headers, and as such, the actual order of the headers and columns is irrelevant.
  2. The CSV file sample available in your Control Panel tailors itself automatically to your account's default language and currency settings. The localization details and financial info configuration of your account will determine the availability of extra column headers, in accordance to any extra languages and currencies available.
  3. With the exception of the mandatory headers and their columns, you can remove all other content completely.
    • Product name (in all languages enabled for your account)
    • Product Code
    • Product Version
    • ID Shipping Class
    • Gift Option
    • Short description (in all languages enabled for your account)
    • Long description (in all languages enabled for your account)
    • System Requirements (in all languages enabled for your account)
    • Platforms
    • Download Link (in all languages enabled for your account)
    • Download Description (in all languages enabled for your account)
    • Price Configuration Type
    • Price Type
    • Default Currency
    • Price (for all currencies enabled for your account)
    • Status
    • 2Checkout ID

Add new products

  1. Once you finalized the CSV file, navigate to Products under Setup, and then click on the Import products button on the left hand side of the screen, underneath the Search products area.
  2. Under the Import from file tab, click Browse and navigate to the location where you saved the CSV file, select it and hit the Next step button. Provided that all headers are correct, and their columns are filled with the necessary details, 2Checkout imports the new products into the system.
  3. Hit the Finish import button and then OK to finalize the process. Click Cancel to stop the process from moving to the final stage in case you notice problems when importing. You will need to confirm the cancelation.
  4. 2Checkout provides a summary of the importing process and the changes you introduced.

Non-mandatory columns for which you don't want to import any information can be empty. You can even delete non-mandatory columns along with their headers from the CSV file, if you consider them irrelevant. The system will also offer you the possibility to ignore specific columns when it doesn't identify them properly and if they're not among the mandatory columns.

Immediately after the import process is finalized, you'll find the newly imported product listed under Setup, Products, where you can access its details and edit them further, if you so require.

Update existing products

In addition to adding new products from scratch, CSV files can also be used to update items that you already added into the 2Checkout platform. If you created and saved the CSV file with the changes you wish to implement, then simply upload it by following the normal steps of the product import process.

Download a CSV with your product info

  1. Under Setup, navigate to Products, and then click on the Import products button on the left hand side of the screen, underneath the Search products area.
  2. Scroll down at the bottom of the screen and hit the Download CSV in the Export products area. You'll export and download a CSV file listing all your active products.

This CSV file contains all product information already in the system, all of which editable. There are three editing strategies possible:

  • Updating info - If you simply modify existing details and introduce new info, for example, when uploading the new CSV file, any existing information will be updated, reflecting the changes you made.
  • Deleting info - If you preserve the columns and headers, but remove all content (as long as it's not mandatory content), when uploading the new CSV file, the system will delete all existing information matching the fields you left empty.
  • Preserving existing info - If you delete the columns and their headers altogether (as long as their presence is not required), the system will preserve the existing product information intact, and make no alterations. Use this method to avoid altering relevant info that you want to keep in place and which doesn't need updating.

Disable and enable existing products

  1. To change a product's status to inactive, essentially disabling it, open the CSV file for that item, and find the Status column header.
  2. Change the value under Status from active to disabled to render the product inactive. Similarly, swap disabled for active to re-enable a product.
  3. Once you made the necessary modifications to the CSV file, save it, getting it ready for import.

FAQ

Can I import/update images using a CSV file?

No. You can only add details for the fields matched with the following column headers: product name , product code, product version, id shipping class, gift option, short description, long description, system requirements, platforms, download link, download description, price configuration type, price type, default currency, price, status, 2Checkout ID (the ID cannot be updated once the product was added). Once you import a new product, all its information is available for editing in your Control Panel, under Setup, Products, and you can easily add images.

Can I use a CSV file to configure pricing options for products?

No. You can use CSV files to define a base price, or set up the pricing for the volume interval (1 to maximum) for products without a base price. You need to manually edit product information to configure more complex pricing schemes, including but not limited to volume discounts, renewals price, promotions, pricing options groups, or any other parameters that impact price.

How do I format numbers?

When creating and editing CSV files, it's best to limit the use of commas only to separate values.

  • Use a dot and not a comma to represent decimals: 0.1 instead of 0,1.
  • Write larger numbers without separating hundreds and thousands, etc. For example, one million should be represented as 1000000 and not 1,000,000. Do not use commas to separate thousands from hundreds, millions from hundred thousands, etc. in numbers with in excess of five digits.

Is there a limit to how many products can be imported simultaneously via the same CSV file?

No. But be advised that the performance of the importing process will degrade when larger CSV files are used.

The Download CSV option is not available for my account. Why?

You first need to set up at least one product, and set its status to active, before you can export a list of active items.

Can I manually map CSV columns to product fields?

Yes. In the eventuality that you exported the CSV file from another application or service and some heading information is incorrect, the system will give you the chance to manually map the headers with the fields they correspond to. However, this scenario involves only mislabeled headings, and your file needs to contain the columns associated to mandatory headers as well the right information in place. Only then will the system correctly detect the data properly.
Each column in a CSV file can be associated to a single field. The importing process will not move on until all columns are correctly assigned to their respective fields. Also, you can't match a column with more than one field.

Is it possible not to enter any values under CSV columns?

Yes. But only as long as they're not mandatory columns. For an empty field value leave a null value between commas, namely simply write two commas in succession without entering any parameters. The system will identify this as an empty field value.

Does 2Checkout synchronize Control Panel changes to product configuration into the file on a third-party server?

Automating the import process provides extra flexibility and control over product management, enabling you to only edit the CSV file, and have the information seamlessly uploaded into the 2Checkout platform. 2Checkout does not save any changes you make to product information or configuration using your Control Panel into the CSV file on your servers.

Place an order with WeChat Pay

Overview

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

Requirements

WeChat Pay is available only for orders with a minimum value of 0.01 USD, placed by shoppers in China or Hong Kong and using one of the supported currencies. You are required to include the following text when using 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. 

Supported currencies

  • CNY
  • USD
  • HKD

Workflow

  1. Shoppers select WeChat as payment option in the interface you provide to them.
  2. Create the order object. Use WE_CHAT_PAY as the type of the PaymentDetails object, and include ReturnURL and CancelURL.
  3. Use the placeOrder method to send the data to 2Checkout.
  4. Once you place the order, 2Checkout logs it into the system. At this point in time, the status of the order is PENDING.
  5. 2Checkout returns an Order object as the output of the placeOrder method. 
  6. Use the PaymentMethod object to create a redirect URL for the shoppers, concatenating the values of the Href and avng8apitoken parameters. Here's an example of the redirect URL:
    https://api.2checkout.com/4.0/scripts/we_chat_pay/authorize/?avng8apitoken=1abc7fd72d008428
  7. After being redirected to WeChat Pay, shoppers need to scan the QR code provided, using the WeChat smartphone app.
  8. After customers enter their payment password, WeChat notifies 2Checkout if the payment is approved, and the status of the order becomes COMPLETE.
  9. Shoppers are redirected to the RedirectURL from the Order information object. In case the payment fails, shoppers are redirected to the CancelURL.

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 WeChat, use WE_CHAT_PAY as the type of the PaymentDetails object and provide a ReturnURL and a CancelURL as part of the PaymentMethod object. See code sample. 

 

Response

Order information

Object

Request

<?php

// authentication script: https://knowledgecenter.2checkout.com/Integration/SOAP_API/API_4.0/02Authentication

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->RefNo = NULL;
$Order->Currency = 'cny';
$Order->Country = 'cn';
$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 = 'CN';
$Order->BillingDetails->State = 'State Example';
$Order->BillingDetails->City = 'City Example';
$Order->BillingDetails->Address1 = 'Address example';
$Order->BillingDetails->Address2 = NULL;
$Order->BillingDetails->Zip = '12345';
$Order->BillingDetails->Email = 'email@address.com';
$Order->BillingDetails->Phone = NULL;
$Order->BillingDetails->Company = NULL;
$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'WE_CHAT_PAY';
$Order->PaymentDetails->Currency = 'cny';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '91.220.121.21';
$Order->PaymentDetails->PaymentMethod->ReturnURL = 'YOUR_RETURN_URL';
$Order->PaymentDetails->PaymentMethod->CancelURL= 'YOUR_CANCEL_URL';

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

$wechatredirect = $newOrder->PaymentDetails->PaymentMethod->Authorize->Href."/?avng8apitoken=".$newOrder->PaymentDetails->PaymentMethod->Authorize->Params->avng8apitoken;

header('Location:' . $wechatredirect);
?>

 

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:

  • TRUE - to send a notice informing customers of product shipment.
  • FALSE - will not trigger a customer notification

Request

require('PATH_TO_AUTH');

$RefNo = "789527422";
$TrackingNumber = '921840912';
$StopCustomerNotification = 1;
$Comment = "We send this note to confirm the shipment of your products.";


$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'markShipped';
$jsonRpcRequest->params = array($sessionID, $RefNo, $TrackingNumber, $StopCustomerNotification, $Comment);
$jsonRpcRequest->id = $i++;

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

var_dump($markOrderAsShipped);

Response

boolean

 

Enable/Disable products

Overview

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

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

productCode

Required (string)

 

Use this object to configure your subscription plan/products.

 

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

Status

Required (Boolean)

 

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

Response

bool(true)

Request

<?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)) {
//        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.0/';
 
$merchantCode = "YOURCODE12345";//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 the login method for authentication
 
$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);
 
$productCode = "YourProductCode";
 
$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'setProductStatus',
'params' => array($sessionID, $productCode, true)
);
 
var_dump (callRPC($jsonRpcRequest, $host));
 
 
?>

Assign price option group

Overview

Use the assignPricingConfigurationOptionGroup method to assign a PricingOption Group to a PricingConfiguration.

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.

PricingConfigurationCode

Required (string)

 

Unique, system-generated pricing configuration identifier.  

PriceOptionsGroupAssigned

Required (Object)

 

Details below.

 

Parameters Type/Description

PriceOptionsGroupAssigned

Object

Code

Required (string)

 

PricingOption Group identifier.

Required

Required (Object)

 

True or false depending on whether the pricing options group is required during the purchase process or not.

Response

bool(true)

Request

<?php

require ('PATH_TO_AUTH');

$PricingConfigurationCode = 'YOUR_CODE';
$PriceOptionsGroupAssigned = new stdClass();
$PriceOptionsGroupAssigned->Code = 'USERSUSERS';
$PriceOptionsGroupAssigned->Required = TRUE;

try {
    $AssignedOption = $client-> assignPricingConfigurationOptionGroup ($sessionID, $PricingConfigurationCode, $PriceOptionsGroupAssigned);
}

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

var_dump("Options", $AssignedOption);

?>

 

Remove promotions translations

Overview

Use the deletePromotionTranslations method via SOAP API 4.0 to remove all localized texts from 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 translations to.

Response

Parameters Type/Description

Status

Boolean

  True or false.

Request

<?php 

class Client
{
    protected static $merchantCode;
    protected static $loginDate;
    protected static $hash;
    protected static $baseUrl;
    protected static $callCount = 0;
    protected static $sessionId = '';

    protected static $client;

    public static function setCredentials($code, $key)
    {
        static::$merchantCode = $code;
        static::$loginDate = gmdate('Y-m-d H:i:s');
        static::$hash = hash_hmac('md5', strlen($code) . $code . strlen(static::$loginDate) . static::$loginDate, $key);
        static::$sessionId = static::login();
    }

    public static function setBaseUrl($url)
    {
        static::$baseUrl = $url;
    }

    public static function login()
    {
        $client = static::getClient();
        return $client->login(static::$merchantCode, static::$loginDate, static::$hash);
    }

    public static function __callStatic($name, $arguments = array())
    {
        $client = static::getClient();

        array_unshift($arguments, static::$sessionId);
        $response = call_user_func_array(array($client, $name), $arguments);

        return $response;
    }

    protected static function getClient()
    {
        $opts = array(
            'http'=> ['user_agent' => 'PHPSoapClient'],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        );

        if (null === static::$client) {
            static::$client = new \SoapClient(static::$baseUrl . '?wsdl', [
                'location' => static::$baseUrl,
                'cache_wsdl' => WSDL_CACHE_NONE,
                'stream_context' => stream_context_create($opts),
            ]);
        }

        return static::$client;
    }
}

Client::setBaseUrl('https://api.2checkout.com/soap/3.1/');
Client::setCredentials('YOUR_MERCHANT_CODE', 'YOUR_SECRET_KEY');
Client::login();

$promotionCode = 'YOUR_PROMOTION_CODE'; // code of the promotion that you want to update

$response = Client::deletePromotionTranslations($promotionCode); // remove all translations
var_dump($response);

 

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

 

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