Retrieve SKU code by details
Overview
Use the getSKUCodeByDetails method to retrieve an SKU based on its included details.
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. |
|
skuDetailsObject |
Object |
|
|
Details below |
|
|
PricingConfigurationCode |
Required (string) |
|
|
Unique identifier of the pricing configuration. |
|
Currency |
Optional (string) |
|
|
ISO currency code. |
|
PurchaseType |
Optional (string) |
|
|
Purchase type identifier. Possible values:
|
|
PriceOptions |
Optional (stringArray) |
|
|
Array of price options names. |
|
Quantity |
Optional (int) |
|
|
Numeric identifier of product quantity. |
Request Example
<?php
require ('PATH_TO_AUTH');
$skuDetailsObject = new \stdClass();
$skuDetailsObject->PricingConfigurationCode = 'YOUR_CODE';
$skuDetailsObject->Currency = 'USD';
$skuDetailsObject->PurchaseType = 'NEW_PRODUCT';
$skuDetailsObject->PriceOptions = ['A'];
$skuDetailsObject->Quantity = 1;
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'getSKUCodeByDetails';
$jsonRpcRequest->params = array($sessionID, $skuDetailsObject);
$jsonRpcRequest->id = $i++;
$getSkuCodeByDetails = callRPC($jsonRpcRequest, $host);
var_dump($getSkuCodeByDetails);
Response Example
{SKUCode} // eg: SKU-EUR-1-10-N-A
Use custom pricing
Overview
Place an order with on the fly pricing using catalog products defined in your Control Panel. Set the Items->Price->Type parameter to CUSTOM, while adding the dynamic price to the Items->Price->Amount parameter.
Payment methods
You can place orders with dynamic pricing using the following payment methods:
- Credit cards
- PayPal
- WeChat Pay
- iDEAL
- Purchase Order
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. |
Response
Parameters | Type/Description |
---|---|
Object |
Request
<?php
require ('PATH_TO_AUTH');
$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->Affiliate = new stdClass();
$Order->Affiliate->AffiliateCode = 'Partner123'
$Order->Affiliate->AffiliateSource = 'MobilePlatform'
$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]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->Items[0]->SubscriptionStartDate = NULL; //If empty or null, subscriptions become active when purchase is made.
$Order->Items[0]->Price = new stdClass();
$Order->Items[0]->Price->Amount = 11; // set the price of the order
$Order->Items[0]->Price->AmountType = 'NET';
$Order->Items[0]->Price->Type = 'CUSTOM'; // must be sent as CUSTOM in order to use dynamic pricing
$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 = 'email@2checkout.com';
$Order->BillingDetails->Phone = NULL;
$Order->BillingDetails->Company = NULL;
$Order->DeliveryDetails = NULL;
$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'CC'; // you can also use TEST, PAYPAL, PURCHASEORDER, WE_CHAT_PAY, IDEAL, CHECK. The flow and requirements are different for each payment method.
$Order->PaymentDetails->Currency = 'usd';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '10.10.10.10';
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$Order->PaymentDetails->PaymentMethod->CardNumber = "4111111111111111";
$Order->PaymentDetails->PaymentMethod->CardType = 'visa';
$Order->PaymentDetails->PaymentMethod->ExpirationYear = '2019';
$Order->PaymentDetails->PaymentMethod->ExpirationMonth = '12';
$Order->PaymentDetails->PaymentMethod->HolderName = 'John';
$Order->PaymentDetails->PaymentMethod->CCID = '123';
$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'
);
echo "<pre>";
var_dump (callRPC((Object)$jsonRpcRequest, $host, true));
Single Sign On (SSO)
Overview
Redirect and login shoppers automatically from your user portal into their customer myAccount based on subscription or customer information.
Requirements
You need a custom domain to use Single Sign-On. Contact 2Checkout directly for guidance on how to set up a custom domain.
Retrieve all configurations
Overview
Use the getPricingConfigurations method to extract information on the pricing configurations you set for a product.
Parameters
Parameters | Type/Description |
---|---|
sessionID |
Required (string) |
|
Session identifier, the output of the Login method. Include sessionID into all your requests. 2Checkout throws an exception if the values are incorrect. The sessionID expires in 10 minutes. |
ProductCode |
Required (string) |
|
The editable code that you control at product-level, not the unique, system-generated product ID. |
Response
Parameters | Type/Description |
---|---|
Array of objects |
Request
<?php
require ('PATH_TO_AUTH');
$productCode = 'YOUR_PRODUCT_CODE';
try {
$ProductPricingConfigurations = $client->getPricingConfigurations($sessionID, $productCode);
}
catch (SoapFault $e) {
echo "Pricing Configurations: " . $e->getMessage();
exit;
}
var_dump("Pricing Configurations", $ProductPricingConfigurations);
?>
Update price options
Overview
Use the updatePriceOptionGroup method to update/edit an existing price options group you configured for your account.
- Price options intervals cannot overlap.
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. |
Required (object) |
|
|
Use this object to update/edit a new price option group for your account. |
You cannot update the
- Code of the price options group.
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.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;
}
$SearchOptions = new stdClass();
$SearchOptions->Name = 'New Users from API';
$SearchOptions->Types = array(
'INTERVAL',
'RADIO',
'COMBO'
); //RADIO, CHECKBOX, INTERVAL, COMBO, INTERVAL
$SearchOptions->Limit = 10;
$SearchOptions->Page = 1;
try {
$existentPriceOptions = $client->searchPriceOptionGroups($sessionID, $SearchOptions);
}
catch (SoapFault $e) {
echo "existentPriceOptions: " . $e->getMessage();
exit;
}
var_dump("existentPriceOptionst", $existentPriceOptions);
$existentPriceOptions[0]->Translations[0]->Name = 'New Users from API_1';
$existentPriceOptions[0]->Translations[0]->Language = 'EN';
$existentPriceOptions[0]->Required = FALSE;
echo "\n";
var_dump($existentPriceOptions);
try {
$NewPriceOptionGroup = $client->updatePriceOptionGroup($sessionID, $existentPriceOptions[0]);
}
catch (SoapFault $e) {
echo "NewPriceOptionGroup: " . $e->getMessage();
exit;
}
var_dump("NewPriceOptionGroup", $NewPriceOptionGroup);
?>
Update subscription payment information
Overview
Use the updateSubscriptionPaymentInformation method to update the credit card information related to the payment to be made for a subscription. To be able to do this, you need to generate a payment token using the credit card information via the 2Pay.js library, and then use this token in the request of the method as indicated below.
Request Parameters
Parameter Name | Type | Required/Optional | Description |
---|---|---|---|
sessionID |
String |
Required |
The 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 |
String |
Required |
The reference of the subscription for which you want to retrieve the payment information. |
paymentInformation |
Object |
Required |
The payment information object, details below: |
PaymentDetails |
Object |
Required |
The payment details object, details below: |
Type |
String |
Required |
The payment details type. Restricted to EES_TOKEN_PAYMENT for now. |
PaymentMethod |
Object |
Required |
The payment method object, details below: |
EesToken |
String |
Required |
The 2Pay token obtained by integrating the 2Pay.js library. |
Vendor3DSReturnURL | String | Required | URL address to which customers are redirected after the 3DS details get validated by the bank and the order is successfully authorized. |
Vendor3DSCancelURL | String | Required | URL address to which customers are redirected after the 3DS details get validated by the bank and the order is successfully authorized. |
Request Example
<?php
declare(strict_types=1);
class Configuration
{
public const MERCHANT_CODE = '';
public const MERCHANT_KEY = '';
public const URL = 'http://api.2checkout.com/soap/6.0';
public const ACTION = 'updateSubscriptionPaymentInformation';
public const ADDITIONAL_OPTIONS = null;
public const SUBSCRIPTION_REF = 'YC9XXMGOYO';
//array or JSON
public const PAYLOAD = <<<JSON
{
"PaymentDetails": {
"Type": "EES_TOKEN_PAYMENT",
"PaymentMethod": {
"EesToken": "f6347256-bbbb-45a8-be61-e21fe1725f47",
"Vendor3DSReturnURL": "www.3dsReturnURL.com",
"Vendor3DSCancelURL": "www.3dsCancelURL.com"
}
}
}
JSON;
}
class Client
{
public function call(
string $url = Configuration::URL,
$payload = Configuration::PAYLOAD,
string $action = Configuration::ACTION
): ?object
{
if (is_array($payload)) {
$payload = json_encode($payload);
}
if (!empty($payload)) {
// SoapClient works with objects(StdClass)
$payload = json_decode($payload);
}
$soapClient = $this->getClient($url);
$sessionId = $this->getSession($soapClient);
$args = array_filter([$sessionId, Configuration::SUBSCRIPTION_REF, $payload]);
return $soapClient->$action(...$args);
}
public function getClient(string $url): SoapClient
{
return new SoapClient(
$url . '?wsdl',
[
'location' => $url,
'cache_wsdl' => WSDL_CACHE_NONE,
]
);
}
public function getSession(SoapClient $client)
{
$date = gmdate('Y-m-d H:i:s');
$merchantCode = Configuration::MERCHANT_CODE;
$key = Configuration::MERCHANT_KEY;
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
$hash = hash_hmac('md5', $string, $key);
// $client->__setCookie('XDEBUG_SESSION', 'PHPSTORM');
return $client->login($merchantCode, $date, $hash);
}
}
try {
$client = new Client();
var_dump($client->call());
} catch (Exception $ex) {
var_dump($ex);
}
Response
The method responds with Boolean True when the payment information update was successfully performed.
Otherwise, in case of validation or access rights failures, it returns the usual error response with specific messages indicating the cause of the failure.
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/ xmlns:ns1="urn:order" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:SOAP-ENC=http://schemas.xmlsoap.org/soap/encoding/ SOAP-ENV:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/>
<SOAP-ENV:Body>
<ns1:updateSubscriptionPaymentInformationResponse>
<updateSubscriptionPaymentInformationReturn xsi:type="ns1:PaymentDetailsCard">
<CardType xsi:type="xsd:string">visa</CardType>
<FirstDigits xsi:type="xsd:string">4012</FirstDigits>
<LastDigits xsi:type="xsd:string">9936</LastDigits>
<Authorize3DSUrl xsi:type="xsd:string">https://...</Authorize3DSUrl>
</updateSubscriptionPaymentInformationReturn>
</ns1:updateSubscriptionPaymentInformationResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Search promotions
Overview
Use the searchPromotions method to extract information on promotions you set up for your account.
Parameters
Parameters | Type/Description |
---|---|
sessionID |
Required (string) |
|
Session identifier, the output of the Login method. Include sessionID into all your requests. 2Checkout throws an exception if the values are incorrect. The sessionID expires in 10 minutes. |
Types |
StringArray |
|
Discount type:
|
Channel |
String |
|
Channel:
|
ProductCode |
String |
|
Unique code that you set for each of your products. |
Pagination |
Object. Details below. |
Limit |
Int |
|
Set a limit for the number of results that should be returned. |
Page |
Int |
|
Set the number of pages that should be returned. |
Response
Parameters | Type/Description |
---|---|
Promotion | Array of objects |
Request
<?php
require ('PATH_TO_AUTH');
$searchOptions = new stdClass();
$searchOptions->Types = array ('REGULAR');
$searchOptions->Channel = 'ECOMMERCE';
$searchOptions->ProductCode = 'Product_Code_1';
$searchOptions->Enabled = TRUE;
$searchOptions->Limit = 99;
$searchOptions->Page = 1;
try {
$Discounts = $client->searchPromotions($sessionID, $SearchOptions);
}
catch (SoapFault $e) {
echo "Discounts: " . $e->getMessage();
exit;
}
var_dump("Promotions", $Discounts);
Retrieve a customer
Overview
Use the getCustomerInformation method to retrieve the details of a customer entity from 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. |
2CheckoutCustomerReference |
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 2CheckoutCustomerReference. If you include it, it needs to belong to the same customer as the 2CheckoutCustomerReference. |
Response
Object |
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;
}
$customerReference = 298084139;
$externalCustomerReference = 'Apitest123456'; //Optional, but if you include it it needs to belong to the same customer as the internal 2Checkout customer reference
try {
$customerInfo = $client->getCustomerInformation($sessionID, $customerReference, $externalCustomerReference);
}
catch (SoapFault $e) {
echo "customerInfo: " . $e->getMessage();
exit;
}
var_dump("customerInfo", $customerInfo);
Signature validation for return URL via InLine checkout
Overview
To start, you need to generate the InLine checkout content using the TwoCoInlineCart client.
At this step, you must add a product to your cart, set the return method, and set a previously generated cart payload signature.
TwoCoInlineCart.cart.setCurrency('USD');
TwoCoInlineCart.products.add({
code : 'TEST_PROD',
quantity: 1,
price : 29
});
TwoCoInlineCart.cart.setReturnMethod({
type: 'redirect',
url : 'https:\/\/yourbackend.com\/'
});
TwoCoInlineCart.cart.setSignature('314cfb1f277ef89f9f3735517...........1c62abee466c9d1774bf1e4655f0');
After triggering TwoCoInlineCart.cart.checkout(); the InLine checkout will initialize in the new iframe.
In case of a valid signature, the cart will boot and the shopper can complete the order. Otherwise, he will see an empty cart page.
In case of a valid signature and successful order placing, the shopper is redirected to the page you have defined in the return parameters. The return URL is appended with some return parameters which are refno, total, total-currency, all of them are signed and their signature should be present in the query parameters.
In the backend, you need to gather all these parameters and validate the parameters' hash you generate with the new signature appended to the return-URL.
To generate the hash and validate the return URL, follow the steps below.
Build the InLine Checkout Signature
To sign an InLine checkout buy-link, you need to follow these steps:
- Sort the parameters that require a signature alphabetically.
- Serialize the parameters and append to them the length of their values.
- Concatenate the resulting values.
- The serialized value is then encrypted with your Buy-Link Secret Word using the HMAC method (algorithm sha256).
- The resulting value is added to the buy-link under the signature parameter.
In order to generate a valid InLine checkout signature, you should include all the parameters from the return URL, except the signature.
Example
When encrypting the values to generate the signature, for the return-url parameter, use an URL with the following structure: https://..... Do not use an encoded URL.
1. Let's consider the following parameters:
- refno = 11606896
- total = 29
- total-currency = USD
The regular return link will have the following structure:
https://www.yourbackend.com/?refno=11606896&total=29&total-currency=USD&signature=08448c91bbb314cfb1f277ef89f9f37355171c62abee466c9d1774bf1e4655f0
2. Sort the parameters alphabetically: refno, total, total-currency.
3. Serialize the values. To serialize a value, you need to append before it the number of letters or digits a value has. For example, the return-type parameter has the 'redirect' value that will be serialized as '8redirect'', where 8 is the number of characters that make up the value.
- refno - 811606896
- total - 229
- total-currency - 3USD
4. Concatenate the values: 118116068962293USD
5. Encrypt using your Secret Word
The serialized value is then encrypted using the HMAC method.
- the algorithm used is sha256
- the key used when encrypting is the merchant secret word (in this example, the secret word is 'vendor-secret-key')
This outputs a 64 character string:
08448c91bbb314cfb1f277ef89f9f37355171c62abee466c9d1774bf1e4655f0
Also, you can use HashValidationTool:
<?php
class HashValidationTool
{
const SHA_256 = 'sha256';
private $params;
private $signature;
private $key;
/**
* HashValidationTool constructor.
*
* @param string $key
*/
public function __construct(string $key)
{
$this->key = $key;
}
/**
* @return string
*/
private function encrypt(): string
{
$serialized = $this->serializeParameters($this->params);
if (strlen($serialized) > 0) {
echo 'Success: serialized params - ' . $serialized . PHP_EOL;
return bin2hex(hash_hmac(self::SHA_256, $serialized, $this->key, true));
} else {
echo 'Error: serialization parameters are empty' . PHP_EOL;
return '';
}
}
/**
* @param string $url
*
* @return bool
*/
public function validate(string $url): bool
{
$this->setUrl($url);
return $this->encrypt() === $this->signature;
}
/**
* @param array $array
*
* @return string
*/
private function serializeParameters(array $array): string
{
ksort($array);
$serializedString = '';
foreach ($array as $value) {
if (is_array($value)) {
$serializedString .= $this->serializeParameters($value);
} else {
$serializedString .= strlen($value) . $value;
}
}
return $serializedString;
}
/**
* @param string $url
*/
private function setUrl(string $url): void
{
$urlParts = parse_url($url);
parse_str($urlParts['query'], $this->params);
$this->signature = $this->params['signature'];
unset($this->params['signature']);
}
}
$hashValidationTool = new HashValidationTool('vendor-secret-key');
if ($hashValidationTool->validate('https://www.yourbackend.com/?merchant=YOUR_VENDOR_CODE¤cy=USD&return-url=https://yourbackend.com/&return-type=redirect&tpl=default&prod=TEST_PROD&price=29&qty=1&refno=11606896&total=29&total-currency=USD&signature=95052ee0c558b53040e97d7d81add2e0f1400ca0936a558910c68ddc8301fc63')) {
echo 'valid';
} else {
echo 'invalid';
}
The successful order placement flow with a valid signature for the InLine checkout is described in the following diagram.