Skip to main content

Use Alipay

Overview

Alipay is a third-party online payment solution, allowing customers to make and receive payments on the Internet. Alipay's market share of online payments exceeds 54% in China.

Supported currencies

Alipay supports USD and CNY transactions.

Workflow

  1. Shoppers select Alipay as a payment option in the checkout interface you provide to them.
  2. Create the order object. Use “ALIPAY” as the type of the PaymentDetails object.
  3. Use the placeOrder method to send the data to 2Checkout.
  4. Once you place the order, 2Checkout logs it into the system. At this point, the status of the order is PENDING.
  5. 2Checkout returns an Order object as the output of the placeOrder method. 
  6. Use the Redirect Object in the PaymentMethod object of the response to create a redirect URL for your shoppers. Using the provided URL, make a request using the provided method (usually a GET request) and add the parameters (located in the Params object) as key-value pairs to URL of the request. 

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.

See code sample for more details. 

Request Example 

<?php

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->RefNo = NULL;
$Order->Currency = "CNY" ;
$Order->Country = "TW";
$Order->Language = 'EN';
$Order->CustomerIP = '10.5.22.197';
$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 = '67B4EDC822';
$Order->Items[0]->Quantity = 1;
$Order->Items[0]->PriceOptions = NULL;
$Order->Items[0]->SKU = NULL;
$Order->Items[0]->Price = NULL;
$Order->Items[0]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->Items[0]->SubscriptionStartDate = NULL;
$Order->BillingDetails = new stdClass();
$Order->BillingDetails->IsCompany = false;
$Order->BillingDetails->Address1 = 'Xian Jing Blvd 77';
$Order->BillingDetails->Address2 = 'floor 1';
$Order->BillingDetails->City = 'Shanghai';
$Order->BillingDetails->State = '';
$Order->BillingDetails->CountryCode = 'CN';
$Order->BillingDetails->Phone = '010-6552-9988';
$Order->BillingDetails->Email = 'hujianbing@336699.cn';
$Order->BillingDetails->FirstName = 'Hu';
$Order->BillingDetails->LastName = 'Jianbing';
$Order->BillingDetails->Zip = '334321';


$Order->DeliveryDetails = new stdClass();
$Order->DeliveryDetails->Address1 = 'Xian Jing Blvd 77';
$Order->DeliveryDetails->Address2 = 'floor 1';
$Order->DeliveryDetails->City = 'Shanghai';
$Order->DeliveryDetails->State = $state;
$Order->DeliveryDetails->CountryCode = 'CN';
$Order->DeliveryDetails->Phone = '010-6552-9988';
$Order->DeliveryDetails->Email = 'hujianbing@336699.cn';
$Order->DeliveryDetails->FirstName = 'Hu';
$Order->DeliveryDetails->LastName = 'Jianbing';
$Order->DeliveryDetails->Zip = '334321';

$Order->PaymentDetails->Type = 'ALIPAY';
$Order->PaymentDetails->Currency = "CNY" ;
$Order->PaymentDetails->HadPayPalToken = false;
$Order->PaymentDetails->CustomerIP = '10.5.22.197';

$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->PaymentMethod->ReturnURL = 'https://yourreturnurl.com';
$Order->PaymentDetails->PaymentMethod->CancelURL= 'https://yourcancelurl.com ';


try {
    $Order = $client->placeOrder($sessionID, $Order);
}
catch (SoapFault $e) {
    echo "Error: " . $e->getMessage();
    exit;
}

var_dump($Order);

Response Parameters

Parameter Type/Description

Order information

Object

  Object containing order information.

Response Example

{
    "RefNo": "189698901",
    "OrderNo": 0,
    "ExternalReference": null,
    "ShopperRefNo": null,
    "Status": "PENDING",
    "ApproveStatus": "WAITING",
    "VendorApproveStatus": "OK",
    "MerchantCode": "251772850506",
    "Language": "en",
    "OrderDate": "2022-08-23 14:32:21",
    "FinishDate": null,
    "Source": "testAPI.com",
    "WSOrder": null,
    "Affiliate": {
        "AffiliateCode": null,
        "AffiliateSource": null,
        "AffiliateName": null,
        "AffiliateUrl": null
    },
    "HasShipping": true,
    "BillingDetails": {
        "FiscalCode": null,
        "TaxOffice": null,
        "Phone": "010-6552-9988",
        "FirstName": "John",
        "LastName": "Doe",
        "Company": null,
        "Email": "test@verifone.com",
        "Address1": "Test Address",
        "Address2": null,
        "City": "Shanghai",
        "Zip": "35005",
        "CountryCode": "cn",
        "State": null
    },
    "DeliveryDetails": {
        "Phone": "010-6552-9988",
        "FirstName": "John",
        "LastName": "Doe",
        "Company": null,
        "Email": "test@verifone.com",
        "Address1": "Test Address",
        "Address2": null,
        "City": "Shanghai",
        "Zip": "35005",
        "CountryCode": "cn",
        "State": null
    },
    "PaymentDetails": {
        "Type": "ALIPAY",
        "Currency": "cny",
        "PaymentMethod": {
            "Amount": "243",
            "Currency": "cny",
            "Redirect": {
                "Url": "https://intlmapi.alipay.com/gateway.do?_input_charset=utf-8&currency=USD&notify_url=https%3A%2F%2Fsecure.2checkout.com%2Falipay%2Fipn.php&out_trade_no=189698901&partner=2088201540985859&refer_url=1.TEST.MOR.com&return_url=https%3A%2F%2Fsecure.2checkout.com%2Forder%2Fgateway_return.php&rmb_fee=243&service=create_forex_trade&subject=2Checkout%E7%92%81%E3%88%A0%E5%B4%9F+%E9%8D%97%E6%9B%9E%E5%BD%BF%3A+%23189698901&trade_information%5Bbusiness_type%5D=4&trade_information%5Bgoods_info%5D=LPUJL13OZ6%5E1&trade_information%5Btotal_quantity%5D=1&sign=1c6c63019202662f10a96b528f8ee1a4&sign_type=MD5",
                "Method": "GET",
                "Params": {
                    "_input_charset": "utf-8",
                    "currency": "USD",
                    "notify_url": "https://secure.2checkout.com/alipay/ipn.php",
                    "out_trade_no": "189698901",
                    "partner": "2088201540985859",
                    "refer_url": "1.TEST.MOR.com",
                    "return_url": "https://secure.2checkout.com/order/gateway_return.php",
                    "rmb_fee": "243",
                    "service": "create_forex_trade",
                    "subject": "2Checkout璁㈠崟 鍗曞彿: #189698901",
                    "trade_information": {
                        "business_type": "4",
                        "goods_info": "LPUJL13OZ6^1",
                        "total_quantity": "1"
                    },
                    "sign": "1c6c63019202662f10a96b528f8ee1a4",
                    "sign_type": "MD5"
                },
                "FullHtml": "<!DOCTYPE html>\n<html lang=\"EN\"><body><script type=\"text/javascript\">window.location.replace(\"https://intlmapi.alipay.com/gateway.do?_input_charset=utf-8&currency=USD&notify_url=https%3A%2F%2Fsecure.2checkout.com%2Falipay%2Fipn.php&out_trade_no=189698901&partner=2088201540985859&refer_url=1.TEST.MOR.com&return_url=https%3A%2F%2Fsecure.2checkout.com%2Forder%2Fgateway_return.php&rmb_fee=243&service=create_forex_trade&subject=2Checkout%E7%92%81%E3%88%A0%E5%B4%9F+%E9%8D%97%E6%9B%9E%E5%BD%BF%3A+%23189698901&trade_information%5Bbusiness_type%5D=4&trade_information%5Bgoods_info%5D=LPUJL13OZ6%5E1&trade_information%5Btotal_quantity%5D=1&sign=1c6c63019202662f10a96b528f8ee1a4&sign_type=MD5\");</script></body></html>"
            },
            "ReturnURL": https://yourreturnurl.com,
            "CancelURL": https://yourcancelurl.com,
            "RecurringEnabled": false,
            "Vendor3DSReturnURL": null,
            "Vendor3DSCancelURL": null,
            "InstallmentsNumber": null
        },
        "CustomerIP": "91.220.121.21"
    },
    "DeliveryInformation": {
        "ShippingMethod": {
            "Code": null,
            "TrackingUrl": null,
            "TrackingNumber": null,
            "Comment": null
        }
    },
    "CustomerDetails": null,
    "Origin": "API",
    "AvangateCommission": 18,
    "OrderFlow": "REGULAR",
    "GiftDetails": null,
    "PODetails": null,
    "ExtraInformation": null,
    "PartnerCode": null,
    "PartnerMargin": null,
    "PartnerMarginPercent": null,
    "ExtraMargin": null,
    "ExtraMarginPercent": null,
    "ExtraDiscount": null,
    "ExtraDiscountPercent": null,
    "LocalTime": null,
    "TestOrder": false,
    "FxRate": 0.14024803891494,
    "FxMarkup": 4,
    "PayoutCurrency": "USD",
    "DeliveryFinalized": false,
    "Errors": null,
    "Items": [
        {
            "ProductDetails": {
                "Name": "Test Product",
                "ShortDescription": "<p>Join all your clouds in a big one</p>",
                "Tangible": false,
                "IsDynamic": false,
                "ExtraInfo": null,
                "RenewalStatus": false,
                "Subscriptions": null,
                "DeliveryInformation": {
                    "Delivery": "BY_AVANGATE",
                    "DownloadFile": null,
                    "DeliveryDescription": "",
                    "CodesDescription": "",
                    "Codes": []
                }
            },
            "PriceOptions": [],
            "Price": {
                "UnitNetPrice": 243,
                "UnitGrossPrice": 243,
                "UnitVAT": 0,
                "UnitDiscount": 0,
                "UnitNetDiscountedPrice": 243,
                "UnitGrossDiscountedPrice": 243,
                "UnitAffiliateCommission": 0,
                "ItemUnitNetPrice": null,
                "ItemUnitGrossPrice": null,
                "ItemNetPrice": null,
                "ItemGrossPrice": null,
                "VATPercent": 0,
                "HandlingFeeNetPrice": 0,
                "HandlingFeeGrossPrice": 0,
                "Currency": "cny",
                "NetPrice": 243,
                "GrossPrice": 243,
                "NetDiscountedPrice": 243,
                "GrossDiscountedPrice": 243,
                "Discount": 0,
                "VAT": 0,
                "AffiliateCommission": 0
            },
            "LineItemReference": "281d818c9b23daf15405807916e95dac5423d043",
            "PurchaseType": "PRODUCT",
            "Code": "LPUJL13OZ6",
            "ExternalReference": "",
            "Quantity": 1,
            "SKU": null,
            "CrossSell": null,
            "Trial": null,
            "AdditionalFields": null,
            "Promotion": null,
            "RecurringOptions": null,
            "SubscriptionStartDate": null,
            "SubscriptionCustomSettings": null,
            "UpSell": null
        }
    ],
    "Promotions": [],
    "AdditionalFields": null,
    "Currency": "cny",
    "NetPrice": 243,
    "GrossPrice": 243,
    "NetDiscountedPrice": 243,
    "GrossDiscountedPrice": 243,
    "Discount": 0,
    "VAT": 0,
    "AffiliateCommission": 0,
    "CustomParameters": null,
    "Refunds": null
}
Parameter Type/Description

Order information

Object

  Object containing order information.

For more on how to redirect shoppers to the payment method’ page  to finalize the payment, read here.

Retrive a cross-sell campaign

Overview

Use the getProductCrossSellCampaigns method to extract information on all cross-sell campaigns triggered by the same primary product.

Parameters

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.

ProductCode

Required (string)

 

The unique code of the primary product triggering cross-sell campaign that you can define for each of your offerings.

Response

CrossSellCampaign

Object

Request

<?php

$host   = "https://api.avangate.com";
$client = new SoapClient($host . "/soap/4.0/?wsdl", array(
    'location' => $host . "/soap/4.0/",
    "stream_context" => stream_context_create(array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false
        )
    ))
));


function hmac($key, $data)
{
    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
        $key = pack("H*", md5($key));
    }
    
    $key    = str_pad($key, $b, chr(0x00));
    $ipad   = str_pad('', $b, chr(0x36));
    $opad   = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad;
    $k_opad = $key ^ $opad;
    return md5($k_opad . pack("H*", md5($k_ipad . $data)));
}

$merchantCode = "YOURCODE123"; //your account's merchant code available in the 'System settings' area of the cPanel: https://secure.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
$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;
}

$ProductCode = 'product_code_custom1';

try {
    $ProductCrossSellCampaigns = $client->getProductCrossSellCampaigns($sessionID, $ProductCode);
}

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

var_dump("ProductCrossSellCampaigns", $ProductCrossSellCampaigns);


?>

Retrieve cross-sell campaigns

Overview

Use the searchCrossSellCampaigns method to extract information about the cross-sell campaigns you configured.

Parameters

Parameters 

Type 

Required

Description 

CampaignName 

String 

Optional 

The name of the campaign.

Status 

String 

Optional 

The status of the campaign; can be ACTIVE/INACTIVE.

Products 

Array of strings 

Optional 

Array of product codes to apply to this campaign. 

RecommendedProducts 

Array of strings 

Optional 

Array of product codes recommended to the shopper.

StartDate 

String 

Optional 

The date when the cross-sell campaign starts, formatted as YYYY-MM-DD 

EndDate 

String 

Optional 

The date when the cross-sell campaign ends, formatted as YYYY-MM-DD 

Type String Optional Can be MERCH/AFF.

Pagination 

Object 

Optional 

  

Page 

Int 

Optional 

The page number of the results.

Limit 

Int 

Optional 

The number of results per page.

Response

Parameters Type/Description
Items An array of CrossSellCampaign Objects
Pagination Pagination Object with the following parameters: Page, Limit, Count

Request

<?php
declare(strict_types=1);

// Start clear CLI
echo chr(27).chr(91).'H'.chr(27).chr(91).'J';
// End clear CLI

$executionStartTime = microtime(true);

$apiVersion = '6.0';
$apiHost = "http://api.avangate.local";

$host = $apiHost."/soap/" . $apiVersion . "/";

$client = new SoapClient(
    $host."?wsdl",
    [
    'location' => $host,
    'trace' => 1,
    'cache_wsdl' => WSDL_CACHE_NONE
    ]
);
$client->__setCookie('XDEBUG_SESSION', 'PHPSTORM');

// Please be aware to consider valid data
$merchantCode = 'your_merchant_code';
$key = 'your_merchant_key';

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

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

var_dump("Generated sessionID: ". $sessionID);
echo "\n\r";

// Build search parameters
$searchOptions = new \stdClass();

$searchOptions->Status = ['ACTIVE'];     // Optional | Ex: ['ACTIVE']
$searchOptions->Type = null;             // Optional | Ex: 'MERCH'
$searchOptions->CampaignName = null;     // Optional | Ex: 'UpdatedCampaign_4'
$searchOptions->Products = [];           // Optional | Ex: ["a01", "a02"]
$searchOptions->RecommendedProducts = [];// Optional | Ex: ["a03"]
$searchOptions->StartDate = null;        // Optional | Ex: 'YYYY-MM-DD'
$searchOptions->EndDate = null;          // Optional | Ex: 'YYYY-MM-DD'
$searchOptions->Pagination = null;       // Optional | Ex: {"Page": "1", "Limit": "10"}

try {
    $result = $client->searchCrossSellCampaigns($sessionID, $searchOptions);
    echo "\n\rSEARCH CROSS SELL CAMPAIGNS: \n\r";
    print_r(json_encode($result, JSON_PRETTY_PRINT));

} catch (SoapFault $e) {
    echo $e->getMessage();
}

$executionEndTime = microtime(true);

// The duration will be displayed in seconds and milliseconds.
$seconds = round($executionEndTime - $executionStartTime, 2);

// Print it out
echo "\n\rThis script took $seconds to execute.\n\r";

Mandatory product info

Overview  

To configure your products, make sure you have the mandatory information on hand, including name, recurring billing plan, pricing.

Mandatory product details 

Product details Description

Name

Use unique names to identify your products. Localize product names to increase conversion in different markets.

Product code

Map product identifiers in your system with products in 2Checkout. If you do not supply a product code, 2Checkout generates a random string instead.

Product type

Regular - standalone product.

Bundle - the item is part of a bundle you sell as a standalone product. You need to create at least 2 products before setting up your first bundle.

Default currency

2Checkout defaults to this currency during the purchase process. Note that localized payment methods generally only support a limited number of currencies.

Price type

  • Dynamic pricing (with a base price - you do not check 'This product does not have a base price') - Dynamic pricing (with base price) is a basic charge configuration. 2Checkout supports both one-time and recurring dynamic pricing and offers the possibility to control various cost components through product options pricing. 

  • Static pricing (without base price) This product does not have a base price' - Static pricing (without base price) configurations enable you to control product costs for each possible combination of options available to shoppers in the cart.

Price

Product price per billing cycle. Available only when you don't check the 'This product does not have a base price' option. 

Billing cycle

The interval of time (in days or months) at the end of which either 2Checkout renews the subscription automatically through a recurring charge or the subscriber purchases a renewal manually.  

Currency conversion

  •  Let 2Checkout auto-convert to other currencies during the ordering process.
  • Or set the price manually per currency.

Net vs. Gross

  • 2Checkout adds VAT or sales tax on top of the product prices during the ordering process. 
  • 2Checkout deducts VAT or sales tax from the total costs of orders. 
Product Tax Category Product attribute that allows merchants to assign newly created products to specific product tax categories.

Optional product details

Product details Description

Version

Your product's version number.

Product group

Assign a specific cart design to a product group and all the products it includes will use the template during the purchase process.

Quantity

You can limit the number of units sold to only one, preventing shoppers from purchasing more.

Short description

Visible to customers on the Product page, during Up-selling campaigns and to affiliates in their Control Panel.

Long description

Visible to customers on the Product page(web version), during Up-selling campaigns and to affiliates in their affiliate XML feed.

System requirements Display info for shoppers about system requirements.

Category

Visible to your affiliates in the Affiliate Panel, allowing them to search for products belonging to specific categories.
Platforms Display info for shoppers about supported platforms.

Trial URL

Configure the URL from where shoppers can download free trials of your products by providing their email address.

Update special price promotion

Overview 

Use the UpdateSpecialPricePromotion method to modify promotion at a special price.

Request parameters 

Parameters Type Required Description
promotionCode String Required Code of the promotion that you want to update.
sessionID String Required Unique identifier of the session.
existingPromotion String Required Details of the existing promotion.
PriceMatrix Array of Objects Required Only for this type of promotion. It is generated by getPriceMatrix and used to set promotion special prices.

Request sample

<?php
require ('PATH_TO_AUTH');

// Retrieve promotion details

$promotionCode = 'PROMOTION_CODE'; // code of the promotion that you want to update

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

// Keep the promotion you want to update in $existingPromotion
$existingPromotion = callRPC((Object)$jsonRpcRequest, $host);
// Set the fields to update


$priceMatrixDefinition1 = new stdClass;
$priceMatrixDefinition1->ProductCode = "test";
$priceMatrixDefinition1->PricingConfigurationCode = "738C6A2049";
$priceMatrixDefinition1->OptionHash = "708e43960c4edc42f14cf388bcb24bde";

$option1 = new stdClass;
$option1->GroupName = "Units";
$option1->OptionText = "1 - maximum";

$price1 = new stdClass;
$price1->Value = 20;
$price1->Currency = "USD";
$price2 = new stdClass;
$price2->Value = 15;
$price2->Currency = "EUR";

$priceMatrixDefinition1->Options = [$option1];
$priceMatrixDefinition1->Prices = [$price1, $price2];

$existingPromotion->DefaultCurrency = 'USD';
$existingPromotion->PriceMatrix = [
    $priceMatrixDefinition1
];

// Update the promotion
$jsonRpcRequest = array (
'jsonrpc' => '2.0',
'id' => $i++,
'method' => 'updatePromotion',
'params' => array($sessionID, $existingPromotion)
);
var_dump (callRPC((Object)$jsonRpcRequest, $host));

Response

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "Code": "M99QQ7Q97A",
    "Name": "Promo percentage REST",
    "Description": "Promo description1",
    "StartDate": "2019-11-30",
    "EndDate": "2100-12-31",
    "MaximumOrdersNumber": -1,
    "MaximumQuantity": "1",
    "InstantDiscount": false,
    "Coupon": {
      "Type": "MULTIPLE",
      "Codes": [
        "code1",
        "code2"
      ]
    },
    "Enabled": true,
    "Type": "SPECIAL_PRICE",
    "Products": [
      {
        "Code": "test",
        "PricingOptionCodes": null,
        "PricingConfigurationCode": null
      }
    ],
    "Translations": [
      {
        "Name": "Promo percentage REST",
        "Language": "EN"
      }
    ],
    "Sources": [],
    "ApplyRecurring": "NONE",
    "RecurringChargesNumber": "0",
    "DefaultCurrency": "EUR",
    "PriceMatrix": [
      {
        "ProductCode": "test",
        "PricingConfigurationCode": "738C6A2049",
        "OptionHash": "708e43960c4edc42f14cf388bcb24bde",
        "Options": [
          {
            "GroupName": "Units",
            "OptionText": "1 - maximum"
          }
        ],
        "Prices": [
          {
            "Value": 31.15600000000014,
            "Currency": "CAD"
          },
          {
            "Value": 20,
            "Currency": "EUR"
          },
          {
            "Value": 40,
            "Currency": "USD"
          },
          {
            "Value": 1587.5251590697817,
            "Currency": "ARS"
          },
          {
            "Value": 18541.128586270122,
            "Currency": "CLP"
          },
          {
            "Value": 18.132399999999887,
            "Currency": "GBP"
          },
          {
            "Value": 2447.1999999999794,
            "Currency": "JPY"
          },
          {
            "Value": 499.51800000000384,
            "Currency": "MXN"
          },
          {
            "Value": 97.536,
            "Currency": "RON"
          },
          {
            "Value": 1846.0500000000052,
            "Currency": "RUB"
          },
          {
            "Value": 601.8285443739301,
            "Currency": "UAH"
          },
          {
            "Value": 384.3740000000019,
            "Currency": "ZAR"
          }
        ]
      }
    ]
  }
} 

Copy payment info

Overview

Copy card-on-file data available in the Avangate system from a source subscription to an imported target subscription. Avangate uses the existing payment information to charge customers as a part of the recurring billing (renewal) process.

Use the copyPaymentInfo method.

Requirements

The imported target subscription and the source subscription must belong to the same customer. The Avangate system checks to make sure that the Avangate Customer Reference (internal identifier) coincides for the customer accounts associated to the target and source subscriptions.

Availability

Please contact Avangate directly if you wish to take advantage of this feature.

How does this method work?

  1. Customer A purchases Subscription A using a VISA credit card and you import Subscription B for the same customer with no data or with an AMEX card.
  2. When Avangate renews Subscription A, it charges Customer A using the VISA, while using the AMEX (if the data was provided) for Subscription B charges.
  3. When you copy the payment data from Subscription A to Subscription B, the Avangate system uses the VISA credit card to renew both subscriptions according with their respective recurring billing cycles. Avangate charges customers during the recurring billing process for the imported target subscription using the payment method they used to purchase the source 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.

TargetSubscriptionReference

Required (string)

 

The Avangate Subscription Reference of the imported target subscription, to which Avangate copies the payment on file data associated with the source subscription.

SubscriptionReference

Required (string)

 

The Avangate Subscription Reference of the source subscription whose attached payment on file data Avangate copies to the target subscription.

Response

Boolean

true or false depending on whether or not the operation succeeded.

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)) {
        $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 = "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; // counter for api calls
// call login
$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);
 
var_dump($sessionID);
$TargetSubscription = 'FFAE3C9429';
$SourceSubscription = '9F4154733C';

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

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

 

Set billing details for the InLine Checkout

Overview

Pre-set the billing details for the InLine checkout.

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. Call any of the following methods to pre-set the billing details:
TwoCoInlineCart.billing.setName('John Snow');
  TwoCoInlineCart.billing.setEmail('john.snow@2checkout.com');
  TwoCoInlineCart.billing.setPhone('+33 892 70 12 39');
  TwoCoInlineCart.billing.setCountry('FR');
  TwoCoInlineCart.billing.setCity('Paris');
  TwoCoInlineCart.billing.setState('');
  TwoCoInlineCart.billing.setZip('75007');
  TwoCoInlineCart.billing.setAddress('Champ de Mars');
  TwoCoInlineCart.billing.setAddress2('5 Avenue Anatole');

5. If you want to reset the billing details, call theTwoCoInlineCart.billing.reset()method.

6. Use theTwoCoInlineCart.cart.checkout()method to display 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.products.add({
    code: "74B8E17CC0"
  });
  
  // Style 1 (all data at once)
  TwoCoInlineCart.billing.setData({
    name: 'John Snow', 
    email: 'john.snow@2checkout.com', 
    phone: '+33 892 70 12 39', 
    country: 'FR', 
    city: 'Paris', 
    state: '', 
    zip: '75007', 
    address: 'Champ de Mars', 
    address2: '5 Avenue Anatole'
  });
  
  // Reset
  TwoCoInlineCart.billing.reset();
  
  // Style 2 (simple)
  TwoCoInlineCart.billing.setName('John Snow');
  TwoCoInlineCart.billing.setEmail('john.snow@2checkout.com');
  TwoCoInlineCart.billing.setPhone('+33 892 70 12 39');
  TwoCoInlineCart.billing.setCountry('FR');
  TwoCoInlineCart.billing.setCity('Paris');
  TwoCoInlineCart.billing.setState('');
  TwoCoInlineCart.billing.setZip('75007');
  TwoCoInlineCart.billing.setAddress('Champ de Mars');
  TwoCoInlineCart.billing.setAddress2('5 Avenue Anatole');
  
  // Reset
  TwoCoInlineCart.billing.reset();
  
  // Style 3 (chained)
  TwoCoInlineCart.billing
    .setName('John Snow')
    .setEmail('john.snow@2checkout.com')
    .setPhone('+33 892 70 12 39')
    .setCountry('FR')
    .setCity('Paris')
    .setState('')
    .setZip('75007')
    .setAddress('Champ de Mars')
    .setAddress2('5 Avenue Anatole')
  ;
  
  TwoCoInlineCart.cart.checkout();
});

Demo

After setting the billing details for the InLine cart using the above methods, your cart should look like this:

 

Subscription end user update

Overview

Use the updateSubscriptionEndUser method to update the details of a subscription’s end user. This method changes per-subscription end user data and not customer details.

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.

EndUser

Required (Object)

  Use this object to update end user information.

Response

Parameter Type/Description

Boolean

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

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)) {
        $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/4.0/';
 
$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; // counter for api calls
// call login
$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);
 
var_dump($sessionID);
$subscriptionReference = '8F749B63E7';
$EndUser = new stdClass ();
$EndUser->Address1 = 'Address line 1';
$EndUser->Address2 = 'Address line 2';
$EndUser->City = 'LA';
$EndUser->Company = 'Company Name';
$EndUser->CountryCode = "US";
$EndUser->Email = 'customerAPI@avangate.com';
$EndUser->FirstName = 'New Customer 2.0';
$EndUser->Language = 'en';
$EndUser->LastName = 'Avangate';
$EndUser->Phone = '1234567890';
$EndUser->State = 'California';
$EndUser->Zip = '90210';
$EndUser->Fax = null;

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

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

 

Shipping in API

Overview

Use the API methods displayed below to create orders for physical products.

Search the shipping methods defined in your Control Panel, and extract information on how the shipping price is calculated.

 

Subscription additional information fields

Overview

Use this object to create, update and retrieve additional information fields from your subscriptions.

Attributes

Parameters Type/Description

fieldName

String

 

The name of the additional information field. Used for identifying additional information fields.

fieldValue

String

 

The value of the additional information field.

 

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