Skip to main content

Customer

Overview

Use the object below to create, update and retrieve customers in 2Checkout.

Input parameters

Parameters Type/Description

ExternalCustomerReference

Optional (string)

 

Unique customer alphanumeric (string) identifiers you control. Aggregate subscriptions under the same Customer account by adding the CUSTOMERID (case sensitive) parameter to Buy links.

FirstName

Required (string)

 

Customer's first name. 

LastName

Required (string)

 

Customer's last name.

Company

Optional (string)

 

Company name.

FiscalCode

Optional (string)

 

Can be null for end users. For companies, it needs to be the VAT ID, which 2Checkout validates.

2Checkout throws an error if the VAT ID is invalid/incorrect. When present, you also need to provide the company name.

 

Can be null for end users.

Address1

Required (string)

 

Customer's address.

Address2

Optional (string)

 

Customer's address.

City

Required (string)

 

Customer's city.

State

Optional (string)

 

Customer's state. For example, "Alabama","Alaska","Arizona".

Zip

Required (string)

 

Zip code.

CountryCode

Required (string)

 

Customer's country code (ISO 3166 two-letter code).

Phone

Optional (string)

 

Customer's phone number.

Fax

Optional (string)

 

Customer's fax number.

Email

Required (string)

 

Customer's email.

Enabled

Optional (boolean)

 

true or false, depending on whether the customer account is active or inactive. An active customer account features at least one Active or Past due subscription. Possible customer statuses:

 

  • Active - Customer account status is Active even if Trial and Cancelled/Expired subscriptions exist for the customer, along as there's at least one Active subscription. Customers with a single subscription featuring the Past due status (expired but in the grace period) are considered Active.
  • Inactive - All subscriptions associated to this Customer account are cancelled, expired or both.
  • Trial - Customer account status is Trial if all Active subscriptions for this customer are trials, regardless of any Cancelled/Expired subscriptions.

Trial

Optional (boolean)

 

true or false, depending on whether the customer account features only trials or also paid subscriptions.

Language

Optional (string)

 

ISO 639-1 two-letter code. Example: “en.”

 

 

Use PayPal

Overview

Place an order using catalog products defined in your Control Panel, and collect the payment using PayPal.

Currency support

Check with 2Checkout support for a list of currencies available for PayPal. 

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

Order

Required (Object)

 

Object designed to collect all data necessary for an order, including billing, product/subscription plan and payment details.

To place an order with PayPal rather than PayPal Express, use PAYPAL as the type of the PaymentDetails object and send the shopper email and a return URL as part of the PaymentMethod object. See code sample. 

Workflow

  1. Create the order object. Use PAYPAL as the type of the PaymentDetails object and send the shopper email and a return URL as part of the PaymentMethod object. Place the order.
  2. Once you place the order, 2Checkout logs it into the system. At this point in time, the status of the order is PENDING. 2Checkout responds with the Order information object.
  3. Redirect shoppers to the RedirectURL from the Order information object you receive as response from 2Checkout.
  4. Once shoppers log into their PayPal account and complete the transaction, they're redirected to the ReturnURL you set in the order object. 2Checkout also authorizes the order and updates the status to AUTHRECEIVED. 
  5. If shoppers log in to their PayPal account and fail to complete the transaction or they cancel it, they're redirected to the CancelURL you set in the order object. 2Checkout updates the status to PENDING.

Response

Parameters Type/Description

Order information

Object

  Object containing order information.

 

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

Place an order

Overview

Use the placeOrder method to place an order.

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.

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

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

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

 

Enable recurring billing

Overview

Use the enableRecurringBilling method to switch on the automatic renewal system for a subscription that's manually renewable. 

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

Boolean

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

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';

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

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

OrderInformation object structure

Member

Type/Description

RefNo

String

 

Order reference number.

OrderNo

String

 

The consecutive order number associated with orders available in the Order search.

ExternalRefNo

String

 

The order reference code (max. 100 chars) provided by the seller. Empty string if missing.

ShopperRefNo

String

 

External shopper identifier.

Status

String

 

The status of the order: AUTHRECEIVED, PENDING, TEST

(COMPLETE, CANCELED, REVERSED, REFUND statuses are only returned for the getOrder method).

ApproveStatus

String

 

The status of the order approval as set either automatically by the Avangate system or manually by a member of our anti-fraud department. This status can vary for new purchases or for orders requiring customers to make manual payments.

Possible values:

  • WAITING: The order has yet to be approved.
  • OK: The order has been approved.
  • INVALIDDATA: The data supplied by the shopper is invalid. The order was not approved.
  • FRAUD: The order is fraudulent.

Language

String

 

Language used in the cart during the purchase process.

OrderDate

String

 

The timestamp (in the API time zone defined in Control Panel) used when the order was placed. Format: Y-m-d H:i:s (2014-05-22 00:12:12).

FinishDate

String

 

The timestamp (in the API time zone defined in Control Panel) when the order reached the Complete status. NULL if the order is not finalized. Format: Y-m-d H:i:s (2014-05-22 00:12:12).

Source

String

 

The link source for the sales. The SRC parameter used to track every sale point generator.

AutoRenewalChecked

Boolean

 

True or false, depending on whether the subscription auto-renewal checkbox was checked during the purchase process.

HasShipping

Boolean

 

True or false, depending on whether the order required shipping.

BillingDetails

Object

 

Details below.

 

Address

String

 

 

Shopper billing address.

 

City

String

 

 

Shopper city from the billing address.

 

Country

String

 

 

Shopper country from the billing address.

 

Email

String

 

 

Shopper billing email address.

 

FirstName

String

 

 

Shopper billing name.

 

LastName

String

 

 

Shopper billing surname.

 

PostalCode

String

 

 

Postal code from the billing address.

 

State

String

 

 

Shopper billing state. E.g.: "Alabama".

 

Company

String

 

 

Company name. Can be NULL for end users. When present, FiscalCode must also be provided.

 

FiscalCode

String

 

 

Can be null for end users. For companies, it needs to be the VAT ID, which is validated by Avangate. An error will be thrown if the VAT ID is invalid/incorrect when calling setPaymentDetails. When present, Company name must also be provided.

DeliveryDetails

Object

 

Details below.

 

Address

String

 

 

Shopper delivery address.

 

City

String

 

 

Shopper delivery city.

 

Country

String

 

 

Shopper delivery country.

 

Email

String

 

 

Shopper email address.

 

FirstName

String

 

 

Shopper delivery first name.

 

LastName

String

 

 

Shopper delivery last name.

 

PostalCode

String

 

 

Shopper delivery postal code.

 

State

String

 

 

Shopper delivery state.

 

Company

String

 

 

Shopper delivery company. Can be NULL for end users.

PaymentInformation

Object

 

Details below.

 

Type

String

 

 

The payment method:

  • CC (credit/debit card)
  • TEST (for test orders)
  • PAYPAL
  • WIRE
  • OTHER (payment methods not listed above)

 

Currency

String

 

 

Payment currency ISO code – ISO 4217.

 

PaymentMethod

Object

 

 

Details below.

 

 

FirstDigits

String

 

 

 

First four credit card digits.

 

 

LastDigits

String

 

 

 

Last four credit card digits.

 

 

CardType

String

 

 

 

Card type:

  • VISA
  • VISAELECTRON
  • MASTERCARD
  • MAESTRO
  • AMEX

Origin

String

 

Order origin channel:

  • Web
  • API
  • Mobile 

Currency

String

 

Order currency.

TotalGeneral

Double

 

Total order value (the costs incurred by the shopper).

TotalWithoutTaxes

Double

 

Total order value without VAT or sales tax.

Taxes

Double

 

VAT or sales tax.

Shipping

Double

 

Shipping costs. NULL if not applicable.

AvangateCommission

Double

 

Avangate order commission.

AffiliateCommission

Double

 

Avangate affiliate commission. NULL if not applicable.

Discount

Double

 

Order discount value. NULL if not applicable.

Products

Array of objects

 

Details below.

 

Id

Int

 

 

Unique, system-generated product ID from the Avangate platform.

 

Code

String

 

 

The code you can attach to products when configuring, editing or importing them in the Avangate platform.

 

Name

String

 

 

Product name.

 

SKU

String

 

 

Product SKU.

 

ExtraInfo

String

 

 

Additional information text entered when generating buy links or via the INFO[productid]= parameter.

 

Quantity

Int

 

 

Purchase number of products.

 

PromotionName

String

 

 

Promotion name.

 

UnitPrice

Double

 

 

Price per product unit.

 

UnitTaxes

Double

 

 

Taxes per product unit.

 

UnitDiscount

Double

 

 

Discount per product unit.

 

UnitAffiliateCommision

Double

 

 

Affiliate commission per product unit.

 

Options

Array of objects

 

 

Array of product pricing options with the structure detailed below.

 

 

OptionText

String

 

 

 

The name of the pricing option selected during the purchase process.

 

 

OptionValue

String

 

 

 

Unique option value code.

 

 

OptionalValue

String

 

 

 

Unique option value code.

 

 

Operator

String

 

 

 

ADD or SUBTRACT, depending on whether the option adds or subtracts a specific amount to or from the product price.

 

 

Usage

String

 

 

 

 

 

 

Price

String

 

 

 

The amount added or subtracted by the pricing options.

 

 

GroupName

String

 

 

 

Product options group name.

 

AdditionalFields

Array of objects

 

 

Array of AdditionalFields information objects with the structure detailed below.

 

 

FieldText

String

 

 

 

Field text visible to shoppers in the cart.

 

 

FieldValue

String

 

 

 

The alpha-numeric characters, underscores and dashes set as the field identifier.

 

Subscriptions

Array of objects

 

 

Array of subscriptions objects with the structure detailed below.

 

 

SubscriptionReference

String

 

 

 

Unique, system-generated subscription identifier.

 

 

PurchaseDate

String

 

 

 

Purchase date.

 

 

ExpirationDate

String

 

 

 

Renewal/expiration date, not considering grace period settings.

 

 

Lifetime

Boolean

 

 

 

Subscription duration.

 

 

Trial

Boolean

 

 

 

TRUE or FALSE depending on whether the subscription is a trial.

 

 

Disabled

Boolean

 

 

 

TRUE or FALSE depending on whether the subscription is disabled.

 

 

RecurringEnabled

Boolean

 

 

 

TRUE or FALSE depending on whether the subscription renewal system is enabled.

AdditionalFields

Array of objects

 

Array of AdditionalFields information objects with the structure detailed below.

 

FieldText

String

 

 

Field text visible to shoppers in the cart.

 

FieldValue

String

 

 

The alpha-numeric characters, underscores and dashes set as the field identifier.

PartnerCode

String

 

Partner code defined in the Control Panel. NULL for eStore orders.

PartnerMargin

Double

 

Partner margin offered for the order. NULL for eStore orders.

PartnerMarginPercent

Double

 

Partner margin percentage from the net value of the products ordered, minus the value of any discounts. NULL for eStore orders.

ExtraMargin

Double

 

Extra margin offered. NULL for eStore orders.

ExtraMarginPercent

Double

 

Extra partner margin percentage from the net value of the products ordered, minus the partner margin and the value of any discounts. NULL for eStore orders.

ExtraDiscount

Double

 

Extra discount offered. NULL for eStore orders.

ExtraDiscountPercent

Double

 

Partner margin percentage from the net value of the products ordered, minus the value of any coupon discounts. NULL for eStore orders.

Retrieve cross-sell campaign texts

Overview

Use the getCrossSellTexts method to extract information on all cross-sell campaigns texts.

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.

LanguageCode

Required (string)

 

ISO language code. (ISO 639-1 two-letter code).

Request

<?php

require ('PATH_TO_AUTH');

$LanguageCode = 'de'; //returns title and description texts you set under https://secure.avangate.com/cpanel/network_cross_selling_settings.php

$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'getCrossSellTexts';
$jsonRpcRequest->params = array(
    $sessionID,
    $LanguageCode
);
$jsonRpcRequest->id = $i++;

var_dump(" \n Cross-sell campaigns: \n", callRPC($jsonRpcRequest, $host));

?>

Response

Parameters Type/Description

Title

String

 

Cross-selling message title. Set here.

Description

String

 

Cross-selling message description. Set here.

Language

String

Retrieve information on 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. Avangate throws an exception if the values are incorrect.  The sessionID expires in 10 minutes.

Types

StringArray

 

Discount type:

  • REGULAR
  • GLOBAL
  • RENEWAL

Channel

String

 

Channel:

  • ECOMMERCE
  • CHANNEL_MANAGER
  • ALL

ProductCode

String

 

Unique code that you set for each of your products.

Limit

Int

 

Number of results returned by the method.

Page

Int

 

Results pagination.

Response

Promotion object.

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;

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

Enable recurring billing

Overview

Use the enableRecurringBilling method to switch on the automatic renewal system for a subscription that's manually renewable. 

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.

subscriptionReference

Required (string)

 

Unique, system-generated subscription identifier.

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

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

INS read receipt response

Overview

Notifications are sent by an HTTP POST request to the message URL that you specified on the INS Notifications tab.

The message parameters are passed as key => value pairs. Your message URLs should route to the script where you will be handling the message. You can listen for messages by simply setting up logic in your application to take action based on the message_type parameter that is passed in each message.

Message types

Currently, there are three types of messages sent using the Instant Notification System (INS).

1. Message Invoice is sent on triggers like order creation or invoice status change.

 {
    "sale_id":"1",
    "sale_date_placed":"1990-01-01 12:00:00",
    "recurring":1,
    "payment_type":"credit card",
    "list_currency":"USD",
    "fraud_status":"pass",
    "order_ref":"1",
    "order_no":"1",
    "vendor_id":"TESTVENDORID",
    "vendor_order_id":"",
    "invoice_id":"100000000000",
    "invoice_status":"approved",
    "invoice_list_amount":"100",
    "invoice_usd_amount":"100",
    "invoice_cust_amount":"100",
    "item_count":1,
    "auth_exp":"2022-01-01",
    "customer_first_name":"John",
    "customer_last_name":"Doe",
    "customer_name":"Jane Doe",
    "customer_email":"john.doe@test.com",
    "customer_phone":"",
    "customer_ip":"1.1.1.1",
    "customer_ip_country":null,
    "cust_currency":"USD",
    "bill_city":"TestCity",
    "bill_country":"NER",
    "bill_postal_code":"",
    "bill_state":"",
    "bill_street_address":"TestStreet",
    "bill_street_address2":"",
    "ship_status":"",
    "ship_tracking_number":"",
    "ship_name":"Doe John",
    "ship_street_address":"TestStreet",
    "ship_street_address2":"",
    "ship_city":"TestCity",
    "ship_state":"",
    "ship_postal_code":"",
    "ship_country":"NER",
    "message_id":1,
    "message_type":"INVOICE_STATUS_CHANGED",
    "message_description":"Invoice status changed",
    "timestamp":"2021-01-01 12:00:00 EEST",
    "key_count":1,
    "item_name_1":"Electronically Delivered Software",
    "item_id_1":"",
    "item_list_amount_1":"100",
    "item_usd_amount_1":"100",
    "item_cust_amount_1":"100",
    "item_type_1":"bill",
    "item_duration_1":"Forever",
    "item_recurrence_1":"1 Month",
    "item_rec_list_amount_1":"100",
    "item_rec_status_1":"live",
    "item_rec_date_next_1":"",
    "item_rec_install_billed_1":"1",
    "hash":"3B2EF87601E548597155C6751FFCCF76"
}

2.   Message Product is sent when a new product is created or an existing product is updated.

{
    "message_id":1,
    "message_type":"CATALOGUE_PRODUCT_CREATED",
    "message_description":"New catalogue product created",
    "timestamp":"2021-01-01 12:00:00 EEST",
    "key_count": 1,
    "avangate_id":"1",
    "enabled":true,
    "fulfillment":"NO_DELIVERY",
    "fulfillment_information":{
        "is_start_after_fulfillment":false,
        "is_electronic_code":false,
        "is_download_link":false,
        "is_backup_media":false,
        "is_download_insurance_service":false,
        "is_instant_delivery_thank_you_page":false,
        "is_display_in_partners_c_panel":false,
        "code_list":null,
        "backup_media":null,
        "product_file":null,
        "additional_information_by_email":null,
        "additional_information_email_translations":{
        },
        "additional_thank_you_page":null,
        "additional_thank_you_page_translations":{
        },
        "return_method":{
            "type":null,
            "url":null
        }
    },
    "generates_subscription":true,
    "gift_option":false,
    "product_group":null,
    "long_description":"",
    "platforms":{
        "0":{
            "id_platform":"1",
            "platform_name":"Linux",
            "category":"Desktop"
        }
    },
    "prices":{
        "name":"TEST's Price Configuration",
        "code":"TESTCODE",
        "default":true,
        "billing_countries":[
        ],
        "use_original_prices":false,
        "pricing_schema":"DYNAMIC",
        "price_type":"NET",
        "default_currency":{
            "id":"1",
            "code":"USD",
            "digitCode":"840",
            "label":"United States Dollar",
            "symbol":"$",
            "symbolPosition":"left",
            "decimalSeparator":".",
            "unitSeparator":",",
            "decimals":"2"
        },
        "prices":{
            "regular":{
                "0":{
                    "amount":100,
                    "currency":"USD",
                    "min_quantity":"1",
                    "max_quantity":"99999",
                    "option_codes":null
                }
            },
            "renewal":{
            }
        },
        "price_options":{
        }
    },
    "product_category":"TESTCATEGORY",
    "product_code":"TESTCODE",
    "product_images":null,
    "product_name":"TESTNAME",
    "product_type":"REGULAR",
    "product_version":"",
    "purchase_multiple_units":true,
    "shipping_class":null,
    "short_description":"",
    "subscription_information":{
        "deprecated_products":[
        ],
        "bundle_renewal_management":"GLOBAL",
        "billing_cycle":-1,
        "billing_cycle_units":"M",
        "is_one_time_fee":true,
        "contract_period":null,
        "usage_billing":7,
        "grace_period":null,
        "renewal_emails":{
            "type":"GLOBAL",
            "settings":{
                "manual_renewal":{
                    "before30_days":false,
                    "before15_days":false,
                    "before7_days":false,
                    "before1_day":false,
                    "on_expiration_date":false,
                    "after5_days":false,
                    "after15_days":false
                },
                "automatic_renewal":{
                    "before30_days":false,
                    "before15_days":false,
                    "before7_days":false,
                    "before1_day":true,
                    "on_expiration_date":true,
                    "after5_days":false,
                    "after15_days":false
                }
            }
        }
    },
    "trial_description":"",
    "trial_url":"",
    "tangible":false,
    "tangible_details":{
        "unit_details":[
        ],
        "fee":[
        ]
    },
    "hash":"435EA2BFAB983240CC27C5FC5D8323B4"
}

3. Message Proposal is sent when a proposal is created or updated. 

{
    "message_id":1,
    "message_type":"PROPOSAL_CREATED",
    "message_description":"Proposal created",
    "timestamp":"2021-01-01 12:00:00 EET",
    "key_count":1,
    "proposal_id":"1",
    "version":"1",
    "created_date":"2021-01-01 12:00:00",
    "updated_date":"2021-01-01 12:00:00",
    "created_by":"TEST",
    "updated_by":"TEST",
    "locked":"",
    "source":"",
    "content":"TEST CONTENT",
    "bill_to":"TEST BILL",
    "name":"TEST NAME",
    "tac":"TEST TAC",
    "type":"TEST TYPE",
    "sent_by":"TEST NAME 2",
    "links":"TEST LINK",
    "status":"PENDING",
    "expiration_date":"2022-01-01 12:00:00",
    "status_comment":"",
    "sell_to":"TEST NAME",
    "hash":"B87C32614A96FCE9C614C0721D19C3B0"
}

Validate response

Each notification message includes a hash computed using the secret word and secret key you set up in your Merchant Control Panel. The hash is returned on each message through the hash key containing the hash algorithm and the hash value, separated by a colon symbol.

Example: "hash":"SHA256:C7CE5C8C4355C3F3162D51530762A31BCFB700030AF3DF072744B5B817F63510"

According to the message, different parameters are required for the hash. The required parameters are concatenated for each type of message and the hash function is applied. The result is converted to uppercase. 

1. For message Invoice, the required parameters are the sale ID, the 2Checkout merchant ID, the invoice ID, and the secret word

PHP Example for Message Invoice

<?php

$invoiceDetails = $_POST;

$secretKey = 'EXAMPLE_SECRET_KEY';
$secretWord = 'EXAMPLE_SECRET_WORD';
$TCOVendorId = 123example_vendor_id;  // your 2checkout vendor id should be a number

$saleId = $invoiceDetails['sale_id'];
$invoiceId = $invoiceDetails['invoice_id'];
$hash = explode(':',$invoiceDetails['hash']); // index 0 is algorithm, index 1 is the hash

$parameters = [
    $saleId,
    $TCOVendorId,
    $invoiceId,
    $secretWord
];



$calculatedHash = strtoupper(hash_hmac($hash[0] ,implode($parameters),$secretKey));
if ($calculatedHash === $hash[1]) {
    http_response_code(200);
    echo true;
} else {
    http_response_code(400);
    echo "calculated hash: $calculatedHash \n";
    echo "received hash: $hash[1]";
}

?>

Node.JS (ES6) Example for Message Invoice

const crypto = require('crypto');
const merchantCode = '123example_vendor_id'; 
const secretWord = 'EXAMPLE_SECRET_WORD';
const secretKey = 'EXAMPLE_SECRET_KEY';

let saleId = request.params['sale_id'];
let invoiceId = request.params['invoice_id'];
let insHashArray = request.params['hash'].split(':');
let insAlgo = insHashArray[0];
let insHash = insHashArray[1];

let parameters = [
    saleId,
    merchantCode,
    invoiceId,
    secretWord
];

const hash = crypto.createHmac(insAlgo, secretKey)
               .update(parameters.join(''))
               .digest('hex');

console.log(hash.toUpperCase() === insHash);

Python Example for Message Invoice

import hmac

merchant_code = 'EXAMPLE_MERCHANT_CODE'
secret_word = 'EXAMPLE_SECRET_WORD'
secret_key = 'EXAMPLE_SECRET_KEY'
sale_id = param['sale_id']
invoice_id = param['invoice_id']
ins_hash_array = param['hash'].split(':')
ins_algo = ins_hash_array[0].replace('-', '_').lower();
ins_hash = ins_hash_array[1];

parameters = [
    sale_id,
    merchant_code,
    invoice_id,
    secret_word
]

hash_string = hmac.new(secret_key.encode('utf-8'), ''.join(parameters).encode('utf-8'), ins_algo).hexdigest().upper()

print(ins_hash == hash_string)

2. For message Product, the required parameters are the product code, the 2Checkout merchant ID, and the secret word

PHP Example for Message Product

<?php

$invoiceDetails = $_POST;

$secretKey = 'EXAMPLE_SECRET_KEY';
$secretWord = 'EXAMPLE_SECRET_WORD';
$TCOVendorId = 123example_vendor_id;  // your 2checkout vendor id should be a number

$productCode = $invoiceDetails['product_code'];
$hash = explode(':',$invoiceDetails['hash']); // index 0 is algorithm, index 1 is the hash

$parameters = [
    $productCode,
    $TCOVendorId,
    $secretWord
];



$calculatedHash = strtoupper(hash_hmac($hash[0] ,implode($parameters),$secretKey));
if ($calculatedHash === $hash[1]) {
    http_response_code(200);
    echo true;
} else {
    http_response_code(400);
    echo "calculated hash: $calculatedHash \n";
    echo "received hash: $hash[1]";
}

?>

Node.JS (ES6) Example for Message Product

const crypto = require('crypto');
const merchantCode = '123example_vendor_id'; 
const secretWord = 'EXAMPLE_SECRET_WORD';
const secretKey = 'EXAMPLE_SECRET_KEY';

let productCode = request.params[‘product_’code];
let insHashArray = request.params['hash'].split(':');
let insAlgo = insHashArray[0];
let insHash = insHashArray[1];

let parameters = [
    productCode,
    merchantCode,
    secretWord
];

const hash = crypto.createHmac(insAlgo, secretKey)
               .update(parameters.join(''))
               .digest('hex');

console.log(hash.toUpperCase() === insHash);

Python Example for Message Product

import hmac

merchant_code = 'EXAMPLE_MERCHANT_CODE'
secret_word = 'EXAMPLE_SECRET_WORD'
secret_key = 'EXAMPLE_SECRET_KEY'
product_code = param[‘product_code’]
ins_hash_array = param['hash'].split(':')
ins_algo = ins_hash_array[0].replace('-', '_').lower();
ins_hash = ins_hash_array[1];

parameters = [
    product_code,
    merchant_code,
    secret_word
]

hash_string = hmac.new(secret_key.encode('utf-8'), ''.join(parameters).encode('utf-8'), ins_algo).hexdigest().upper()

print(ins_hash == hash_string)

3. For message Proposal, the required parameters are the proposal ID, the 2Checkout merchant ID, and the secret word.

PHP Example for Message Proposal

<?php

$invoiceDetails = $_POST;

$secretKey = '=B6gcTl(4t8@D3yUM!TP';
$secretWord = 'Mv#-Z*nb7U%qYJwc-tsb&f?JEyUP5p5WK4*txCfT@336CuwZrZkdqc&K$zEZqnBP';
$TCOVendorId = 250111206876;

$proposalId = $invoiceDetails['proposal_id'];
$hash = explode(':',$invoiceDetails['hash']); // index 0 is algo, index 1 is hash

$parameters = [
    $proposalId,
    $TCOVendorId,
    $secretWord
];



$calculatedHash = strtoupper(hash_hmac($hash[0] ,implode($parameters),$secretKey));
if ($calculatedHash === $hash[1]) {
    http_response_code(200);
    echo true;
} else {
    http_response_code(400);
    echo "calculated hash: $calculatedHash \n";
    echo "received hash: $hash[1]";
}

?>

Node.JS (ES6) Example for Message Proposal

const crypto = require('crypto');
const secretWord = 'AABBCCDDEEFF';
const 2COVendorId = 1;

let proposalId = request.params['proposal_id'];

let parameters = [
    proposalId,
    2COVendorId,
    secretWord
];

let hash = crypto.createHash('md5').update(parameters.join('')).digest();

console.log(hash.toUpperCase() === request.params['md5_hash']);

Python Example for Message Proposal

from urllib import request
from flask import Flask, jsonify, request, Request
from urllib.parse import urlencode, urldefrag
from werkzeug.datastructures import ImmutableOrderedMultiDict
import hashlib

class MyRequest(Request):
    parameter_storage_class = ImmutableOrderedMultiDict

class MyFlask(Flask):
    request_class = MyRequest

app = MyFlask(__name__)
def calculate_hash_string(payload_tuple_list):
    secretWord = 'AABBCCDDEEFF'
    2COVendorId = 1

    proposalId = payload_tuple_list['proposalId']

    parameters = [
        proposalId,
        2COVendorId,
        secretWord
    ]

    hash_string = hashlib.md5(''.join(parameters).encode('utf-8')).digest().upper()

    return hash_string

@app.route('/ins', methods=['POST'])
def ins():
    ins_payload_received = request.form
    return ins_payload_received['md5_hash'] === calculate_hash_string(ins_payload_received)

if __name__ == '__main__':
app.run()

Read receipt response

Currently, there are no required response values, so a basic response with HTTP 200 status will suffice.

3D Secure flow for API orders

Overview

3D Secure is a system designed to increase security of online transactions using cards by checking customer identities before allowing them to finalize purchase. 3D Secure works by redirecting your customers to pages provided by their banks, where they need to enter additional security tokens or password to trigger the completion of the charge.

By using 3D Secure, you get additional protection from liability for fraudulent card payments, with your customers having to go through an extra layer of authentication.

Introducing Dynamic 3D Secure via API

Starting with 2Checkout API 5.0, your orders placed via API are processed automatically through the Dynamic 3D Secure flow. Dynamic 3D Secure is mechanism that allows us to evaluate a transaction in real-time based on a range of rule parameters that are able to determine if 3D Secure should be enabled or not.

Based on specific filters set in our backend system, 3D Secure will be enabled or not on a transaction basis in real-time. The list of filters is includes:

  • Credit card issuing country
  • Billing country 
  • IP country 
  • Order amount

If one of these filters is not matching with the thresholds set in the 2Checkout system, 3D Secure will be enabled. Otherwise the transaction is considered to be safe and can go through without 3D Secure.

Availability

Placing orders via API with the 3D Secure flow is available starting with the version 5 of 2Checkout's API.

Benefits

Place orders via API starting with version 5, and let Dynamic 3D Secure mechanism bring you the following advantages:

  • Increased authorization rates – we measured and observed that in specific countries the use of 3D Secure could have an overwhelmingly positive impact (United Kingdom, Russia) while in other countries it has a negative impact (United States, China).
  • Mitigated fraud risks – 3D Secure significantly decreased the fraud rate for your incoming orders.
  • Less chargeback – the use of 3D Secure can reduce the number of chargebacks in some cases (e.g. reasons like fraud/not recognized) as customers are not allowed to open a chargeback with their bank.

How it works

For credit card orders placed starting with 2Checkout API 5.0, you need to pass through additional parameters that support the Dynamic 3D Secure flow.

Send the following parameters as part of the PaymentMethod object:

Parameters Description
Vendor3DSReturnURL Required (string)
  URL address to which customers are redirected after the 3DS details get validated by the bank and the order is successfully authorized.
Vendor3DSCancelURL Required (string)
  URL address to which customers are redirected if the 3DS details were not validated or the order could not be authorized.

 

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