Skip to main content

Assign a subscription to another customer

Overview

Use the setSubscriptionCustomer method. 2Checkout moves subscription under the customer for which you provide the 2Checkout customer reference or the External customer reference during the subscription update process.

json_diagram.png

Requirements

To move a subscription from a source customer to a target customer:

  • Use 2Checkout customer references or External customer references belonging to the target customer. 2Checkout re-assigns the subscription to the target customer. 
  • Customer references must be valid and associated to the target customer entity under which you move the subscription.
  • If you provide both the 2Checkout customer reference and External customer reference they need to belong to the same target customer entity.

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

Boolean

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

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';
$customerReference = CUSTOMER_REFERENCE;

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

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

IPN POST failure recovery process

#

Action

No of attempts

Stage 1

2Checkout sends the first Instant Payment Notification (IPN) instantaneously for events per your account’s Notification Settings.

1

Stage 2

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

2

Stage 3

If the issue persists, and requests continue to result in failures, 2Checkout makes another four (4) retries, 15 minutes apart.

4

Stage 4

Following the four tries made in Stage 3, the 2Checkout system performs one-hour interval continuous requests for a maximum of two (2) days after it sent out the initial notification, until a valid response.

1/h

Retrieve all additional fields

Overview

Use the getAdditionalFields method to extract information about additional fields 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.

Response

Parameters Type/Description

AdditionalFields

Array of objects

Request

<?php

require ('PATH_TO_AUTH');

try {
    $AdditionalFields = $client->getAdditionalFields($sessionID);
}

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

var_dump("AdditionalFields", $AdditionalFields);

Assign to another customer

Overview

Use the setSubscriptionCustomer method. 2Checkout moves subscription under the customer for which you provide the 2Checkout customer reference or the External customer reference during the subscription update process.

json_diagram.png

Requirements

To move a subscription from a source customer to a target customer:

  • Use 2Checkout customer references or External customer references belonging to the target customer. 2Checkout re-assigns the subscription to the target customer. 
  • Customer references must be valid and associated to the target customer entity under which you move the subscription.
  • If you provide both the 2Checkout customer reference and External customer reference they need to belong to the same target customer entity.

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

Boolean

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

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';
$customerReference = CUSTOMER_REFERENCE;

try {
    $newCustomerInfo = $client->setSubscriptionCustomer($sessionID, $subscriptionReference, $customerReference);
}
catch (SoapFault $e) {
    echo "newCustomerInfo: " . $e->getMessage();
    exit;
}
var_dump("newCustomerInfo", $newCustomerInfo);

Retrieve a customer

Overview

Use the getCustomerInformation method to retrieve the details of a customer entity from the Avangate system.

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.

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.

Request

<?php

require ('PATH_TO_AUTH');

$customerReference = CUSTOMER_REFERENCE;
$externalCustomerReference = 'EXT_CUSTOMER_REFERENCE'; //Optional, but if you include it it needs to belong to the same customer as the internal Avangate customer reference

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

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

Response

Parameters Type/Description

Customer

Object

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

Order information

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

 

Signature validation for return URL via ConvertPlus

Overview

To start, you need to have the buy-link with the return-URL and return-type parameters defined and signed. Read here how to create such a link and sign its parameters.

After opening the buy-link in the browser, the shopper will be redirected to the 2Checkout page. During the booting of the cart, the signature is checked against the buy-link query parameters.

In case of an invalid signature, the buy-link parameter is disregarded and the shopper will see the 'Thank You' page instead of a redirect.

In case of a valid signature for the buy-link parameters and successful order placing, the shopper is redirected to the page you have defined in the return parameters. The return-URL is appended with all buy-link parameters and with some extra parameters, 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 parameter's 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 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 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:

  • return-url = 'https://www.yourbackend.com'
  • return-type = 'redirect'
  • merchant = 'YOUR_VENDOR_CODE' (this is the merchant code)
  • prod = 'TEST_PROD'  (this is the product code)
  • qty = 1
  • price = 29
  • tpl = default
  • refno = 11606896
  • total = 29
  • total-currency = USD
  • currency = USD

The regular return link will have the following structure:

https://www.yourbackend.com/?merchant=YOUR_VENDOR_CODE&currency=USD&return-url=https%3A%2F%yourbackend.com%2F&return-type=redirect&tpl=default&prod=TEST_PROD&price=29&qty=1&refno=11606896&total=29&total-currency=USD&signature=95052ee0c558b53040e97d7d81add2e0f1400ca0936a558910c68ddc8301fc63

2. Sort the parameters alphabetically: currency, merchant, price, prod, qty, refno, return-type, return-url, total, total-currency, tpl.

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. 

  • currency - 3USD
  • merchant - 16YOUR_VENDOR_CODE
  • price - 229
  • prod - 9TEST_PROD
  • qty - 11
  • refno - 811606896
  • return-type - 8redirect
  • return-url - 24https://yourbackend.com/
  • total - 229
  • total-currency - 3USD
  • tpl - 7default

4. Concatenate the values:

3USD16YOUR_VENDOR_CODE2299TEST_PROD118116068968redirect24https://yourbackend.com/2293USD7default'

5. Encrypt using your Buy-Link Secret Word that can be found in your Merchant Control Panel, under Integrations → Webhooks & API → Secret word section.

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: 

3598511a17b038b9a0f5579f26bb51a17a8e78ac99a2f6b833714a88a6bbb0c4

 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&currency=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 with a valid signature for the default theme is described in the following diagram.

valid signature diagram.jpg

The successful order with an invalid signature for the default theme is described in the following diagram. 

invalid signature diagram.jpg

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

<?

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';

$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",
    "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.

 

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). 

 

 

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.

 

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