Skip to main content

Add promotion coupon

Overview

Use the addPromotionCoupon method via JSON-RPC API 4.0 to add single or multiple coupons to a 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 coupons to.

promotionCoupon

Required (object)

 

type

Required (string)

 

 

Coupon type. Available values:

  • SINGLE, use in conjunction with Code
  • MULTIPLE, use in conjunction with Codes

 

Code/Codes

Required (string / array of strings)

 

 

Coupon code (for SINGLE) or array of coupon codes (for MULTIPLE).

Response

Parameter Type/Description
promotionCoupon Object

Request

<?php

function callRPC($Request, $host, $Debug = true) {
    $curl = curl_init($host);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSLVERSION, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
    $RequestString = json_encode($Request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString);
    if ($Debug) {
        $RequestString;
    }
    $ResponseString = curl_exec($curl);
    if ($Debug) {
        $ResponseString;
    }
    if (!empty($ResponseString)) {
        var_dump($ResponseString);
        $Response = json_decode($ResponseString);
        if (isset($Response->result)) {
            return $Response->result;
        }
        if (!is_null($Response->error)) {
            var_dump($Request->method, $Response->error);
        }
    } else {
        return null;
    }
}

$host = 'https://api.avangate.com/rpc/3.1/';

$merchantCode = "YOUR_MERCHANT_CODE"; // your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY"; // your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php

$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');
$hash = hash_hmac('md5', $string, $key);

$i = 1;

$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;

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

// Promotion code corresponding to the promotion you want to add coupons to
$promotionCode = '';

// Define single coupon object
$promotionCoupon = new stdClass;
$promotionCoupon->Type = 'SINGLE';
$promotionCoupon->Code = 'YOUR_CODE_HERE';

// Define multiple coupon object
$promotionCoupon = new stdClass;
$promotionCoupon->Type = 'MULTIPLE';
$promotionCoupon->Codes = ['YOUR_CODE_1', 'YOUR_CODE_2'];

$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'addPromotionCoupon',
'params' => array($sessionID, $promotionCode, $promotionCoupon)
);
var_dump (callRPC($jsonRpcRequest, $host));

API Authentication

Overview

The 2Checkout API requires you to authenticate for any requests. Follow the steps below to learn how to authenticate in order to use the 2Checkout API.

How to authenticate

This is achieved via digest access authentication, using your Merchant Code & Secret Key. These can be found in your 2Checkout Merchant Control Panel, under Integrations → Webhooks & API.

merchant code_secret Key in control panel.png

To authenticate, you must first generate a hash code that will then be used together with your Merchant Code. The string used in the hash function is generated by concatenating the following values (in this order):

  1. Length of your Merchant Code
  2. Merchant Code
  3. Length of the current DateTime formated as Y-m-d H:i:s
  4. Current DateTime 

For example, for Merchant Code “YOURCODE123“ trying to authenticate on 2020-06-18 08:05:46 GMT, the string that needs to be hashed would look like: “11YOURCODE123192020-06-18 08:05:46”.

Once the string has been generated, this needs to be hashed using the SHA algorithm and the Secret Key available in the 2Checkout Merchant Control Panel. 

Hashing algorithms available

Starting with API 6.0, authentication in the API supports the 256-bit variant of each of the two SHA (Secure Hash Algorithm) families, meaning SHA2 and SHA3.

In PHP, this would look like:

$merchantCode = "YOUR_MERCHANT_CODE";  
$key = "YOUR_SECRET_KEY";  

$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');  

$algo = "SHA3-256"; 

$hash = hash_hmac($algo, $string, $key);

Authenticating on REST protocol

Authentication on REST is done via an X-Avangate-Authentication header provided on all requests. The X-Avangate-Authentication header value contains the Merchant Code, request DateTime, and the hash generated above. 

The format of the header is:

X-Avangate-Authentication: code="{MERCHANT_CODE}" date="{REQUEST_DATE_TIME}" hash="{HASH}" algo="{ALGO}"

Once the hash has been generated, this can be used to authenticate on any of the three protocols.

<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 

# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm , $string, $key); 
$payload = ''; 

$ch = curl_init(); 

$headerArray = [ 
"Content-Type: application/json", 
"Accept: application/json", 
"X-Avangate-Authentication: code=\"{$merchantCode}\" date=\"{$date}\" hash=\"{$hash}\" algo=\"{$hashAlgorithm}\"" 
];
 
curl_setopt($ch, CURLOPT_URL, $host); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSLVERSION, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); 

$response = curl_exec($ch);

Authenticating on SOAP protocol

Authentication on SOAP is done via the login method, using the hash generated above. Once the session id is returned by the login method, this will be used in all subsequent API requests.  

A full-working example in PHP for SOAP login looks like:

<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 

# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm, $string, $key); 

try { 
    $sessionID = $client->login($merchantCode, $date, $hash, $hashAlgorithm); 
    print_r($sessionID); 
} catch (SoapFault $e) { 
    echo $e->getMessage(); 
} 

Authenticating on RPC protocol

Authentication on RPC is done via the login method, using the hash generated above. Once the session id is returned by the login method, this will be used in all subsequent API requests.

A full-working example in PHP for RPC login looks like:

<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 
 
# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm , $string, $key); 

$i = 1; 
$jsonRpcRequest = new stdClass(); 
$jsonRpcRequest->jsonrpc = '6.0'; 
$jsonRpcRequest->method = 'login'; 
$jsonRpcRequest->params =[$merchantCode, $date, $hash, $hashAlgorithm]; 
$jsonRpcRequest->id = $i++; 
$sessionID = callRPC($jsonRpcRequest, $host);

SHA Algorithm

Generating the hash needed to authenticate using SHA-2 or SHA-3 is similar to using MD5, with the note that in the list of parameters, the hashing algorithm must be specified (the last parameter in the list). 

REST Example

<?php
$merchantCode = "YOURCODE123";
$key = "SECRET_KEY";

$apiVersion = '6.0';
$resource = 'leads';
$host = "https://api.2checkout.com/rest/".$apiVersion."/".$resource."/"; 

$date = gmdate('Y-m-d H:i:s');
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
$hash = hash_hmac($algo , $string, $key); 
$payload = ''; 

$ch = curl_init();

$headerArray = array( 
    "Content-Type: application/json", 
    "Accept: application/json", 
    "X-Avangate-Authentication: code=\"{$merchantCode}\" date=\"{$date}\" hash=\"{$hash}\" algo=\"{$algo}\"" 
);

curl_setopt($ch, CURLOPT_URL, $host); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSLVERSION, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); 
 
$response = curl_exec($ch); 

SOAP Example

<?php
$host  = "https://api.2checkout.com";
$soapClient = new SoapClient($host . "/soap/6.0/?wsdl", array(
    'location' => $host . "/soap/6.0/",
    "stream_context" => stream_context_create(array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false
        )
    ))
));

$merchantCode = "YOURCODE123";
$key = "SECRET_KEY";
$now = gmdate('Y-m-d H:i:s');

$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash   = hash_hmac($algo, $string, $key);

try {
    $sessionID = $soapClient->login($merchantCode, $now, $hash);
}

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

JSON-RPC Example

<?php 
$host = 'https://api.2checkout.com/rpc/6.0/'; 

function callRPC($Request, $host, $Debug = true) { 
    $curl = curl_init($host); 
    curl_setopt($curl, CURLOPT_POST, 1); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($curl, CURLOPT_VERBOSE, true); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($curl, CURLOPT_SSLVERSION, 0); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json')); 
    $RequestString = json_encode($Request); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString); 
    if ($Debug) {
        $RequestString; 
    } 
    $ResponseString = curl_exec($curl); 
    if ($Debug) { 
        $ResponseString; 
    } 
    if (!empty($ResponseString)) { 
        var_dump($ResponseString); 
        $Response = json_decode($ResponseString); 
        if (isset($Response->result)) { 
            return $Response->result; 
        } 
        if (!is_null($Response->error)) { 
            var_dump($Request->method, $Response->error); 
        } 
    } else { 
        return null; 
    }
}

$merchantCode = "YOURCODE123";  
$key = "SECRET_KEY";  
$date = gmdate('Y-m-d H:i:s'); 

$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 
$hash = hash_hmac($algo, $string, $key); 

$i = 1;

$jsonRpcRequest = new stdClass(); 
$jsonRpcRequest->jsonrpc = '2.0'; 
$jsonRpcRequest->method = 'login'; 
$jsonRpcRequest->params = array($merchantCode, $date, $hash, $algo); 
$jsonRpcRequest->id = $i++;


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

Integration test cases

Testing your integration should be straightforward:

  • For SOAP and JSON-RPC, run a request on the login method and check if you are getting a successful result with an alphanumeric session id.
  • For REST, run a GET call or search request against a simple resource like payouts or leads. While the result may be empty if you do not have any activity yet, the HTTP response should be 200 OK, letting you know that the authentication was successful.

Testing your API with Postman

   You can test your API using Postman only with the SHA256 version of the algorithm, as Postman does not support SHA3.

Postman example

Postman 2 example

Retrieve order status information

Overview

Get information about an existing order.

Requirements

Parameters

Parameters Type/Description
sessionID Required (String)
  Session identifier, which is the output of the Login method. An exception is thrown if the values are incorrect.
refNo Required (String)
  The unique, system-generated identifier of a partner order.

Response

Parameters Type/Description
Order Object

Request

<?php

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

$refNo = 'YOUR_ORDER_REFERENCE_NUMBER';

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

Errors

Error Description

INVALID_PARTNER

No partner is set.

INVALID_REFERENCE

The provided order reference is invalid.

 

Remove product from cart

Overview

Use this method to remove a product that was added to the shopping cart, during the current session.

Requirements

Parameters

Parameter Type/Description
sessionID Required (String)
  Session identifier, which is the output of the Login method. An exception is thrown if the values are incorrect.
productId Required (Integer)
  Unique product identifier from the Avangate system.
priceOptions Optional (StringArray)
 

Array of price options codes. These identifiers mark the individual options inside pricing options configuration groups.

This parameter must match exactly the pricing option combination of the product added to the cart in order for the product to be removed.

 

Partner orders can involve the same product, bot ordered in multiple instances, each with different pricing options.

 

Can be NULL.

quantity Optional (Integer)
  Defines the number of product units added to cart that should be removed. If no quantity info is provided, the product is completely removed from cart. Can be NULL.

Response

Parameters Type/Description
Result Boolean
  True or false

Request

<?php

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

$productId = 'PRODUCT_ID_TO_REMOVE';
$quantity = QUANTITY_TO_REMOVE;
$priceOptions = array(
'YOUR_PRICE_OPTIONS',
);

$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'deleteProduct',
'params' => array($sessionID, $productId, $quantity, $priceOptions)
);

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

Errors

Error Description

EMPTY_CART

The shopping cart is empty.

PRODUCT_ERROR

There is no product with the specified settings in cart.

 

Top 5 affiliate program pillars for success

How do you build a successful affiliate program? What do you need to do that? Well, we cannot cover in one webinar the whole process, but you should definitely keep your eyes on some pillars around which you can elaborate.



Julie Avila, VP of Client Services at Schaaf-PartnerCentric, and Cristian Miculi, Senior Manager of Alliances for 2Checkout share more on 5 of the most important pillars of building and optimizing an affiliate program.

You'll find out more about:

  • Getting a technical integration done right
  • What to look at when approving affiliates
  • How to structure your payouts scheme in order to best motivate affiliates
  • What to watch out for when it comes for affiliates fraud
  • How to optimize your affiliate program from a business perspective
Top 5 Affiliate Program Pillars for Success

 

Retrieve account's time zone

Overview

Use the getTimezone method to retrieve information on the time zone used by your account for the 2Checkout API.

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.

Response

Parameters Type/Description

Timezone

String

 

The time zone you selected or the default GMT+02:00 time zone of the 2Checkout system.

Request

<?php

require ('PATH_TO_AUTH');

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

 

Google Tag Manager Code Integration for Default Flows – Google Analytics 4

Overview

The Google Tag Manager (GTM) is a small piece of JavaScript and non-JavaScript code (a container snippet) that you paste into your pages to configure or enable tags from Google Analytics or third parties. For more information on the Google Tag Manager and how to install it, click here.

Setting the Google Tag Manager (GTM)

To implement Google Tag Manager on your website, follow these steps:

  1. Log into your 2Checkout Merchant Control Panel.
  2. Navigate to SetupInterface templates.
  3. Click to Edit the template that needs to be tracked. An example is shown in the image below:
    Googla Analytics for Deafult Flows_Interface templates_1.png
  4. In the Head Information areaMeta & CSS, paste the Google Tag Manager code for your account at the end of the existing code in the section. An example of the Google Tag Manager code is shown below:

    <!-- Google Tag Manager -->
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-XXXXXX');</script>
    <!-- End Google Tag Manager -->

    Example of GTM code for the <body> tag:

    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->

    The GTM code needs to be placed on your own website as well – one snippet of code in the <head> and the other in the <body> tag, if this step has not already been done previously. See the image below for a screenshot of an example code that needs to be added to your own website. More information can be found on this page: https://developers.google.com/tag-manager/quickstart.
    Install GTM

Sending MyOrder Data to Google Analytics 4

By default, the myOrder object is displayed only for orders with payments authorized instantly (this includes usually credit cards and PayPal), after the payment is complete (transaction needs to be authorized successfully). To have the myOrder object available for all placed orders regardless of the payment status (to send revenue to Google Analytics 4 based on myOrder.TotalPrice, to more offline payment methods orders), follow the steps below:

  1. Log in to your Control Panel account.
  2. Go to SetupOrdering Options.
  3. Scroll down to the After sale message area and check the checkbox for the Show message for all placed orders option.
    web analytics in Merchant Control Panel_2.png
  4. Click Save settings at the bottom of the page.

A JavaScript object called myOrder is available on the Thank you page providing information about the purchased products including ID, quantity, name, price, etc.

To see information about orders in Google Analytics 4, follow these steps:

  1. Log in to your Control Panel account.
  2. Navigate to SetupOrdering Options and click on the Analytics tab.
    web analytics in Merchant Control Panel_1.png
  3. Scroll down to the Tracking script section and add a code snippet (for example add <div></div>).
  4. Apply the code to all languages or to the languages for which you want your template to be tracked.
  5. Click Save at the bottom of the page.
    web analytics in Merchant Control Panel_3.png

Google Tag Manager Configuration for Google Analytics 4

Create the Google Tag in Google Tag Manager

If you already have a Google Tag in your container that fires on all pages where the Google Tag Manager code is added, then you do not need to create a new Google Tag specifically for 2Checkout and can proceed directly to the next section.

Follow these steps to create a Google Tag:

Google tag

  1. Select Google Tag from the list of pre-defined tags. In the Tag ID section of the Google Tag Manager, enter the Measurement ID you find in your Google Analytics 4, under AdminData Streams.
  2. Click on your website property and copy the Measurement ID. In the image below you can see where the Measurement ID is located in the Google Analytics 4 interface:
    Google_Analytics_4_tag_2.png
  3. Under Fields to set, add the cookie_flags configuration:
    • Under Field Name add cookie_flags
    • Under Value add SameSite=None;Secure
  4. For Triggering select All Pages.
    All pages

Send eCommerce information to Google Analytics 4 from the 2Checkout shopping cart

2Checkout shopping carts include a dataLayer with eCommerce information for Google Analytics 4. You can view this information by typing dataLayer into the browser console and under gtag4, you can see the eCommerce information for Google Analytics 4, both at checkout and at purchase on the order Finish page.

Google_Analytics_4_tag_4.png

To send eCommerce information to GA4 from the 2Checkout shopping cart, follow these steps:

  1. Log in to Google Tag Manager.
  2. Configure variables in the Google Tag Manager. To capture the eCommerce information from the dataLayer, you will first need to configure certain dataLayer variables in the Google Tag Manager.
  3. Create a new User-Defined variable, called gtag4.event, in the Google Tag Manager.

    • Name your variable gtag4.event to track it easier.
    • For Variable Type, select Data Layer Variable from the options provided by Google.
    • Under Data Layer Variable Name, type gtag4.event.
    • Under Data Layer Version, select Version 2.

    Google_Analytics_4_tag_5.png
    Google_Analytics_4_tag_6.png

  4. Create a new User-Defined variable called gtag4.currency in the Google Tag Manager.

    • Name your variable gtag4.currency to track it easier.
    • For Variable Type select Data Layer Variable from the options provided by Google.
    • Under Data Layer Variable Name type gtag4.currency.
    • Under Data Layer Version select Version 2.

    Google_Analytics_4_tag_7.png

  5. Create a new User-Defined variable called gtag4.items in the Google Tag Manager.

    • Name your variable gtag4.items to keep track of it easier.
    • As Variable Type select Data Layer Variable from the options provided by Google.
    • Under Data Layer Variable Name type gtag4.items.
    • Under Data Layer Version select Version 2.

    gtag4_1.png

  6. Create a new User-Defined variable called gtag4.tax in the Google Tag Manager.

    • Name your variable gtag4.tax to keep track of it easier.
    • For Variable Type select Data Layer Variable from the options provided by Google.
    • Under Data Layer Variable Name type gtag4.tax.
    • Under Data Layer Version select Version 2.

    gtag4_2.png

  7. Create a new User-Defined variable called gtag4.transaction_id in the Google Tag Manager.

    • Name your variable gtag4.transaction_id to keep track of it easier.
    • For Variable Type select Data Layer Variable from the options provided by Google.
    • Under Data Layer Variable Name type gtag4.transaction_id.
    • Under Data Layer Version select Version 2.

    gtag4_3.png

  8. Create a new User-Defined variable called gtag4.value in the Google Tag Manager to capture the total value of the order, including tax.

    • Name your variable gtag4.value to keep track of it easier.
    • For Variable Type select Data Layer Variable from the options provided by Google.
    • Under Data Layer Variable Name type gtag4.value.
    • Under Data Layer Version select Version 2.

    gtag4_4.png

To create a tag in your Google Tag Manager to send eCommerce information to Google Analytics 4, follow these steps:

  1. Create a new tag called Google Analytics GA4 – 2 checkout event.

    • For Tag Type, select Google Analytics: GA4 event from the options provided by Google.
    • Under Measurement ID, add the measurement ID from the Google Analytics 4 property to which you want to send data. This is normally the same measurement ID that you have in your Google Tag. Once you add the measurement ID from your Google Tag, you will see the message Google Tag found in this container.
    • Under Event Name, select the previously configured variable gtag4.event (between double curly brackets {}), as shown in the image below.
    • Under Event Parameters, add the parameters items, currency, transaction_id, value, and tax.
    • Assign a value for each of them by adding the corresponding previously configured variable, as shown in the screenshot below. For example, for the value of the event parameter name items, add the previously configured data layer variable gtag4.items (between double curly brackets {}), as shown in the image below.

    properties

  2. Under Triggering, create a trigger called 2checkout Event for the Google Analytics GA4 – 2 checkout event tag.

    • For Trigger Type select Custom Event from the options provided by Google.
    • As Event name type 2checkout event.
    • Under This trigger fires on, select All Custom Events.

    gtag4_7.png
    gtag4_8.png

  3. Click Save and then Submit to Publish your settings.

Test your integration

To check a purchase in Google Analytics 4, follow the steps below:

  1. Place an order in the 2Checkout shopping cart, using the template that has your Google Tag Manager code.
  2. Log in to your Google Analytics 4 account.
  3. Navigate to MonetizationEcommerce purchases.
    gtag4_9.png
  4. You will be able to see the number of purchases for your products and the revenue from your purchases.
    gtag4_10.png​​​​​​

Update a customer

Overview

Use the updateCustomerInformation method to update 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.

Customer

Object

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;
}
$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;
}
$customerInfo->Email = 'newemailaddressupdated@email.com';
try {
    $updatedCustomerInfo = $client->updateCustomerInformation($sessionID, $customerInfo);
}
catch (SoapFault $e) {
    echo "updatedCustomerInfo: " . $e->getMessage();
    exit;
}
var_dump("updatedCustomerInfo", $updatedCustomerInfo);

 

Refunding an Order

Overview

Reimbursing customers by issuing Total or Partial refunds for their orders is available via API. 

Issuing refunds can be done on the REST protocol via a POST request to /orders/{RefNo}/refund/ and on SOAP and JSON-RPC protocols via the issueRefund method.

Availability

Refunding an order via API is available for all accounts.

Requirements

  • Order must be in status COMPLETE
  • Order must not be older than 3 months
  • The refunded amount must not be higher than the total amount of the order

Request Object

Field name

Type

Required/Optional

Description

RefNo

String

Required (only on SOAP and JSON-RPC)

2Checkout generates unique reference numbers for the refunded order.

Amount

Double

Required

The amount refunded for that order. Can be equal to the order amount (for full order refund) or smaller (for partial refunds).

The currency of the amount is the same as the currency the order was paid in.

Items

Array of RefundItem

Required

The details of the refunded items.

Comment

String

Required

Free text comment for the refund.

Reason

String

Required

The refund reason; must be one of the default refund reasons or a custom reason defined in the 2Checkout Merchant Control Panel.

RefundItem Object

Field name

Type

Required/Optional

Description

LineItemReference

String

Optional

2Checkout product code for the refunded product.

Quantity

Integer

Optional

Quantity of product refunded.

Amount

Double

Optional

Amount refunded.

Request example

REST

{
  "amount": 23,
  "items": [
    {
      "LineItemReference": "my_product_1",
      "Quantity": 1
    }
  ],
  "comment": "requested by shopper",
  "reason": "CUSTOM_REASON"
}

SOAP and JSON-RPC Example

For the SOAP and JSON-RPC protocols, the issueRefund method needs to be called with the components of the requests in the parameter list. 

More information about issuing refunds can be found here (for JSON-RPC) and here (for SOAP).

The JSON-RPC object that needs to be sent would look like

{
   "jsonrpc":"2.0",
   "method":"issueRefund",
   "params":[
      "om7sb5uob2p2g9r321iif2v3hd7p5gkn", //session id
      "11370513",                         //orderRef
      "25.39",                           //amount 
      {
         "Quantity":1,                   //quantity of product refunded
         "Amount":25.39                  //amount of product refunded
      },
      "This is a comment",               //comment
      "Duplicate purchase"               //reason
   ],
   "id":2
}

 For SOAP requests, the following parameters need to be added to the SOAP request:


$refundedOrder = $client->issueRefund($sessionID, $orderReference, $amount, $items, $comment, $reason);

Response

The API will return a Boolean when issuing refunds. A true response means that the refund was registered successfully.

Error handling

A full list of errors returned by the issueRefund API method can be found here.

 

Retrieve the history of a subscription

Overview

Retrieve information on the evolution of a subscription in the Avangate system, including details of the initial acquisition and the subsequent renewals and upgrades. Use the getSubscriptionHistory method to retrieve 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. Avangate 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
SubscriptionHistory Object

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';

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

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

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