Skip to main content

Add a digital dynamic product with a dynamic coupon

Overview

Use the order promotions object to add a digital dynamic product with a dynamic coupon (for the PSP business model).

Use case

  1. Add an HTML link or button to your page like the one below.
  2. Create a JavaScript click handler to execute the InLine Client desired methods.
  3. Use the TwoCoInlineCart.setup.setMode('DYNAMIC') method to let the cart know you are using dynamic instead of catalog products.
  4. Use the TwoCoInlineCart.cart.setCurrency(currency-code) method to set the currency.
  5. Add your product to the cart by calling the TwoCoInlineCart.products.add({name, quantity, price, options}) method.
  6. You can see below a signature token request payload for this example. A success response contains a JSON with the property “signature“ which needs to be used at the next step to set the signature using the TwoCoInlineCart method.
{
    "merchant": "250535979326",
    "dynamic": "1",
    "currency": "USD",
    "products": [
        {
            "name"    : "A test digital product",
            "quantity": 1,
            "price"   : 20,
            "type"    : 'digital'
        },
        {
            "name"    : "A test promotion",
            "quantity": 1,
            "price"   : 5,
            "type"    : 'coupon'
        }
    ]
}

7. Use the TwoCoInlineCart.cart.setSignature('718e810fee34be2bf4b9d4582323aa37580c4011ef694116cca5b0bb7badd2f1') method to set the signature. It is important that you employ TwoCoInlineCart.cart.removeAll() just before TwoCoInlineCart.products.addMany(products) or TwoCoInlineCart.products.add(product) methods to remove previous products as the signature is based on the products' definition.

 8. Use the TwoCoInlineCart.cart.checkout() method to show the cart on your page.

Sample request

HTML

<a href="#" class="btn btn-success" id="buy-button">Buy now!</a>

JavaScript

window.document.getElementById('buy-button').addEventListener('click', function() {
  TwoCoInlineCart.setup.setMode('DYNAMIC');
  TwoCoInlineCart.cart.setCurrency('USD');
  
  TwoCoInlineCart.products.removeAll();
  TwoCoInlineCart.products.add({
      name: 'A test digital product',
      quantity: 1,
      price: 20,
      type: 'digital'
  });
  TwoCoInlineCart.products.add({
      name: 'A test promotion',
      quantity: 1,
      price: 5,
      type: 'coupon'
  });
  
  TwoCoInlineCart.cart.setSignature('5c07abeddff1f1e9521d7c726b7746a09049fcf24e6d1299577b1703d275089c');
  TwoCoInlineCart.cart.checkout();
});

Demo

After adding a digital dynamic product with a dynamic coupon using the above method, your cart should look like this:

 

LCN POST failure recovery process

Overview

In case of an invalid inline response, 2Checkout resends the LCN notification until successfully confirmed. Also, we will display an error notification in the Control Panel Dashboard area.

LCN POST Failure recovery

No of attempts

Stage 1:

The first License Change Notification (LCN) is sent instantaneously for subscription/license modification events per the vendor's LCN Settings.

1

Stage 2:

If the initial notification fails, the subsequent two (2) LCN messages are sent after the next five (5) minutes.

2

Stage 3:

If the issue persists, and requests continue to result in failures, another four (4) tries are made, at 15-minute intervals.

4

Stage 4:

Following the four tries made in Stage 3, the 2Checkout system will perform one-hour interval continuous requests for a maximum of two (2) days since the notification was initially triggered until a valid response is received.

1/h

 

Set the order external reference in the InLine Cart

Overview

Use the Cart object to set order external reference of the InLine Cart by calling theTwoCoInlineCart.cart.setOrderExternalRef(your-external-reference)method.

Use case

  1. Add an HTML link or button in your page like the one below.
  2. Create a JavaScript click handler to execute the Inline Client desired methods.
  3. Use theTwoCoInlineCart.products.add({code, quantity, options})method to prepare your catalog product.
  4. In order to set currency use TwoCoInlineCart.cart.setCurrency(currency-code).
  5. In order to set order external reference useTwoCoInlineCart.cart.setOrderExternalRef(your-external-reference)method.
  6. You can see below a signature token request payload for this example. A success response contains a JSON with the property “signature“ which needs to be used at the next step to set the signature using the TwoCoInlineCart method.
{
    "merchant": "AVLRNG",
    "currency": "USD",
    "products": [
        {
            "code": "74B8E17CC0"
        }
    ],
    "reference": {
        "external": {
            "order": "test-order-external-ref"
        }
    }
}

The above payload will generate the signature f40503a3feeb2c5fc0ca002ded20c59ad0f0b439e3911cfb03538906635d0ae4.

7. Use the TwoCoInlineCart.cart.setSignature('f40503a3feeb2c5fc0ca002ded20c59ad0f0b439e3911cfb03538906635d0ae4') method to set the signature.

8. Use theTwoCoInlineCart.cart.checkout()method to show the cart on your page.

Sample request

HTML

<a href="#" class="btn btn-success" id="buy-button">Buy now!</a>

Javascript

window.document.getElementById('buy-button').addEventListener('click', function() {
  TwoCoInlineCart.cart.setCurrency('USD');
  TwoCoInlineCart.products.add({
    code: "74B8E17CC0"
  });
  TwoCoInlineCart.cart.setSignature('f40503a3feeb2c5fc0ca002ded20c59ad0f0b439e3911cfb03538906635d0ae4');
  TwoCoInlineCart.cart.setOrderExternalRef('test-order-external-ref');
  TwoCoInlineCart.cart.checkout();
});

Demo

After setting the order external reference in the InLine cart using the above method, your cart should look like this:

 

SSO in cart

Overview

Use the getSingleSignOnInCart method.  2Checkout attaches a unique token to links, designed to identify the returning shoppers and support the automatic extraction of payment data and billing information from the 2Checkout system. For example, you can generate single sign on in cart links for existing customers logged into your website based on their external or 2Checkout customer IDs.

How does this work?

When accessing the shopping cart using tokenized payment links:

  • 2Checkout prefills automatically customer billing and delivery details associated with their 2Checkout customer accounts (linked based on their unique customer IDs).
  • 2Checkout presents shoppers with an optimized payment area featuring the credit / debit cards used to make previous purchases / transactions in the 2Checkout system. Customers have the option of selecting one of the payment methods depending on available card-on-file data.

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

Required (string)

 

Unique customer identifiers. Can be either the ExternalCustomerReference you control or the system-generated AvangateCustomerReference.

customerType

Required (string)

 

Possible values:

  • ExternalCustomerReference
  • AvangateCustomerReference

url

Required (string)

 

The shopping cart URL. 2Checkout redirects shoppers to this URL.

 

Possible values:

 

Any buy link you generate from the cPanel or using the API. Note: For the time being, payment tokenization does not support Express Payments Checkout or the 2Checkout mobile shopping cart.

validityTime

Optional (int)

 

The time, in seconds, before the single sign-on URL expires. By default, the URL expires after 10 seconds. (optional)

validationIp

Optional (string)

 

The IP address of the shopper, necessary for security purposes. Can be an empty string or a valid IP, or null.

Response

Parameters Type/Description

Single sign-on URL

String

 

The generated string is the tokenized time-limited single sign-on URL pointing to 2Checkout shopping cart.

 

Note: Each SSO link cleans any previous cart sessions. Shoppers using multiple SSO links would purchase only a single product at a time.

 

If shoppers add multiple products to cart via SSO buy links and then use a non-SSO link, they’ll purchase all items using the same order.

When you use single sign on in cart for customers without card on files in the 2Checkout system, the generated tokenized link prefills the billing information but the purchase process requires that shoppers provide payment information, such as a credit or debit card.

Example: https://store.YourCustomDomain.com/order/checkout.php?PRODS=1112233&logintoken=8b74ac97f8277654563c44da6915b054ba0d21be

 

Important! You can use the value of the logintoken to retrieve customer information by SSO token.

 

Request

<?php

require ('PATH_TO_AUTH');

$idCustomer = '352365983';
$customerType = 'AvangateCustomerReference';
$url = 'https://store.avancart.com/order/checkout.php?PRODS=4639321&QTY=1&CART=1&CARD=2';
$validityTime = 50;
$validationIp = null;

$jsonRpcRequest = array (
'method' => 'getSingleSignOnInCart',
'params' => array($sessionID, $idCustomer, $customerType, $url, $validityTime, $validationIp),
'id' => $i++,
'jsonrpc' => '2.0');

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

Are affiliates cannibalizing online sales?

Did you ever wonder how valuable your affiliates are to your purchase funnel? If that's true, then you're going to want to watch this webinar.

Jessica Griffin, Sr. Sales and Marketing Specialist at Schaaf-PartnerCentric and Cristian Miculi, Sr. Alliances Manager at 2Checkout will lend their considerable experience and expertise to answering the critical question of how to get the most value from your affiliate relationships. 

With their help, you'll come away with a clear understanding of the different types of affiliates in the marketplace, their key motivations and drivers, and how best to work with them.

Plus, they'll also provide you with some hands-on advice and tips for optimizing affiliate program conversion rates.

Join Our Webinar

 

ConvertPlus Buy-Link Signature for Catalog Products

Overview

You can generate links for catalog products outside the Merchant Control Panel, using the ConvertPlus parameters explained in this article. Some of the ConvertPlus buy-link parameters require a signature for the redirect.

 

Recommended resources

Generate custom links

ConvertPlus parameters that require a signature:

Parameter Description
return-url URL to which customers are redirected after their finalized purchase. Learn more about Redirect URL in this article.
return-type

The return method used for redirecting your customers after a successful sale. Possible values:

  • Link in the Thank You page
  • Header Redirect
expiration

Buy link expiry date. The link becomes invalid after the date of this parameter. Send as a UTC timestamp.

Example: 

1537549421 

order-ext-ref Use this parameter to set an external reference to the order.
item-ext-ref Set product identifier for your catalog products. When included, the parameter needs to be signed.
customer-ref The 2Checkout system generates default customer numerical (integer) IDs automatically for all orders of products that feature subscriptions. It can be used for new acquisitions aggregating new subscriptions under an existing Customer account.
customer-ext-ref The external customer reference.

ConvertPlus parameters to be included in the signature

  1. General parameters included in the signature, regardless of the type of checkout (catalog products, dynamic products, renewal, unfinished payment): return-url, return-type, expiration, order-ext-ref,customer-ref, customer-ext-ref, lock.
  2. Parameters to be included in the signature for dynamic products buy-links: currency, prod, price, qty, tangible, type, opt, description, recurrence, duration, renewal-price, item-ext-ref.
  3. Parameters to be included in the signature for manual renewal buy-links: prod, qty, opt.
  4. Parameters to be included for on-the-fly pricing for catalog products: prod, priceqty, opt, coupon, currency.
  5. Parameters to be included when an approved URL is set: in this case, all parameters will be included in the signature, when redirected after successful completion of a sale.

Build the ConvertPlus Signature

To sign a ConvertPlus buy-link, you need to follow these steps:

  1. Sort the parameters that require a signature alphabetically.
  2. Serialize the parameters and append to them the length of their values.
  3. Concatenate the resulting values.
  4. The serialized value is then encrypted with your Buy-Link Secret Word using the HMAC method (algorithm sha256).
  5. The resulting value is added to the buy-link under the signature parameter.

In order to generate a valid ConvertPlus signature, you can include the below parameters as well. The merchant parameter does not require to be signed.

  •     merchant = '2COLRNC' (this is the merchant code)
  •     prod = 'E2932D0DE2'  (this is the product code)
  •     qty = 1

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.

Let's consider the following parameters:

  •     return-url = 'https://www.2checkout.com'
  •     return-type = 'redirect'
  •     expiration = '1665835200'
  •     order-ext-ref = '123456'

The regular buy-link will have the following structure:

https://secure.2checkout.com/checkout/buy?merchant=2COLRNC&prod=E2932D0DE2&qty=1&return-url=https%3A%2F%2Fwww.2checkout.com&return-type=redirect&expiration=1665835200&order-ext-ref=123456

Sort the parameters alphabetically 

  •     expiration = '1665835200'
  •     order-ext-ref = '123456'
  •     return-type = 'redirect'
  •     return-url = 'https://www.2checkout.com'

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 expiration parameter has the '1665835200' value that will be serialized as '101665835200', where 10 is the number of digits that make up the value. The value of the return-type parameter is 'redirect', so the serialized value will be '8redirect', where 8 is the number of letters that make up the value.

  •     expiration = '101665835200'  
  •     order-ext-ref = '6123456'
  •     return-type = '8redirect'
  •     return-url = '25https://www.2checkout.com'

Concatenate the values 

    '10166583520061234568redirect25https://www.2checkout.com'

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 'secret_word')

This outputs a 64 character string:

520ba411696e37f1839145bfa793f7199d8d0295a228ea42dc20a3f39196e358

Add the string in the buy-link 

https://secure.2checkout.com/checkout/buy?merchant=2COLRNC&prod=E2932D0DE2&qty=1&test=1&return-url=https%3A%2F%2Fwww.2checkout.com&return-type=redirect&expiration=1665835200&order-ext-ref=123456&signature=520ba411696e37f1839145bfa793f7199d8d0295a228ea42dc20a3f39196e358

Single Sign-On (SSO)

Overview

Redirect and login shoppers automatically from your user portal into their 2Checkout 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.

 

Orders with installments

Overview

2Checkout supports local Brazilian Visa, MasterCard and AMEX credit/debit cards limited to national purchases in the local currency BRL (Brazilian Real)

Requirements

  1. Installments are available only for:
    • Brazilian customers
    • Local Visa, MasterCard or AMEX cards
    • Non-recurring transactions
  2. The minimum installment threshold is 5 BRL. The maximum number of installments is 6.
  3. Mandatory information for payments also includes shopper's phone number and  Fiscal Code (CPF/CNPJ).

Do local BR cards with/without installments require an addendum to my contract?

Yes. Please contact 2Checkout for activation.

How does it work?

  1. Create the Order object.
  2. Validate the number of installments available based on total order value. 
  3. Place the order specifying the number of installments. 

Funds collection for installment payments

2Checkout pays you in full, regardless of the number of installments (this is covered directly by the banks). 

 

 

Use PayPal Express

Overview

Use the getPayPalExpressCheckoutRedirectURL method to retrieve the RedirectURL by sending an Order object with PAYPAL_EXPRESS payment method.

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.

 

Use PAYPAL_EXPRESS as the payment method.

Response

Parameters Type/Description
PayPalExpressCheckoutRedirectURL String

Retrieve PayPal redirect URL

<?php

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->Language = 'fr';
//$Order->LocalTime = date('Y-m-d G:i:s');
$Order->CustomerReference = 'APITEST'; //uniqid('TESTCUSTOMER:');

$Product = new stdClass();
$Product->Code = 'my_subscription_1';
$Product->Quantity = 1;
$Order->Items[] = $Product;

$Order->Currency = 'EUR';

$Payment = new stdClass();
$Payment->Type = 'PAYPAL_EXPRESS';
$Payment->Currency = 'EUR';
$Payment->CustomerIP = '91.220.121.21';
$Payment->FundingSource = 'Credit'; // set the funding source (optional), can be Standard (default, existing payment method) and Credit (the payment method will be PayPal credit)

$PayPalExpress = new stdClass();
$PayPalExpress->Email = 'customer@email.com';
$PayPalExpress->ReturnURL = 'http://' . $_SERVER['HTTP_HOST'] . '/api/place_order_api_soap_paypal_express_response.php';
$PayPalExpress->CancelURL = 'http://' . $_SERVER['HTTP_HOST'] . '/api/place_order_api_soap_paypal_express_response.php?cancel=true';

$Payment->PaymentMethod = $PayPalExpress;
$Order->PaymentDetails = $Payment;

// Call the method for retrieving Express Checkout redirect URL
$redirectUrl = $client->getPayPalExpressCheckoutRedirectURL($sessionID, $Order);
header('Location:' . $redirectUrl);

Place order with PayPal Express 


<?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 = 'placeOrder';
    public const ADDITIONAL_OPTIONS = null;
    //array or JSON
    public const PAYLOAD = <<<JSON
{
  "Country": "us",
  "Currency": "USD",
  "CustomerIP": "91.220.121.21",
  "ExternalReference": "SOAP_API_AVANGTE",
  "Language": "en",
  "Source": "testAPI.com",
  "BillingDetails": {
    "Address1": "Test Address",
    "City": "LA",
    "State": "California",
    "CountryCode": "US",
    "Email": "testcustomer@2Checkout.com",
    "FirstName": "Customer",
    "LastName": "2Checkout",
    "Zip": "12345"
  },
  "Items": [
    {
      "Code": "A90B3D8FDE",
      "Quantity": 1
    }
  ],
  "PaymentDetails": {
    "Currency": "USD",
    "CustomerIP": "91.220.121.21",
    "FundingSource": "Credit",
    "PaymentMethod": {
      "RecurringEnabled": false,
      "ReturnURL": "http://secure.avangate.local/test/index.php",
      "CancelURL": "http://secure.avangate.local/test/create_order.php"
    },
    "Type": "PAYPAL"
  }
}
JSON;
}

class Client
{
    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, $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);
}

Workflow 

  1. Authentication via login API method.
  2. Retrieve PayPal redirect URL. When you retrieve the PayPal redirect URL, apart from the token you will also receive 2 parameters that are encoded: billingDetails and deliveryDetails. These have to be base64_decoded and the information should be used in the placeOrder API call (email, billing address etc.).
  3. Place the order with PayPal Express using the token sent by PayPal.

 

Retrieve a promotion

Overview

Use the getPromotion method to extract information on a promotion 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. Avangate throws an exception if the values are incorrect. The sessionID expires in 10 minutes.

CouponCode

Required (string)

 

The coupon code of your promotion. This is case sensitive.

Response

Promotion object. 

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);
 
$couponCode = '12345';
 
$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'getPromotion',
'params' => array($sessionID, $couponCode)
);
var_dump (callRPC((Object)$jsonRpcRequest, $host));
 
?>

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