Skip to main content

Create proposal

Overview

Use the createProposal method via JSON-RPC API 6.0 to add/create a new quote.

Request Parameters

Parameters Type Required/Optional Description
proposal Object Required  
proposalContent Object Required  
lineItems Object Required  
sessionId String Required Unique 2Checkout session ID code.

Request Sample

<?php

require ('PATH_TO_AUTH');

$proposal = new stdClass();
$proposal->Type = "acquisition";
$proposal->BillTo = new stdClass();
$proposal->BillTo->Company = "Billing company";
$proposal->Content = new stdClass();
$proposal->Content->Language = "EN";
$proposal->Content->Currency = "USD";
$proposal->Content->LineItems =  array();
$lineItem = new stdClass();
$lineItem->ProductName = "My Product Name";
$lineItem->ProductCode = "5DCB30C6B0";
$lineItem->Quantity = 1;
$lineItem->Price = 54.2;
$lineItem->DiscountedPrice = 50;
$lineItem->PriceType = "net";
$lineItem->ContractPeriod = 0;
$proposal->Content->LineItems[0] = $lineItem;
$proposal->tac = new stdClass();
$proposal->tac->content = "Lorem ipsum.";
$proposal->SellTo = new stdClass();
$proposal->SellTo->Company = "End user company";

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

try {
    $result = callRPC($jsonRpcRequest, $host);
    echo "Proposal: </br>", 
    var_dump($result);
}
catch (SoapFault $e) {
    echo "Could not fetch proposal: " . $e->getMessage();
    exit;
}

Request sample with prorationDate

<?php


        require('PATH_TO_AUTH');

        $proposal = new stdClass();
        $proposal->Type = "amendment";
        $proposal->BillTo = new stdClass();
        $proposal->BillTo->Company = "Billing company";
        $proposal->Content = new stdClass();
        $proposal->Content->Language = "EN";
        $proposal->Content->Currency = "USD";
        $proposal->Content->Terms = 30;
        $proposal->Content->LineItems = array();
        $lineItem = new stdClass();
        $lineItem->ProductName = "My Product Name";
        $lineItem->ProductCode = "5DCB30C6B0";
        $lineItem->Quantity = 1;
        $lineItem->Price = 54.2;
        $lineItem->DiscountedPrice = 50;
        $lineItem->PriceType = "net";
        $lineItem->ContractPeriod = 0;
        $lineItem->ProrationDate = "2020-11-14T15:28:56+00:00";
        $lineItem->subscriptionReference ="1234567890";
        $proposal->Content->LineItems[0] = $lineItem;
        $proposal->tac = new stdClass();
        $proposal->tac->content = "Lorem ipsum.";
        $proposal->SellTo = new stdClass();
        $proposal->SellTo->Company = "End user company";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
            echo "Proposal: </br>",
            var_dump($result);
        } catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

Request sample with vatCode

<?php

        require ('PATH_TO_AUTH');

        $proposal = new stdClass();
        $proposal->Type = "acquisition";
        $proposal->BillTo = new stdClass();
        $proposal->BillTo->Company = "Billing company";
        $proposal->Content = new stdClass();
        $proposal->Content->Language = "EN";
        $proposal->Content->Currency = "USD";
        $proposal->Content->LineItems =  array();
        $lineItem = new stdClass();
        $lineItem->ProductName = "My Product Name";
        $lineItem->ProductCode = "5DCB30C6B0";
        $lineItem->Quantity = 1;
        $lineItem->Price = 54.2;
        $lineItem->DiscountedPrice = 50;
        $lineItem->PriceType = "net";
        $lineItem->ContractPeriod = 0;
        $proposal->Content->LineItems[0] = $lineItem;
        $proposal->tac = new stdClass();
        $proposal->tac->content = "Lorem ipsum.";
        $proposal->SellTo = new stdClass();
        $proposal->SellTo->Company = "End user company";
        $proposal->SellTo->VatCode = "854234564";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
            echo "Proposal: </br>", 
            var_dump($result);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

Request sample with TaxExemptionId

<?php

        require ('PATH_TO_AUTH');

        $proposal = new stdClass();
        $proposal->Type = "acquisition";
        $proposal->BillTo = new stdClass();
        $proposal->BillTo->Company = "Billing company";
        $proposal->Content = new stdClass();
        $proposal->Content->Language = "EN";
        $proposal->Content->Currency = "USD";
        $proposal->Content->LineItems =  array();
        $lineItem = new stdClass();
        $lineItem->ProductName = "My Product Name";
        $lineItem->ProductCode = "5DCB30C6B0";
        $lineItem->Quantity = 1;
        $lineItem->Price = 54.2;
        $lineItem->DiscountedPrice = 50;
        $lineItem->PriceType = "net";
        $lineItem->ContractPeriod = 0;
        $proposal->Content->LineItems[0] = $lineItem;
        $proposal->tac = new stdClass();
        $proposal->tac->content = "Lorem ipsum.";
        $proposal->SellTo = new stdClass();
        $proposal->SellTo->Company = "End user company";
        $proposal->SellTo->TaxExemptionId = "854234564";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
            echo "Proposal: </br>", 
            var_dump($result);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

Response

The createProposal API call returns Proposal object.

Cross-sell

Overview

Use this object to retrieve information about the cross-sell campaigns you configured for your account. 

Parameters

CrossSellCampaign

Object

MasterProducts

Array

 

Array of product codes for the items you set to trigger the cross-sell campaign.

DisplayType

String

 

  • cart – Shopping cart
  • review – Review page
  • finish – Thank you page

DisplayInEmail

Boolean

 

True or false depending on whether you set the cross-sell campaign to display in payment receipt emails or not.

Products

Array of objects

 

Details below

 

ProductCode

String

 

 

Product code for the item you set as recommended for the cross-sell campaign.

 

Discount

String

 

 

Value of the discount. This is a percentage.

 

DiscountType

String

 

 

PERCENT – you can only set discounts as a percentage from the product price.

CampaignCode

String

 

Unique, system-generated cross-sell campaign code.

Name

String

 

Campaign name.

StartDate

String

 

YYYY-MM-DD. The start date you set for the cross-sell campaign.

EndDate

String

 

YYYY-MM-DD. The end date you set for the cross-sell campaign.

 

InLine Checkout methods and parameters

Overview

Minimize your customers' effort by collecting their order/billing information and passing it to InLine Checkout. Simplify the checkout experience and enable your customers to place orders only by confirming their payment information.

 

Related links

Advanced InLine Checkout experience

InLine Checkout offers you advanced control over the ordering process, for minimizing the customer's effort during the purchase. You can send the billing and delivery information directly to the cart if they are collected on your website by a shopping cart application. InLine Checkout enables you to:

  • Place test orders
  • Set coupons codes in cart
  • Set the cart language
  • Set the cart currency
  • Set a redirect URL after a finalized purchase

We recently improved the perceived loading time for the InLine checkout ordering engine by pre-loading the cart iframe. Faster loading time for the InLine cart means an enhanced shopping experience and helps you to increase conversion rates with no other effort on your side. See more details below in the Cart methods table.

Send information to InLine Checkout

After you integrate the InLine Checkout JavaScript code in your website application, you get access to the library that allows you to add products, control billing and shipping details, and start the checkout process. Follow the instructions below to control the information displayed by InLine Checkout.

Handling products

Products are handled by the products' service. This service allows you to retrieve the list of added products, add products to cart, remove individual products, or remove all the products from the cart.

Use the methods and product attributes listed below to add/remove products from the cart.

Product attributes

Attributes Type/Description
code

String

Product code assigned by you when creating the product. Required for catalog products.

type

String

Product type. Required only for dynamic products. Possible values:

[PRODUCT, SHIPPING, TAX]. Default value is PRODUCT.

name

String

Product name. Required for dynamic products.

price

String - for dynamic products

Product price. It is required for dynamic products.

 

Object - for catalog products with on-the-fly pricing

Product price. It is required for catalog products with on-the-fly pricing and includes value and currency.

tangible

String

Product tangible flag. Required only for dynamic products. Default value is FALSE.

quantity

String

Product quantity. Default value is 1. Required for catalog products with on-the-fly pricing.

options

Array

The product price options. It is supported for both catalog and dynamic products. Required for catalog products with on-the-fly pricing.

 

Product price options structure for dynamic products:

  • Name (String)- The price option name
  • Value (String, Number, Array of strings or numbers) - The price option value
  • Surcharge (string) - The price option surcharge - applicable only for dynamic products

Product price options structure for catalog products:

  • Name (String) – The unique code of the pricing OPTION GROUP
  • Value (String) – The unique code of the pricing OPTION
recurrence

Object

Required for dynamic products.

Possible values:

  • DAY
  • WEEK
  • MONTH
  • YEAR
  • FOREVER (available only for duration)

This parameter is conditioned by two other parameters: duration and renewalPrice.

duration

Object

Sets the duration of the recurrence. Required for dynamic products.

renewalPrice

Integer

Sets the price to be applied to the renewal order. Required for dynamic products.

Product methods

Methods Description
add Adds a single product to the list. Use the above list of parameters to add a product to cart.
remove Removes a product from the list.
addMany

Adds an array of product objects to the main list.

removeAll

Removes all products from the list.

getAll

Retrieves the products list.

HANDLING billing details

Billing details are handled by the billing service. Each billing information is controlled by a setter method.

Use the attributes and methods listed below to control the billing information displayed in the cart. Customers are able to fill in their billing information in the overlay provided by InLine Checkout. In case your shopping cart application collects customer's billing information, use the attributes and methods listed below to pass that information over to the cart.

Billing details attributes

Attributes Type/Description
name

String

Customer billing name. Example: "John Doe". 

email

String

Customer billing email. Example: "john.doe@email.com".

phone

String

Customer billing phone number. Example: "403940281923".

country

String

Customer billing country. Example: "US".

city

String

Customer billing city. Example: "Los Angeles".

state

String

Customer billing state. Example: "California".

zip

String

Customer billing zip code. Example: "90078".

address

String

Customer billing address. Example: "1093 Rodeo Drive".

address2

String

Customer billing additional address information. "293 Postal Box".

company-name

String

CompanyName

When sending the Company name the Company checkout flow will be triggered. Otherwise, the default checkout flow for InLine cart is the individual flow.

fiscal-code

String

fiscalCode

When sending the Fiscal code, the Company checkout flow will be triggered only if also another company flow relevant parameter will be also sent (Company name and/or Tax office). Otherwise, the default checkout flow for InLine cart is the individual flow.

tax-office

String

taxOffice

When sending the Tax office the Company checkout flow will be triggered. Otherwise, the default checkout flow for InLine cart is the individual flow.

Billing details methods

Methods Description
setData

Sets the entire billing data.

setName Sets the billing name.
setEmail Sets the billing email.
setPhone

Sets the billing phone.

setCountry Sets the billing country.
setCity Sets the billing city.
setState Sets the billing state.
setZip

Sets the billing zip code.

setAddress Sets the billing address.
setAddress2 Sets additional billing address information.
reset Resets the billing data.

setCompanyName

Sets the billing Company name

setFiscalCode

Sets the billing Fiscal code

setTaxCode

Sets the billing Tax code

Handle shipping details 

Shipping details are handled by the shipping service. Each shipping information is controlled by a setter method.

Use the attributes and methods listed below to control the shipping information displayed in the cart. In case you use a shopping cart application that collects the shipping information, use the attributes and methods listed below to pass that information over to the cart.

Shipping details attributes

Attributes Type/Description
name

String

Customer shipping name. Example: "John Doe". 

email

String

Customer shipping email. Example: "john.doe@email.com".

phone

String

Customer shipping phone number. Example: "403940281923".

country

String

Customer shipping country. Example: "United States of America".

city

String

Customer shipping city. Example: "Los Angeles".

state

String

Customer shipping state. Example: "California".

zip

String

Customer shipping zip code. Example: "90078".

address

String

Customer shipping address. Example: "1093 Rodeo Drive".

address2

String

Customer shipping additional address information. "293 Postal Box".

Shipping details methods

Methods Description
setData

Sets the entire shipping data.

setName Sets the shipping name.
setEmail Sets the shipping email.
setPhone

Sets the shipping phone.

setCountry Sets the shipping country.
setCity Sets the shipping city.
setState Sets the shipping state.
setZip

Sets the shipping zip code.

setAddress Sets the shipping address.
setAddress Sets additional shipping address information.
reset Resets the shipping data.

HANDLE the Checkout process 

Control the cart behavior by using the cart service. Use the checkout method to start the InLine Checkout experience.

Cart attributes

Attributes Type/Description
source

String

Sale originating source. Example: "YouTube Channel".

language

String

Cart language code. Example: "FR".

currency

String

Cart currency code. Example: "USD".

test

Boolean

Test order flag. Possible values:

  • true for test orders
  • false for real orders
setReturnMethod

String

Sets the ReturnMethod object. 

URL to which customer is redirected after a successful payment. Example: https://www.merchant-website.com.

coupon

String

Order promotion coupon. Example: "50%off".

token

String

Token for the authorization code.

expiration

String

The expiration date for the authorization.

orderExternalRef

String

The unique identifier of an order placed in the 2Checkout system, mirroring the reference you're using to manage order data in your system.

CustomerReference Integer. The 2Checkout system generates default customer numerical (integer) IDs automatically for all orders containing products that feature subscriptions. Can be used for new acquisitions aggregating new subscriptions under an existing Customer account.
ExternalCustomerReference String. The external customer reference.
autoAdvance

Boolean. Auto-advanced flag.

 

Possible values:

  • true for auto-advance
  • false for cart flow without auto-advance

Cart methods

Methods Description
register*

Makes the products, billing, shipping, cart and formParser services available.

These services are unavailable unless this method is called.

checkout

Starts the cart service which displays the overlay payment form.

addCoupon

Adds a coupon to the coupons list.

addCoupons Adds coupons in the cart from a list array.
removeCoupon

Removes a coupon from the coupons list.

removeCoupons

Clears all coupons from the cart instance.

setSource

Sets the order source.

setCurrency

Sets the currency on the cart instance.

setLanguage

Sets the language code for the order.

setReturnMethod

Sets the ReturnMethod object by calling TwoCoInlineCart.cart.setReturnMethod({url, type}). 

URL to which customer is redirected after a successful payment. Example: https://www.merchant-website.com.

setTest

Send true for placing a test order.

setLoaderState Handles the overlay window visibility.
setIframeState

Handles the loader visibility.

reloadCart

Reloads the cart instance.

setOrderExternalRef Sets the order external reference.
setCustomerReference Sets 2Checkout customer reference.
setExternalCustomerReference Sets external customer reference.
setCartLockedFlag

Boolean

Lock cart flag. Possible values:

  • true 
  • false

setIframeLoad

One string parameter: 'immediate' or 'delayed'. Additionally, the InLine cart can also be set by using TwoCoInlineCart',{"app":{"merchant":"MERCHANT_CODE", "iframeLoad": "immediate"} instead of TwoCoInlineCart.setup.setIframeLoad.

setIframeLoadDelay

One number parameter; sets the time in milliseconds. Modify the pre-loading time of the cart iframe by adding a delay using the TwoCoInlineCart.setup.setIframeLoadDelay method. 

setReset

Boolean

Erases all previous cart sessions from the customer's browser upon opening a new cart to avoid overlapping of the buy-link parameters. Possible values:

  • true 
  • false 
cart.setAutoAdvance

Sets the auto-advanced cart behavior. If all mandatory checkout parameters are prefilled, the shopper is advanced to the payment details page. 

addAdditionalField Sets an additional field for your account.

Retrieve cart attributes from InLine Checkout by using get methods: getTest, getLanguage, getCurrency, getSource, getCoupons, getSuccessURL, getCustomerReference, getExternalCustomerReference, getCartLockedFlag.

*When inserting the JavaScript code snippet from your Control Panel into your e-commerce website, you will get access to the library that allows you to add products, control billing and shipping details, and start the checkout process, without having to call the register() method.

Subscribe to shopping cart events

To subscribe to shopping cart events you need to call the events service 'subscribe' method with the event name as the first argument and a callback function as the second argument.

Below you can find a list of events that are supported by the shopping cart and you can subscribe to:

1. 'cart:opened' - triggers when the shopping cart is opened.

2. 'cart:closed' - triggers when the shopping cart is closed.

3. 'payment:finalized' - triggers when the payment has finalized.

4. 'fulfillment:finalized' - triggers when the fulfillment is completed.

TwoCoInLineCart.events.subscribe('cart:opened', function () {
    console.log('cart:opened triggered');
});

Sample request for catalog products

TwoCoInlineCart.setup.setMerchant('merchantCode'); // your Merchant code
TwoCoInlineCart.register();

TwoCoInlineCart.billing.setCountry('US'); // customer billing country
TwoCoInlineCart.billing.setName('John Doe'); // customer billing Name
TwoCoInlineCart.billing.setEmail('john.doe@email.com'); // customer email address
TwoCoInlineCart.billing.setCompanyName('<company name>')
TwoCoInlineCart.billing.setFiscalCode('<fiscal code>')
TwoCoInlineCart.billing.setTaxOffice('<tax office>')
TwoCoInlineCart.cart.setReset(true); // erase previous cart sessions

TwoCoInlineCart.shipping.setName('Jane Doe'); // customer Delivery name
TwoCoInlineCart.shipping.setEmail('jane.doe@email.com'); // customer Delivery email

TwoCoInlineCart.products.add({
    code: 'the-2co-product-code',
    quantity: 3
    options: [{
       name: 'color',
       value: 'red'
   }]
});

TwoCoInlineCart.products.addMany([
    {
        type: 'PRODUCT', 
        name: 'product 1', 
        price: 10, 
        tangible: true, 
        quantity: 1, 
    },
    {
        type: 'PRODUCT', 
        name: 'product 2', 
        price: 30, 
        tangible: true, 
        quantity: 1, 
    }                
]);

TwoCoInlineCart.cart.addCoupon('50%OFF'); // discount code
TwoCoInlineCart.cart.setCurrency('GBP'); // order currency
TwoCoInlineCart.cart.setLanguage('fr'); // language code
TwoCoInlineCart.cart.setOrderExternalRef('1231231'); // order external reference
TwoCoInlineCart.cart.setExternalCustomerReference('ID123extern'); // external customer reference 
TwoCoInlineCart.cart.checkout(); // start checkout process

Sample request for dynamic products

TwoCoInlineCart.setup.setMerchant('merchantCode'); // your merchant code
TwoCoInlineCart.setup.setMode('DYNAMIC'); // product type
TwoCoInlineCart.register();

TwoCoInlineCart.cart.setCurrency('USD'); // order currency

TwoCoInlineCart.products.add({
name        : 'A test dynamic product',
recurrence:{
    unit: 'WEEK',
    length: 2
},
duration: {
    unit: 'YEAR',
    length: 1
},
renewalPrice: 100.99
});
TwoCoInlineCart.cart.checkout(); //start checkout process

Add a catalog product to InLine Cart

Overview

Use the Product object to add a catalog product to the InLine Cart by calling the click event handler.

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. Use theTwoCoInlineCart.cart.checkout()method to show the cart on your page.

Sample request

HTML 

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

Javascript

window.document.getElementById('buy-button').addEventListener('click', function() {
  TwoCoInlineCart.products.add({ // Adding the desired product in the cart
    code: "74B8E17CC0", // Product code from 2Checkout cPanel account
    quantity: 3 // Quantity of the given product
  });
  TwoCoInlineCart.cart.checkout();
});

Demo

After adding the product to the InLine cart using the above method, your cart should look like this:

Update proposal

Overview

Use the updateProposal method via JSON-RPC API 6.0 to update the details of a proposal or quote.

Request parameters

Request parameters for the updateProposal method via JSON-RPC API 6.0
Parameters Type Required/Optional Description
proposalId String Required The unique merchant proposal ID generated by the 2Checkout system.
sessionId String Required Unique 2Checkout session ID code.
Name String Optional Proposal name.
UserId String Optional The unique user ID generated by the 2Checkout system.
BillTo Object Optional  The billing details associated with the proposal.
SellTo Object Optional Represents the entity using the service. Used for tax calculation.

Request sample

<?php

require ('PATH_TO_AUTH');

$proposalID = "0573e71d-38bb-4d61-88ca-b3c557517c68";

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

try {
    $result = callRPC($jsonRpcRequest, $host);
}
catch (SoapFault $e) {
    echo "Could not fetch proposal: " . $e->getMessage();
    exit;
}

$result->Name = "Updated proposal name";
$result->UserId = "myuser";
$result->BillTo->FirstName = "Billing Contact first name";
$result->BillTo->LastName = "Billing Contact last name";
$result->BillTo->Email = "contact@email.com";
$result->BillTo->Country = "US";
$result->BillTo->State = "California";
$result->BillTo->City = "San Francisco";
$result->BillTo->Address = "Street name No. 9 San Francisco, California";
$result->SellTo->FirstName = "Contact first name";
$result->SellTo->LastName = "Contact last name";
$result->SellTo->Email = "contact@email.com";
$result->SellTo->Country = "US";
$result->SellTo->State = "California";
$result->SellTo->vatCode = "85421564";
$result->SellTo->City = "San Francisco";
$result->SellTo->Address = "Street name No. 5 San Francisco, California";

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

try {
    $result = callRPC($jsonRpcRequest, $host);
    echo "Proposal: </br>", 
    var_dump($result);
}
catch (SoapFault $e) {
    echo "Could not fetch proposal: " . $e->getMessage();
    exit;
}

Request sample with prorationDate

<?php

        require ('PATH_TO_AUTH');

        $proposalID = "0573e71d-38bb-4d61-88ca-b3c557517c68";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }
        $result->Content->LineItems[0]->ProrationDate = "2020-11-14T15:28:56+00:00";


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

        try {
            $result = callRPC($jsonRpcRequest, $host);
            echo "Proposal: </br>",
            var_dump($result);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

Request sample with vatCode

<?php

        require ('PATH_TO_AUTH');

        $proposalID = "0573e71d-38bb-4d61-88ca-b3c557517c68";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

        $result->Name = "Updated proposal name";
        $result->UserId = "myuser";
        $result->BillTo->FirstName = "Billing Contact first name";
        $result->BillTo->LastName = "Billing Contact last name";
        $result->BillTo->Email = "contact@email.com";
        $result->BillTo->Country = "US";
        $result->BillTo->State = "California";
        $result->BillTo->City = "San Francisco";
        $result->BillTo->Address = "Street name No. 9 San Francisco, California";
        $result->SellTo->FirstName = "Contact first name";
        $result->SellTo->LastName = "Contact last name";
        $result->SellTo->Email = "contact@email.com";
        $result->SellTo->Country = "US";
        $result->SellTo->State = "California";
        $result->SellTo->vatCode = "85421564";
        $result->SellTo->City = "San Francisco";
        $result->SellTo->Address = "Street name No. 5 San Francisco, California";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
            echo "Proposal: </br>", 
            var_dump($result);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

Request sample with TaxExemptionId

<?php

        require ('PATH_TO_AUTH');

        $proposalID = "0573e71d-38bb-4d61-88ca-b3c557517c68";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

        $result->Name = "Updated proposal name";
        $result->UserId = "myuser";
        $result->BillTo->FirstName = "Billing Contact first name";
        $result->BillTo->LastName = "Billing Contact last name";
        $result->BillTo->Email = "contact@email.com";
        $result->BillTo->Country = "US";
        $result->BillTo->State = "California";
        $result->BillTo->City = "San Francisco";
        $result->BillTo->Address = "Street name No. 9 San Francisco, California";
        $result->SellTo->FirstName = "Contact first name";
        $result->SellTo->LastName = "Contact last name";
        $result->SellTo->Email = "contact@email.com";
        $result->SellTo->Country = "US";
        $result->SellTo->State = "California";
        $result->SellTo->TaxExemptionId = "85421564";
        $result->SellTo->City = "San Francisco";
        $result->SellTo->Address = "Street name No. 5 San Francisco, California";

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

        try {
            $result = callRPC($jsonRpcRequest, $host);
            echo "Proposal: </br>", 
            var_dump($result);
        }
        catch (SoapFault $e) {
            echo "Could not fetch proposal: " . $e->getMessage();
            exit;
        }

Response

The updateProposal call via JSON-RPC API 6.0 returns the Proposal object.

Place orders with catalog products

Overview

Use this object via JSON-RPC API 6.0 to create new orders and collect payments from shoppers using catalog products defined in your Merchant Control Panel.

For orders that require physical delivery, if no shipping methods are provided, 2Checkout will add to the cart your account's default shipping configuration.

You can find a list of common errors that may arise when using the placeOrder call via API 6.0 here.

Supported payment methods/flows

Requirements

For credit card orders placed using 2Checkout API 6.0 or a more recent version, you need to pass through additional parameters that support the 3D Secure flow. 3D Secure works by redirecting 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 customers having to go through an extra layer of authentication.

Send the following parameters in the placeOrder call, as part of the PaymentDetails 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.
WSOrder Optional (String)
  The WSOrder parameter is used to control the website URL displayed in the email messages shoppers receive after they place an order. By default, 2Checkout reports the URL set as Homepage in the Account information area. Adding WSOrder to the buy-links for your products will cause the optional website address set by using the parameter to override and replace the Homepage URL in the email notifications sent to customers. The behavior is similar to the WS_ORDER parameter supported on checkout/cart pages and described here.

Response

Parameters Type/Description
Order information Object
  Object containing order information.

Parameters

 
Parameters Type/Description
Currency String / Optional
  The currency ISO code for the payment - ISO 4217. Example: “usd.”
Country String / Optional
  Shopper country. ISO 3166 two-letter code. Example: “us.”
Language String / Optional
  ISO 639-1 two-letter code. The language used for the purchase process. Example: “en.”
ExternalReference String / Optional
  Set external reference identifiers for orders. Enables you to replicate the functionality of the REF parameter included into Buy Links. Maximum 100 characters. If there is a need for longer references, you can apply an md5 hash for any string value, resulting in a 32 characters string. You can verify the hash after the order notification, on the client side.
Source String / Optional
 

The link source for the sales. Enables you to replicate the functionality of the SRC (separate link identifier) parameter when included into Buy Links. Use the SRC parameter to track sale sources.

 

Maximum length 255 characters.

CustomerReference Integer/Optional
  Set an external customer ID, attached to the customer.
Affiliate Object/Optional
                 AffiliateCode String/Required
  The affiliate unique code (as returned by the affiliates API methods).
AffiliateSource String/Optional
  The affiliate source.
Items Array of objects / Required
  Details below. 
  OrderItem Object
      Details below. 
    Code String / Mandatory
      Unique product identifier your control. Max length 256 characters. Only for catalog products.
    Quantity Integer / Optional
      Number of units
    PriceOptions Array of strings / Optional
      Array of price option codes.
    SKU String / Optional
      SKU identifier.
    Price Object - Can be NULL. If Price Type is set to 'CUSTOM', dynamic pricing can be added to the order via the Amount parameter.
    CrossSell Object – Can be NULL
        Details below. 
      ParentCode String 
        The product code of the master product you set to trigger the campaign.
      CampaignCode String 
        Unique, system-generated identifier for cross-sell campaigns.
    Trial Object – Can be NULL
        Details below. 
      Period Integer 
        The length of the trial subscription lifetime in days.
      Price Double / Optional
        Total trial price in the payment currency before 2Checkout deducts any taxes, discounts, etc.
    AdditionalFields Array of objects – Can be NULL
      AdditionalFieldSet Object – Can be NULL
        Code String
          The alpha-numeric characters, underscores and dashes that are set as the field identifier.
        Value String
          Selected field value.
    SubscriptionStartDate String
     

Specify the date time stamp when the subscription becomes active. Format 2016-07-02 22:22:22 (YYYY-MM-DD HH:mm:ss). Available for JSON-RPC and REST.

Send empty or NULL to activate subscriptions on the same date when customers purchase them.

You can exclude HH:mm:ss when sending the date and include only YYYY-MM-DD. In this case, 2Checkout uses 00:00:01. Default time zone GMT+02:00.

    SubscriptionCustomSettings Object/Optional
      To use this, the ExtraInformation object with AssistedSale property set to "true" is required.
   

CycleAmountType

String/Required
      Billing cycle unit NET/GROSS.
   

CycleUnit

String/Required
      DAY/MONTH. Can be NULL.
   

CycleAmount

Float/Required
      Billing cycle (renewal) price.
   

CycleLength

Integer/Required
      Billing cycle length. Can be NULL.
   

ContractLength

Integer/Optional
   
 
Contract period length (expressed in the specified CycleUnit; must be multiple of CycleLength). Can be NULL.
   

MerchantDealAutoRenewal

Boolean/Optional
      Merchant deal auto-renewal flag.
   

ClientDealAutoRenewal

Boolean/Optional
      Client deal auto-renewal flag.
BillingDetails Object / Required
    Details below. 
  FirstName String / Required
    Shopper name.
  LastName String / Required
    Shopper surname.
  CountryCode String / Required
    Shopper country. ISO 3166 two-letter code.
  State String/Optional – Required for US, Canada, Brazil, Turkey, India and Romania
    The state in the shopper's country. Mandatory when you set the Billing Country to US, Canada, Brazil, Turkey, India and Romania. Use case insensitive utf8 strings for the full name, or just the two letter code.
  City String /Required
    Shopper city.
  Address1 String/Required
    Shopper address.
  Address2 String / Optional
    Shopper address.
  Zip String/Required
    ZIP/ Postal code.
  Email String/Required
    Shopper email address.
  Phone String / Optional
    Shopper phone number. Mandatory when you set Brazil as the Billing Country. Can be NULL.
  Company String / Optional
    Company name. Can be null for end users. When present, you also need to provide the FiscalCode.
  FiscalCode String / Optional– Required for Brazil
   

• For companies, it needs to be the VAT ID. 2Checkout will validate the value provided and throw an error if the VAT ID is invalid/incorrect when calling setPaymentDetails. When present, you also need to provide the Company name.

• Mandatory when you set Brazil as the Billing Country. For Brazilian customers it represents the Fiscal Code (CPF/CNPJ).

Mandatory when you set India as the Billing Country, and purchase is made by a Company.

• Can be NULL for end users.

  TaxExemptionId  Optional (string)
    Tax Exempt Certification id used to deduct taxes for US orders
Example: 1b80eecc349v
DeliveryDetails Object / Required
                    Details below. 
    FirstName String / Required
                    Shopper name from the delivery details.
    LastName String / Required
                    Shopper surname from the delivery details.
    CountryCode String / Required
                    Shopper country. ISO 3166 two-letter code from the delivery details.
    State String/Optional – Required for the US, Canada, Brazil, Turkey, India, and Romania
                    The state in the shopper's country. Mandatory when you set the Billing Country to US, Canada, Brazil, Turkey, India, and Romania. Use case insensitive utf8 strings for the full name, or just the two-letter code.
    City String / Optional
                    Shopper city from the delivery details.
    Address1 String / Optional
                    Shopper address from the delivery details.
    Address2 String / Optional
                    Shopper address from the delivery details.
    Zip               String / Optional
                    ZIP/ Postal code from the delivery details.
    Email String / Optional
      Shopper email address from the delivery details.
    Phone String / Optional
      Shopper phone number from the delivery details. Mandatory when you set Brazil as the Billing Country. Can be NULL.
    Company String / Optional
      Company name from the delivery details. Can be null for end users. When present, you also need to provide the FiscalCode.
DeliveryInformation

Object / Optional

For products that require physical delivery, use this object to send the shipping method.

    ShippingMethod        

Object

Details below

      Code           String
  System-generated identified for your shipping method configuration
PaymentDetails Object / Required
  Adapt this object to the desired payment method.
  Type Required (string)
   

The payment method:

  • CC (credit/debit card - including local Brazilian cards).
  • ENCRYPTED_PAYMENT_DATA (client-side encryption)
  • PAYPAL
  • PAYPAL_EXPRESS
  • CCNOPCI(credit/debit card for non-PCI certified merchants).
  • TEST (for test orders).
  • PREVIOUS_ORDER(place new orders using the reference of a previous order).
  • EXISTING_PAYMENT_DATA  (use a card one of your customers already used to purchase from your account).
  • WIRE – the placeOrder response includes Wire payment details.
  • CHECK – the placeOrder response includes Check payment details.
  • WE_CHAT_PAY (for WeChat payments).
  • IDEAL (for iDEAL payments).
  • PURCHASEORDER - use for orders with POs.
  • FREE – for 0 value orders for which you’re not requiring customers to provide payment details.
  • ALIPAY
  • UNIONPAY
  • DIRECT_EBANKING 
  • TRUSTLY (for Trustly payments)
  • EES_TOKEN_PAYMENT (2Pay.js)
  • APPLE PAY
  • BOLETO/PIX
  • GOOGLE PAY
  • Echeck/ACH
  • Stored Credit
  Currency Required (string)
    The currency ISO code for the payment - ISO 4217. Example: “usd.”
  PaymentMethod Optional (object)
   

Object structure and parameters differ according to payment method selected and API method (placing orders (POST) vs. retrieving order data (GET)).

 

NULL for 0 value orders for which you’re not requiring customers to enter payment details.

                                                              RecurringEnabled Optional (boolean)Optional (boolean)
   

true – shopper checks the auto-renewal checkbox and 2Checkout charges subscription renewals using a recurring billing process.

false – shopper doesn’t check the auto-renewal checkbox.

      CardPayment Optional (object)
          Details below. 
        CardNumber Required (string)
          The credit/debit card number.
        CardType Required (string)
          visa, visaelectron, mastercard, maestro, amex, discover, dankort, cartebleue, jcb, hipercard, elo
        ExpirationYear Required (string)
          The year in which the card expires.
        ExpirationMonth Required (string)
          The month in which the card expires.
        HolderName Required (string)
          Cardholder name.
        CCID Required (string)
          Credit Card Identification - an extra ID printed on the card, usually a 3-4 digit number, the CVC2/CVV2.
        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.
        HolderNameTime Optional (float)
         

The interval of time in seconds in which shoppers enter their name in the HolderName field. An abnormally short interval is usually a red flag for fraud attempts.

Can be NULL, but not a negative number.

        CardNumberTime Optional (float)
         

The interval of time in seconds in which shopper enters their card number in the CardNumber field. An abnormally short interval is usually a red flag for fraud attempts.

Can be NULL, but not a negative number.

        InstallmentsNumber  Optional (Int)
          Number of installments. Available only when customers un Brazil pay with Visa or MasterCard using Brazilian Real as the order currency. Use 1 or exclude the parameter for full payments. 
      PayPalExpress Optional (object)
          Details below. 
        Email Optional (string)
          Email address customers use for their PayPal account.
        ReturnURL Optional (string)
          The PayPal Express Checkout redirect URL returned by calling the getPayPalExpressCheckoutRedirectURL method. The return URL is the page on your website to which PayPal redirects yourbuyer's browser after the buyer logs into PayPal and approves the payment. Typically, this is a secure page (https://...) on your site.
        CancelURL Optional (string)
          The cancel URL is the page on your website to which PayPal redirects your buyer's browser if the buyer does not approve the payment. Typically, this is the secure page (https://...) on your site from which you redirected the buyer to PayPal.
      PreviousOrder Optional (Object)
          Details below. 
        RefNo Optional (string)
         

Order reference a previous purchase that reached the Approved/Complete status. You can use orders for which customers paid with credit/debit cards or with PayPal. The status of orders should be AUTHRECEIVED or COMPLETE.

 

Check the validity of references with the isValidOrderReference method.

 

The 2Checkout system blocks you from using references for fraudulent or potentially fraudulent orders.

      PurchaseOrderPaymentDetails Optional (Object)
          Details below. 
        InternalPONumber Optional (string)
          Identifier that business customers use internally in their organization to track and manage Purchase Orders (PO). Can be NULL.
        AutoApprove Optional (boolean)
         

TRUE - requires activation of the PO AutoApprove package (If the package is inactive 2Checkout returns an error). Please contact 2Checkout. When AutoApprove is TRUE, 2Checkout no longer requires that business customers upload a PO document. As such, PO orders are automatically approved for your account, without a PO doc. 2Checkout sets the PURCHASE_PENDING status for auto-approved PO orders.

FALSE - Default. Send this if the PO AUtoApprove package is not available for your account. 2Checkout uses the same flow as cart purchases with Purchase Orders for business customers placing orders with POs via API. This means that customers receive the same emails as if they made the purchase using the cart and need to update the PO document, which is reviewed by 2Checkout and that you need to approve. 2Checkout sets the AVAITING_UPLOAD status for POs andUnfinished for their orders.

 

Can be NULL.

      WE_CHAT_PAY Optional (string)
        Details below
        ReturnURL Optional (string)
          The return URL is the page to which your customers are redirected after their successful payment.
        CancelURL Optional (string)
          The cancel URL is the page to which your customers are redirected after their failed payment attempt.
      IDEAL Optional (string)
        Details below
        ReturnURL Optional (string)
          The return URL is the page to which your customers are redirected after their successful payment.
        CancelURL Optional (string)
          The cancel URL is the page to which your customers are redirected after their failed payment attempt.
        BankCode Required (string)
          String contains the SWIFT code of the bank, the plus sign "+", and the first 3 characters from the bank name. E.q.: in the case of Rabobank, code parameter is "RABONL2U+RAB".
      EXISTING_PAYMENT_DATA Optional (Object)
        By using EXISTING_PAYMENT_DAT you no longer require shoppers to enter any payment details.
        TransientToken Optional (string)
          Returned as a part of the process of retrieving customer information by SSOToken.
      TRUSTLY  Optional (string)
          Details below.
        ReturnURL Optional (string)
     

 
  The return URL is the page to which your customers are redirected after their successful payment. The return URL is the page to which your customers are redirected after their successful payment. 
      DIRECT_DEBIT_ACH Optional (object)
          Details below.
        AccountHolderName Optional (string)
          Full name of the account holder.
        BankRoutingNumber Optional (string)
          Bank Routing number consisting of up to 17 digits.
        AccountNumber Optional (string)
          Account number with fixed 9 digit length.
        AccountType Optional (string)
          Possible values are "S" for SAVINGS accounts or "C" for CHECKING accounts.
  CustomerIP Optional (string)
    Shopper IP.
Promotions Optional (Array of strings)
  Array of promotion codes.
AdditionalFields Object / Optional
    Details below. 
  Code Optional (string)
    The alpha-numeric characters, underscores, and dashes that are set as the field identifier.
  Text Optional (string)
    Field text visible to shoppers in the cart.
  Value Optional (string)
    Selected field value.
LocalTime Optional (string)
 

Local shopper time in the following format: Y-m-d H:i:s.

This parameter can impact the fraud score of an order when it's missing, NULL or incorrectly formatted.

GiftDetails Optional (object)
  Contains contact details for the recipient of a gift purchase.
  FirstName Optional (string)
    First name of gift recipient.
  LastName Optional (string)
    Last name of gift recipient.
  Email Optional (string)
    Email of gift recipient. 2Checkout uses this email for the delivery/fulfillment process.
  GiftNote Optional (string)
    Custom text shoppers provide as a message to the gift recipient.

Request example

<?php
declare(strict_types=1);
class Configuration
{
    public const MERCHANT_CODE = '';
    public const MERCHANT_KEY = '';
    public const URL = 'http://api.2checkout.com/rpc/6.0';
    public const ACTION = 'placeOrder';
    public const ADDITIONAL_OPTIONS = null;
    //array or JSON
    public const PAYLOAD = <<<JSON
{
    "Currency": "USD",
    "Country": "US",
    "CustomerIP": "91.220.121.21",
    "Source": "testAPI.com",
    "WSOrder": "http://www.myurlfortest.com",
    "ExternalReference": null,
    "BillingDetails": {
        "Address1": "Test Address",
        "City": "London",
        "CountryCode": "US",
        "Email": "customer@2Checkout.com",
        "FirstName": "Customer",
        "LastName": "2Checkout",
        "Phone": "556133127400",
        "State": "DF",
        "Zip": "70403-900"
    },
    "PaymentDetails": {
        "Type": "CC",
        "Currency": "USD",
        "CustomerIP": "91.220.121.21",
        "PaymentMethod": {
            "CCID": "123",
            "CardNumber": "4111111111111111",
            "CardNumberTime": "12",
            "CardType": "Visa",
            "ExpirationMonth": "12",
            "ExpirationYear": "2023",
            "HolderName": "John Doe",
            "HolderNameTime": "12",
            "RecurringEnabled": true,
            "Vendor3DSReturnURL": "www.test.com",
            "Vendor3DSCancelURL": "www.test.com"
        }
    },
    "Items": [
        {
            "Code": "testprod",
            "Quantity": "1"
        }
    ]
}
JSON;
}
class Client
{
    private const LOGIN_METHOD = 'login';
    private $calls = 1;
    private $sessionId;
    private function generateAuth(): array
    {
        $merchantCode = Configuration::MERCHANT_CODE;
        $key = Configuration::MERCHANT_KEY;
        $date = gmdate('Y-m-d H:i:s');
        $string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
        $hash = hash_hmac('md5', $string, $key);
        return compact('merchantCode', 'date', 'hash');
    }
    public function login(string $url)
    {
        $payload = $this->generateAuth();
        $response = $this->call($url, array_values($payload), self::LOGIN_METHOD);
        $this->sessionId = $response['result'];
    }
    public function call(
        string $url = Configuration::URL,
               $payload = Configuration::PAYLOAD,
        string $action = Configuration::ACTION
    ): ?array {
        if (empty($this->sessionId) && $action !== self::LOGIN_METHOD) {
            $this->login($url);
        }
        if(is_string($payload)) {
            $payload = json_decode($payload, true);
        }
        if (!empty($this->sessionId)) {
            $payload = [$this->sessionId, Configuration::ADDITIONAL_OPTIONS, $payload];
        }
        $payload = array_filter($payload);
        $request = json_encode([
            'jsonrpc' => '2.0',
            'method' => $action,
            'params' => $payload,
            'id' => $this->calls++,
        ]);
        $curl = curl_init($url);
        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', 'Cookie: XDEBUG_SESSION=PHPSTORM'));
        curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
        $response = curl_exec($curl);
        if(empty($response)) {
            die('Server unavailable');
        }
        echo $response . '</br>';
        return json_decode($response, true);;
    }
}
$client = new Client();
$result = $client->call();
var_dump($result);

 

Remove promotion sources

Request

<?php 

class Client
{
    protected static $merchantCode;
    protected static $loginDate;
    protected static $hash;
    protected static $baseUrl;
    protected static $callCount = 0;
    protected static $sessionId = '';

    protected static $client;

    public static function setCredentials($code, $key)
    {
        static::$merchantCode = $code;
        static::$loginDate = gmdate('Y-m-d H:i:s');
        static::$hash = hash_hmac('md5', strlen($code) . $code . strlen(static::$loginDate) . static::$loginDate, $key);
        static::$sessionId = static::login();
    }

    public static function setBaseUrl($url)
    {
        static::$baseUrl = $url;
    }

    public static function login()
    {
        $client = static::getClient();
        return $client->login(static::$merchantCode, static::$loginDate, static::$hash);
    }

    public static function __callStatic($name, $arguments = array())
    {
        $client = static::getClient();

        array_unshift($arguments, static::$sessionId);
        $response = call_user_func_array(array($client, $name), $arguments);

        return $response;
    }

    protected static function getClient()
    {
        $opts = array(
            'http'=> ['user_agent' => 'PHPSoapClient'],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        );

        if (null === static::$client) {
            static::$client = new \SoapClient(static::$baseUrl . '?wsdl', [
                'location' => static::$baseUrl,
                'cache_wsdl' => WSDL_CACHE_NONE,
                'stream_context' => stream_context_create($opts),
            ]);
        }

        return static::$client;
    }
}

Client::setBaseUrl('https://api.avangate.com/soap/3.1/');
Client::setCredentials('YOUR_MERCHANT_CODE', 'YOUR_SECRET_KEY');
Client::login();

$promotionCode = 'YOUR_PROMOTION_CODE'; // code of the promotion that you want to update
$sources = ['source1', 'source2']; // array of sources to remove from the promotion

$response = Client::deletePromotionSources($promotionCode,$sources); // Set the promotion discount to the existing promotion
var_dump($response);

Update price options

Overview

Use the updatePriceOptionGroup method to update/edit an existing price options group you configured for your account. Price options intervals cannot overlap. 

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.

PriceOptionsGroup

Required (object)

 

Use this object to update/edit a new price option group for your account.

You cannot update the Code and Required parameters of the price options group.

Response

bool(true)

Request

<?php

require ('PATH_TO_AUTH');

$SearchOptions = new stdClass ();
$SearchOptions->Name = 'New Users from API';

$SearchOptions->Types = array('INTERVAL', 'RADIO'); //RADIO, CHECKBOX, INTERVAL, COMBO, INTERVAL

$SearchOptions->Limit = 10;
$SearchOptions->Page = 1;

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

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

$updatedPriceOptions = $existentPriceOptions[0];

$existentPriceOptions[0]->Translations[0]->Name = 'New Users from API3';
$existentPriceOptions[0]->Translations[0]->Language = 'EN';

$updatedPriceOptions = $existentPriceOptions[0];
echo "$updatedPriceOptions->Name";

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

?>

Retrieve order fields

Overview

Use the getAdditionalFields method to extract information about additional fields you set up for your account.

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.

Response

AdditionalFields

Array of orders

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

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

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

var_dump("AdditionalFields", $AdditionalFields);


?>

Retrieve a promotion

Overview

Use the getPromotion method to extract information on a promotion you set up for your account.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

PromotionCode

Required (string)

 

System-generated identifier 2Checkout associated with promotion campaigns.

Response

Parameters Type/Description
Promotion Object 

 

Request

<?php

require ('PATH_TO_AUTH');

$PromotionCode = 'YOUR_COUPON_CODE';

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

?>

Need help?

Do you have a question? If you didn’t find the answer you are looking for in our documentation, you can contact our Support teams for more information. If you have a technical issue or question, please contact us. We are happy to help.

Not yet a Verifone customer?

We’ll help you choose the right payment solution for your business, wherever you want to sell, in-person or online. Our team of experts will happily discuss your needs.

Verifone logo