Skip to main content

Payment flow for E-wallets (online payment methods)

Overview

E-wallets are online payment methods where the order is registered by 2Checkout, but the shopper has to reach a 3rd party's website in order to authenticate and finalize the payment. PayPal is one of the most used E-wallet solutions that dominate the eCommerce world, but other local players, especially in Asian countries, are starting to gain market share.

The following payment methods are supported for the E-wallet (online payment methods) flow PayPal, Alipay, WeChat, iDeal.

Availability

Available to all 2Checkout accounts.

PayPal

Payment method Object structure

Field name Type Required/Optional Description
ReturnURL String Mandatory The return URL is the page on your website to which PayPal redirects your buyer's browser after the buyer logs in to PayPal and approves the payment. Typically, this is a secure page (https://...) on your site.
Email String Optional Email address customers use for their PayPal account.

Request example

{
   "Language":"en",
   "Country":"US",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"USD",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"DD996A4DB3",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"US",
      "State":"New York",
      "City":"New York",
      "Address1":"Example Street",
      "Zip":"10005",
      "Email":"customer@email.com"
   },
   "PaymentDetails":{
      "Type":"PAYPAL",
      "Currency":"USD",
      "PaymentMethod":{
         "RecurringEnabled":false,
         "ReturnURL":"http:\/\/mywebsite.com\/order\/",
         "Email":"customer@email.com"
      }
   }
}

Redirecting shoppers to PayPal

If the order is placed successfully, the 2Checkout API responds with the complete order information. Inside the PaymentDetails node, you will find the PaymentMethod node that contains the RedirectURL

The shopper needs to be redirected to this URL that takes them to the PayPal website to finalize the payment. Once the payment is finalized, shoppers are redirected back to the ReturnURL

PayPal Express - Alternative Flow

In some checkout flows, the user experience might require some details filled in by the shopper on PayPal's side. In order to streamline the checkout experience, this information can be used when placing orders by using the PayPal Express payment method. 

These are the required steps for the PayPal Express flow:

  1. First, you must retrieve the RedirectURL from PayPal by calling the getPayPalExpressCheckoutRedirectURL method for JSON-RPC and SOAP, or by making a PUT request to /paymentmethods/PAYPAL_EXPRESS/redirecturl/ on REST.
  2. The body of the request must contain the order object with, at a minimum, the product information as well as the payment details: the customer's email address and a ReturnURLthe page on the shop's side where the shopper is redirected after the flow is completed on the PayPal's side. 
  3. The ReturnURL parses the response that PayPal sends in order to fetch the needed information and finalize the payment. 
  4. The getPayPalExpressCheckoutRedirectURL method will return a URL where the shopper needs to be redirected in order to complete the payment.
  5. Once the shopper completes the payment, PayPal returns the shopper to the URL provided in the ReturnURL. The information provided by the shopper on PayPal's side is available in the GET parameters of the ReturnURL (all information is MIME base64 encoded):
  • billing details (under the billingDetails key)
  • delivery details (under the deliveryDetails key)
  • a token in the URL.

6. If the shopper cancels their payment, then the cancel key will be returned in the URL. 

7. The information provided in the billing and delivery details must be filled in the order object. 

The payment method object will look like this:

Field name Type Required/Optional Description
Email String Required The email of the customer, as used when triggering the getPayPalExpressCheckoutRedirectURL method.
Token String Required The token returned by PayPal.
ReturnURL String Required The return URL on the shop side that will handle successful orders.
CancelURL String Required The return URL on the shop side that will handle canceled orders.

In JSON, this looks like:

    "PaymentDetails": {
        "Type": "PAYPAL_EXPRESS",
        "Currency": "EUR",
        "CustomerIP": "91.220.121.21",
        "PaymentMethod": {
            "Email": "customer@email.com",
            "Token": "EC-470284976K7901234",
            "ReturnURL": "http://shop.com/place_order_api_json_paypal_express_response.php",
            "CancelURL": "http://shop.com/place_order_api_json_paypal_express_response.php?cancel=true"
        }
    }

Alipay

Payment method object structure

Alipay does not require any mandatory fields to be sent in the PaymentDetails node of the request.

Request example

{
   "Language":"en",
   "Country":"HK",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"CNY",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"DD996A4DB3",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"HK",
      "State":"Hong Kong",
      "City":"Hong Kong",
      "Address1":"Example Street",
      "Zip":"999077",
      "Email":"example@email.com"
   },
   "PaymentDetails":{
      "Type":"ALIPAY",
      "Currency":"CNY",
      "PaymentMethod":{
         "RecurringEnabled":false
      }
   }
}

Redirecting shoppers to Alipay

If the order is placed successfully, the 2Checkout API responds with the complete order information. Inside the PaymentDetails node, you will find the PaymentMethod/Redirect node that contains the URL

The shopper needs to be redirected to this URL. This takes them to the Alipay website, where they can finalize the payment. 

WeChat

Payment method object structure

Field name Type Required/Optional Description
ReturnURL  String Required The URL address to which customers are redirected after the payment is completed successfully.
CancelURL  String Required The URL address to which customers are redirected after the payment is completed unsuccessfully.

Request example

{
   "Language":"en",
   "Country":"CN",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"USD",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"DD996A4DB3",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"CN",
      "State":"Beijing",
      "City":"Beijing",
      "Address1":"Example Street",
      "Zip":"102629",
      "Email":"example@email.com"
   },
   "PaymentDetails":{
      "Type":"WE_CHAT_PAY",
      "Currency":"USD",
      "PaymentMethod":{
         "RecurringEnabled":false,
         "ReturnURL":"http:\/\/yourreturnurl.com",
         "CancelURL":"http:\/\/yourcancelurl.com"
      }
   }
}

Redirecting shoppers to WeChat

If the order is placed successfully, the 2Checkout API responds with the complete order information. Inside the PaymentDetails node, you will find the PaymentMethod/Authorize node that contains the Href, Method, and Params node. 

The shopper needs to be redirected to this Href, using the Method mentioned in the API response. Additionally, the parameters in the Params node need to be sent as key-value pairs in the request.

This takes shoppers to the WeChat website, where they can finalize the payment. 

iDeal

iDeal is a standardized online banking-based payment method tailored to users in the Netherlands. iDEAL supports online payments via secure online transfers directly between bank accounts. 

To place an order with iDeal, the shopper needs to select the bank that they use. The full list of supported banks can be queried via API by calling the getIdealIssuerBanks method (SOAP and JSON-RPC) or making a GET request /paymentmethods​/IDEAL​/issuerbanks​/ on REST.

The output of this API call is the list of supported banks, as code (to be used when placing the order), and the user-readable name of the bank.

[
   {
      "Code":"ABNANL2A+ABN",
      "Name":"ABN AMRO"
   },
   {
      "Code":"RABONL2U+RAB",
      "Name":"Rabobank"
   },
   {
      "Code":"INGBNL2A+ING",
      "Name":"ING"
   }
]

Payment method Object structure

Field name Type Required/Optional Description
BankCode String Required The bank code as returned by the getIdealIssuerBanks API call.
ReturnURL  String Required The URL address to which customers are redirected after the payment is completed successfully.
CancelURL  String Required The URL address to which customers are redirected after the payment is completed unsuccessfully.
BankCode String Required The bank code as returned by the getIdealIssuerBanks API call.

 Request example

{
   "Language":"en",
   "Country":"NL",
   "CustomerIP":"10.10.10.10",
   "Source":"Website",
   "ExternalCustomerReference":"externalCustomerId",
   "Currency":"EUR",
   "MachineId":"123456789",
   "Items":[
      {
         "Code":"DD996A4DB3",
         "Quantity":1
      }
   ],
   "BillingDetails":{
      "FirstName":"Customer First Name",
      "LastName":"Customer Last Name",
      "CountryCode":"NL",
      "State":"North Holand",
      "City":"Amsterdam",
      "Address1":"Example Street",
      "Zip":"1183",
      "Email":"example@email.com"
   },
   "PaymentDetails":{
      "Type":"IDEAL",
      "Currency":"EUR",
      "PaymentMethod":{
         "ReturnURL":"http:\/\/yourreturnurl.com",
         "CancelURL":"http:\/\/yourcancelurl.com",
         "BankCode":"RABONL2U+RAB"
      }
   }
}

Redirecting shoppers to finalize the payment

Once the order has successfully been placed, in the response in the PaymentDetails/PaymentMethod/Authorize node, you have the information needed to compose the URL where the shopper needs to finalize the payment.

The shopper needs to reach the Href via the Method HTTP method, with the key-values in the Params in the request parameters.

 "PaymentDetails":{
      "Type":"IDEAL",
      "Currency":"eur",
      "PaymentMethod":{
         "Authorize":{
            "Href":"https:\/\/api.avangate.com\/6.0\/scripts\/ideal\/authorize",
            "Method":"GET",
            "Params":{
               "avng8apitoken":"ukaiuljobm84jmt3"
            },
            "AvangateId":null
         },
         "ReturnURL":"http:\/\/yourreturnurl.com",
         "CancelURL":"http:\/\/yourcancelurl.com",
         "BankCode":"RABONL2U+RAB",
         "RecurringEnabled":false
      },
      "CustomerIP":"5.12.32.22"
   },

Once the shopper has finalized the payment, the order will be marked with 'status = Complete'.

Integration test cases

  1. Build a request in order to place a new order, with all the relevant information. Make sure that when the order is sent in the API, the response contains an order object (order was placed successfully).
  2. Make sure that you handle the redirect to the 3rd party site.
  3. If you have any additional webhook integrations, make sure that the webhooks are correctly configured and that the notifications are received and processed successfully. 

 

How to customize and style the 2Pay.js payment form

Overview

The 2Pay.js payment form can be customized and styled by providing an object as the second argument when calling the create method from component service in the TwoPayClient JavaScript SDK.

Before moving on to the payment form customization, let's take a look at how the elements work and how they are rendered by the browser.

To implement the documentation below, you need to have a 2Pay.js client already set up and a payment form already working inside your web page. If not, read this article to see the basic implementation of 2Pay.js.

Merchant’s Web Page and the 2Pay.js Form

As you probably noticed, the payment form renders inside an iFrame so the merchant’s page CSS will have to be written separately from the payment form. For example, you have a Full name field which is on the merchant’s page and the credit card, CVV and expiration date fields that are in the iFrame. However, the entire form will have to look and behave the same and the only way to customize the iFrame is by using the style configuration.

Payment Form Elements and Behavior

Rendering the payment form with the default styling (no styles applied) will consist of the following structure.

Generic elements

You can use generic elements as high-level HTML elements.

<body>
  <div>
    <form class="form">
      <div class="row">
        <div class="col">
        
          <!-- Credit card number field content goes here -->
          
        </div>
      </div>
      <div class="row">
        <div class="col">
        
          <!-- Expiration date field content goes here -->
        
        </div>
        <div class="col">
        
          <!-- CVV field content goes here -->
        
        </div>
      </div>
    </form>
  </div>
</body>

The Payment Form <body> Element

The payment form is rendered inside an iFrame and it needs to have an HTML, a <body> and a <head> tag.

CSS rules such as font, color, and background can be applied to the <body> by providing styles in the style object, as shown in the example below.

let component = jsPaymentClient.components.create('card', {
    margin                      : 0,
    fontFamily                  : 'Helvetica, sans-serif',
    fontSize                    : '1rem',
    fontWeight                  : '400',
    lineHeight                  : '1.5',
    color                       : '#212529',
    textAlign                   : 'left',
    backgroundColor             : '#ffffff'
});

HTML Elements <div class=”row”> and <div class=”col”>

The purpose of these two elements is to offer a way to divide the payment form content. For example, using rows and columns by applying CSS rules for them. Below is an example of how the payment form can display with the credit card number field on a row and expiration date field and CVV field on another row with two columns.

var component = twoPayClient.components.create('card', {
    '.row': {
        display : 'flex',
        flexWrap: 'wrap'
    },
    '.col': {
        flexBasis: '0',
        flexGrow : '1',
        maxWidth : '100%',
        padding  : '0',
        position : 'relative',
        width    : '100%'
    },
});

Card number field 

The card number field will be rendered together with several other HTML elements that are represented and explained below.

 <body>
  <div>
    <form class="form">
      <div class="row">
        <div class="col">
        
          <!-- Credit card number field START -->
          <div class="field-container card-number">
            <div class="field-wrapper form-group is-error is-empty is-required">
              <label for="card-number" class="label control-label">Card number</label>
              
              <div class="input-wrapper">
                <input type="text" autocomplete="cc-number" id="card-number" name="card-number" class="field form-control">
                <i class="card-icon"></i>
                <i class="lock-icon"></i>
                <!-- default state of the error or valid icon -->
                <i class="" style="display: none;"></i>
              </div>
            </div>
            
            <span class="validation-message">Enter a valid card number.</span>
          </div>
          <!-- Credit card number field END -->
    ...

The field container <div class=”field-container card-number”>

It holds all the card number field elements and it can customizable, as shown in the example below.

 var component = twoPayClient.components.create('card', {
    '.field-container': {
        paddingBottom: '14px'
    }
});

The field wrapper <div class=”field-wrapper”>

It contains the label, input, and icons and offers support for different states (validation or transition):

  • default → Contains the base class names “field-wrapper form-group is-error is-empty is-required“. Usually, you will apply only some spacing to this element:
var component = twoPayClient.components.create('card', {
    '.field-wrapper': {
        paddingRight: '25px'
    }
});
  • focus → Offers support for when the input is focused by adding the class name “is-focused” to this element.
  • error → Offers support for when there is a validation error and adds the class name “is-error“ to this element.
  • valid → Offers support for when the field validation passes and adds the class name ”is-valid” to this element.

The field’s label <label class="label control-label">

Styling the field’s label:

var component = twoPayClient.components.create('card', {
    label: {
        display     : 'inline-block',
        marginBottom: '9px',
        color       : '#313131',
        fontSize    : '14px',
        fontWeight  : '300',
        lineHeight  : '17px'
    }
});

Styling the field’s label on focus:

var component = twoPayClient.components.create('card', {
    '.is-focused label': {
        color: '#83ddeb'
    }
}); 

Styling the field’s label on error: 

var component = twoPayClient.components.create('card', {
    '.is-error label': {
        color: '#D9534F'
    }
});

Styling the field’s label when valid: 

var component = twoPayClient.components.create('card', {
    '.is-valid label': {
        color: '#1BB43F'
    }
});

The input wrapper <div class="input-wrapper">

Offers support for absolute positioning of the icons:

 var component = twoPayClient.components.create('card', {
    '.input-wrapper': {
        position: 'relative'
    }
});

The input <input type=”text” class=”field form-control”>

This is the actual input field where the user types in the data.

Styling the input:

var component = twoPayClient.components.create('card', {
    'input': {
        fontSize: '18px'
    }
});

 Styling the input on focus:

var component = twoPayClient.components.create('card', {
    'input:focus': {
        border         : '1px solid #5D5D5D',
        backgroundColor: '#FFFDF2'
    }
});

Styling the input on error:

 var component = twoPayClient.components.create('card', {
    '.is-error input': {
        border: '1px solid #D9534F'
    }
});

 Styling the input when valid:

var component = twoPayClient.components.create('card', {
    '.is-valid input': {
        border: '1px solid #1BB43F'
    }
});

The card icon <i class="card-icon"></i> or <i class="card-type-icon"></i> (card number specific element)

This element represents the card icon which appears by default in the card number field. The “card-icon” class name changes into “card-type-icon“ after the credit card auto-detection returns a card type.

This element’s style can also be customized:

var component = twoPayClient.components.create('card', {
    '.card-icon': {
      left: '10px'
    },
    '.card-type-icon': {
      right: '30px'
    }
});

The lock icon <i class="lock-icon"></i> (available for card number and CVV fields)

This element can be customized the same way as the card icon or it can be hid.

var component = twoPayClient.components.create('card', {
    '.lock-icon': {
      display: 'none'
    }
});

The lock icon <i class="error-icon"></i> or <i class="valid-icon"></i>

This element represents the error of valid icons. When an error is present, the element will have the class name “error-icon“, or if the field is valid, the element will have the “valid-icon“ class name. There is no class name on default state.

The example below shows how to style the error and valid icons:

var component = twoPayClient.components.create('card', {
    '.valid-icon': {
      right: '-25px'
    },
    '.error-icon': {
      right: '-25px'
    }
});

The validation message element <span class="validation-message">

This element displays only whether an error is present for the current field.

Here's how you can customize the validation message element:

var component = twoPayClient.components.create('card', {
    '.validation-message': {
        color       : '#D9534F',
        fontSize    : '10px',
        fontStyle   : 'italic',
        marginTop   : '6px',
        marginBottom: '-5px',
        display     : 'block',
        lineHeight  : '1'
    }
});

The above styling can be applied to all payment form fields with some exceptions:

  • card-icon, card-type-icon – are only available for the card number field;
  • lock-icon – is only available for the card number and CVV fields;
  • you cannot pass any URL references in the style object. The following example will NOT work:
// Non working example
var component = twoPayClient.components.create('card', {
    '.valid-icon': {
        backgroundImage: 'url("https://my-web-site.com/some-valid-image.png")'
    }
});

The Style Object

Default style object

The default style object used, if no other style object has been provided, is the one below:

{
  margin: 0,
  fontFamily: 'Helvetica, sans-serif',
  fontSize: '1rem',
  fontWeight: '400',
  lineHeight: '1.5',
  color: '#212529',
  textAlign: 'left',
  backgroundColor: '#ffffff',
  '*': {
    'boxSizing': 'border-box'
  },
  '.no-gutters': {
    marginRight: 0,
    marginLeft: 0
  },
  '.row': {
    display: 'flex',
    flexWrap: 'wrap'
  },
  '.col': {
    flexBasis: '0',
    flexGrow: '1',
    maxWidth: '100%',
    padding: '0',
    position: 'relative',
    width: '100%'
  },
  'div': {
    display: 'block'
  },
  '.field-container': {
    paddingBottom: '14px'
  },
  '.field-wrapper': {
    paddingRight: '25px'
  },
  '.input-wrapper': {
    position: 'relative'
  },
  label: {
    display: 'inline-block',
    marginBottom: '9px',
    color: '#313131',
    fontSize: '14px',
    fontWeight: '300',
    lineHeight: '17px'
  },
  'input': {
    overflow: 'visible',
    margin: 0,
    fontFamily: 'inherit',
    display: 'block',
    width: '100%',
    height: '42px',
    padding: '10px 12px',
    fontSize: '18px',
    fontWeight: '400',
    lineHeight: '22px',
    color: '#313131',
    backgroundColor: '#fff',
    backgroundClip: 'padding-box',
    border: '1px solid #CBCBCB',
    borderRadius: '3px',
    transition: 'border-color .15s ease-in-out,box-shadow .15s ease-in-out',
    outline: 0
  },
  'input:focus': {
    border: '1px solid #5D5D5D',
    backgroundColor: '#FFFDF2'
  },
  '.is-error input': {
    border: '1px solid #D9534F'
  },
  '.is-error input:focus': {
    backgroundColor: '#D9534F0B'
  },
  '.is-valid input': {
    border: '1px solid #1BB43F'
  },
  '.is-valid input:focus': {
    backgroundColor: '#1BB43F0B'
  },
  '.validation-message': {
    color: '#D9534F',
    fontSize: '10px',
    fontStyle: 'italic',
    marginTop: '6px',
    marginBottom: '-5px',
    display: 'block',
    lineHeight: '1'
  },
  '.card-expiration-date': {
    paddingRight: '.5rem'
  },
  '.is-empty input': {
    color: '#EBEBEB'
  },
  '.lock-icon': {
    top: 'calc(50% - 7px)',
    right: '10px'
  },
  '.valid-icon': {
    top: 'calc(50% - 8px)',
    right: '-25px'
  },
  '.error-icon': {
    top: 'calc(50% - 8px)',
    right: '-25px'
  },
  '.card-icon': {
    top: 'calc(50% - 10px)',
    left: '10px',
    display: 'none'
  },
  '.is-empty .card-icon': {
    display: 'block'
  },
  '.is-focused .card-icon': {
    display: 'none'
  },
  '.card-type-icon': {
    right: '30px',
    display: 'block'
  },
  '.card-type-icon.visa': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.mastercard': {
    top: 'calc(50% - 14.5px)'
  },
  '.card-type-icon.amex': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.discover': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.jcb': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.dankort': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.cartebleue': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.diners': {
    top: 'calc(50% - 14px)'
  },
  '.card-type-icon.elo': {
    top: 'calc(50% - 14px)'
  }
}

Allowed CSS Properties

[
    // orphan properties
    'bottom',
    'clear',
    'clip',
    'color',
    'cursor',
    'direction',
    'display',
    'float',
    'height',
    'left',
    'letterSpacing',
    'opacity',
    'position',
    'right',
    'top',
    'verticalAlign',
    'visibility',
    'width',
    'zIndex',

    // align
    'alignContent',
    'alignItems',
    'alignSelf',

    // background
    'backgroundBlendMode',
    'backgroundClip',
    'backgroundColor',
    'backgroundPosition',
    'backgroundRepeat',
    'backgroundSize',
    'background',

    // border
    'borderBottomColor',
    'borderBottomLeftRadius',
    'borderBottomRightRadius',
    'borderBottomStyle',
    'borderBottomWidth',
    'borderBottom',
    'borderCollapse',
    'borderColor',
    'borderLeftColor',
    'borderLeftStyle',
    'borderLeftWidth',
    'borderLeft',
    'borderRadius',
    'borderRightColor',
    'borderRightStyle',
    'borderRightWidth',
    'borderRight',
    'borderSpacing',
    'borderStyle',
    'borderTopColor',
    'borderTopLeftRadius',
    'borderTopRightRadius',
    'borderTopStyle',
    'borderTopWidth',
    'borderTop',
    'borderWidth',
    'border',

    // box
    'boxDecorationBreak',
    'boxShadow',
    'boxSizing',

    // break
    'breakAfter',
    'breakBefore',
    'breakInside',

    // flex
    'flex',
    'flexBasis',
    'flexDirection',
    'fontFeatureSettings',
    'flexFlow',
    'flexGrow',
    'flexShrink',
    'flexWrap',

    // font
    'fontFamily',
    'fontKerning',
    'fontLanguageOverride',
    'fontSizeAdjust',
    'fontSize',
    'fontStretch',
    'fontStyle',
    'fontSynthesis',
    'fontVariant',
    'fontVariantAlternates',
    'fontVariantCaps',
    'fontVariantEastAsian',
    'fontVariantLigatures',
    'fontVariantNumeric',
    'fontVariantPosition',
    'fontWeight',
    'font',

    // justify
    'justifyContent',
    'justifyItems',
    'justifySelf',

    // line
    'lineBreak',
    'lineHeight',

    // list
    'listStylePosition',
    'listStyleType',
    'listStyle',

    // margin
    'marginBottom',
    'marginLeft',
    'marginRight',
    'marginTop',
    'margin',

    // max
    'maxHeight',
    'maxWidth',

    // min
    'minHeight',
    'minWidth',

    // outline
    'outlineColor',
    'outlineOffset',
    'outlineStyle',
    'outlineWidth',
    'outline',

    // overflow
    'overflow',
    'overflowWrap',
    'overflowX',
    'overflowY',

    // padding
    'paddingBottom',
    'paddingLeft',
    'paddingRight',
    'paddingTop',
    'padding',

    //text
    'textAlign',
    'textAlignLast',
    'textDecoration',
    'textDecorationColor',
    'textDecorationLine',
    'textDecorationSkip',
    'textDecorationStyle',
    'textIndent',
    'textOverflow',
    'textShadow',
    'textTransform',
    'textUnderlinePosition',

    // transform
    'transform',
    'transformOrigin',
    'transformStyle',
    'transition',
    'transitionDelay',
    'transitionDuration',
    'transitionProperty',
    'transitionTimingFunction',

    // word
    'wordBreak',
    'wordSpacing',
    'wordWrap'
]

Allowed CSS Pseudo-classes

 [
    ':hover',
    ':focus',
    ':active',
    ':disabled',
    '::placeholder',
    '::after',
    '::before'
]

Retrieve upgrade options for a subscription

Overview

Use the getProductUpgradeOptions method to retrieve the possible upgrade options for a 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.

subscriptionReference

Required (string)

 

Unique, system-generated subscription identifier.

Response

Parameters Type/Description

Upgrade options

Array of objects

Request

<?php

require ('PATH_TO_AUTH');

$subscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';

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

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

Set an external reference for an upgrade

Overview

Use the setExternalRef method in conjunction with setSubscriptionUpgrade.

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.

ExternalRef

Required (string)

 

External reference you control.

Response

Boolean

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

Request


<?php
$host   = "https://api.2checkout.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 = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.2checkout.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.2checkout.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;
}
$ExternalReference = '9F4154733C';
try {
    $extRef = $client->setExternalRef($sessionID, $ExternalReference);
}
catch (SoapFault $e) {
    echo "extRef: " . $e->getMessage();
    exit;
}
var_dump("extRef", $extRef);

 

Retrieve price based on specific options

Overview

Use getPrice to extract cost information for a product/subscription plan, based on a specific list of options. 

Parameters

Parameters Type/Description

Item

Required (Object)

Details below.

 

Code

Required (string)

 

 

Unique product identifier your control. Max length 256 characters.

 

Quantity

Required (String)

 

 

Number of units.

 

PriceOptions

Optional (Array of objects)

 

 

Array of price option groups.

                   Options Optional (Array of objects)
    Array of pricing options.
                                     Value Optional (String)
    Pricing option code.

Billing details

Optional (Object)

 

Details below. Can be null. 

 

FirstName

Optional (string)

 

 

Shopper name.

 

LastName

Optional (string)

 

 

Shopper surname.

 

CountryCode

Optional (string)

 

 

Shopper country. ISO 3166 two-letter code. Include CountryCode in your request in combination with a null value for Currency, to receive the price in the default currency of the country you set. 

 

State

Optional (string) – Required for US, Brazil and Romania

 

 

The state in the shopper's country. Mandatory when you set the Billing Country to US, Brazil and Romania. Use case insensitive utf8 strings for the full name, or just the two letter code.

 

City

Optional (string)

 

 

Shopper city.

 

Address1

Optional (string)

 

 

Shopper address.

 

Address2

Optional (string)

 

 

Shopper address.

 

Zip

Optional (string)

 

 

ZIP/ Postal code.

 

Email

Optional (string)

 

 

Shopper email address.

 

Phone

Optional (string)

 

 

Shopper phone number. Mandatory when you set Brazil as the Billing Country. Can be NULL.

 

Company

Optional (string)

 

 

Company name. Can be null for end users. When present, you also need to provide the FiscalCode.

 

FiscalCode

Optional (string) – 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).

• Can be NULL for end users.

Currency

Required (string)

 

The currency ISO code for the payment - ISO 4217. Example: “usd.”

CouponCode

Optional (string)

 

Promotion coupon/voucher.

PayType

Optional (string)

 

The payment method:

  • CC (credit/debit card - including local Brazilian cards).
  • ENCRYPTED_PAYMENT_DATA (client-side encryption)
  • PAYPAL
  • PAYPAL_EXPRESS
  • 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.
  • PURCHASEORDER - use for orders with POs.
  • FREE – for 0 value orders for which you’re not requiring customers to provide payment details.

Response

Parameters Type/Description
ItemPrice

Object

Details below.

UnitNetPrice

Float

 

The value per product unit, excluding sales tax/VAT expressed in the payment currency.

UnitGrossPrice

Float

 

Total value per product unit, including sales tax/VAT expressed in the payment currency. UnitGrossPricedoes not reflect any discounts.

UnitVAT

Integer

 

Sales tax/VAT per product unit expressed in the payment currency.

UnitDiscount

Integer

 

Value of the discount per product unit expressed in the payment currency.

UnitNetDiscountedPrice

Float

 

The value per product unit, expressed in the payment currency, excluding sales tax/VAT, from which 2Checkout deducts the unit discount.

UnitGrossDiscountedPrice

Float

 

Total costs shoppers incur per product unit, expressed in the payment currency. This value includes sales tax/VAT, 2Checkout and affiliate commissions, but 2Checkout deducts the value of any discounts.

UnitAffiliateCommission

Integer

 

Value of the affiliate commission per product unit calculated expressed in the payment currency.

 

2Checkout deducts discounts from the costs incurred by shoppers before calculating affiliate commissions.

 

2Checkout does not take into account shipping costs when calculating affiliate commissions.

 

NULL when 2Checkout does not apply an affiliate commission.

VATPercent Integer
  VAT percentage applied to purchase.
HandlingFeeNetPrice Integer
  Handling fee applied to your NET price configuration.
HandlingFeeGrossPrice Integer
  Handling fee applied to your GROSS price configuration.
AffiliateCommission Optional (double)
  Value of the affiliate commission for the order calculated from the NetDiscountedPrice expressed in the payment currency. Or NULL. 2Checkout does not take into account shipping costs when calculating affiliate commissions.
Currency Optional (string)
  The currency ISO code for the payment - ISO 4217. Example: “usd.” Use null as value when you include CountryCode in your request, to receive the price in the default currency of the country you set. 
Discount Optional (double)
  Value of the discounts for an order expressed in the payment currency.
GrossDiscountedPrice Optional (double)
  Total costs shoppers incurexpressed in the payment currencyThis value includes sales tax/VAT, 2Checkout and affiliate commissions, but 2Checkout deducts the value of any discounts.
GrossPrice Optional (double)
  Total order value, including sales tax/VAT expressed in the payment currency. GrossPrice does not reflect any discounts.
NetDiscountedPrice Optional (double)
  The NetPrice order value excluding sales tax/VAT, from which 2Checkout deducts discounts. NetDiscountedPriceis expressed in the payment currency.
NetPrice Optional (double)
  Order value excluding sales tax/VAT expressed in the payment currency.
VAT Optional (double)
  Value of sales tax/VAT expressed in the payment currency.

Request

<?php

require ('PATH_TO_AUTH');

$CartItem = new stdClass();

$CartItem->Code = 'my_subscription_1';
$CartItem->Quantity = 1;
$CartItem->PriceOptions = array();

// $CartItem->Trial = new stdClass();
$CartItem->Trial->Period = 8;
$CartItem->Trial->Price = 0; //

$BillingDetails = NULL;
$Currency = 'USD';
$CouponCode = '123';
$PayType = 'CC';

try {
    $itemPrice = $client->getPrice($sessionID, $CartItem, $BillingDetails, $Currency, $CouponCode, $PayType);
}
catch (SoapFault $e) {
    echo "itemPrice: " . $e->getMessage();
    exit;
}
var_dump("itemPrice", $itemPrice);

 

Add/Import subscriptions without payment data

Overview

This article covers subscription import without credit/debit card information. Use the addSubscription method to import a subscription into the Avangate system.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

Subscription import

Required (Object)

 

Object designed to provide Avangate with all the information to create a subscription.

Response

Parameters Type/Description

SubscriptionReference

String

 

Unique, system-generated subscription identifier.

Request

<?php

require ('PATH_TO_AUTH');

$Product = new stdClass ();
$Product->ProductCode = 'my_subscription_1';
$Product->ProductId = 4639321;
$Product->ProductName = 'Avangate Subscription Imported';
$Product->ProductVersion = 1.0;
$Product->ProductQuantity = 3;
$Product->PriceOptionCodes = array();
$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 = 'Customer';
$EndUser->Language = 'en';
$EndUser->LastName = 'Avangate';
$EndUser->Phone = '1234567890';
$EndUser->State = 'California';
$EndUser->Fax = NULL;
$EndUser->Zip = '90210';
$Subscription = new stdClass();
$Subscription->ExternalSubscriptionReference = '12345678912ImportedSubscription';
$Subscription->SubscriptionCode= NULL;
$Subscription->StartDate = '2013-01-01';
$Subscription->ExpirationDate = '2017-12-30';
$Subscription->Product = $Product;
$Subscription->EndUser = $EndUser;
$Subscription->ExternalCustomerReference = '12354678ExtCustRef';
$Subscription->AdditionalInfo = 'Additional information set on subscription';

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

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

Retrieve an additional field

Overview

Use the getAdditionalField method to extract information about a specific additional field 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.

fieldCode

Required (string)

 

Field identifier. Alpha-numeric chars, underscores and dashes.

Response

Parameters Type/Description

AdditionalField

Array of objects

Request

<?php
 
require ('PATH_TO_AUTH');

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

Single Sign On by customer reference

Overview

Use the getSingleSignOnByCustomer method to create Single Sign-On links into 2Checkout myAccount based on customer references (IDs). Use either the 2Checkout Customer Reference or the External Customer Reference to identify specific customers.

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.

IdCustomer

Required (string)

 

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

CustomerType

Required (string)

 

Possible values:

  • ExternalCustomerReference
  • 2CheckoutCustomerReference

Page

Optional (string)

 

The specific myAccount page where you redirect the customer.

Possible values:

my_subscription - redirect shoppers to the subscription's page of myAccount based on the SubscriptionReference you provide.

my_products - redirects shoppers to the myAccount page designed to list all products purchased from 2Checkout.

https://store.YourCustomDomain.com/m...t/my_products/?

user_data - redirects shoppers to the Personal Information page in myAccount

https://store.YourCustomDomain.com/m...unt/user_data/?

order_lookup - redirects shoppers to the Order Lookup area of myAccount:

https://store.YourCustomDomain.com/m.../order_lookup/

faq - redirects shoppers to the Support page of myAccount

https://secure. YourCustomDomain.com/support/

payment_methods – redirect shoppers to the Payment Methods area of myAccount:

https://store.YourCustomDomain.com/m...yment_methods/

Do not include PAGE in the URL to redirect shoppers to myAccount homepage

https://store.YourCustomDomain.com/myaccount/?

 

Request

Optional (string)

 

Needed for 'my_subscription'

Request[]=code=123D40F123 redirects customers to the page for the subscription with the 123D40F123 SubscriptionReference value.

 

ValidityTime

Optional (int)

 

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

ValidationIp

Optional (string)

 

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

LanguageCode Optional (string)
  ISO 639-1 two-letter code.

Response

Parameter Type/Description

Single sign-on URL

String

 

The string generated is the complete single sign-on URL pointing to 2Checkout myAccount, containing the unique URL. Shoppers using it log into their 2Checkout myAccount automatically.

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.2checkout.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.2checkout.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);
$IdCustomer = '352365983';
$CustomerType = '2CheckoutCustomerReference';
$Page = 'my_license';
$Request = null;
$ValidityTime = 50;
$ValidationIp = null;

$jsonRpcRequest = array (
'method' => 'getSingleSignOnByCustomer',
'params' => array($sessionID, $IdCustomer, $CustomerType, $Page, $Request, $ValidityTime, $ValidationIp),
'id' => $i++,
'jsonrpc' => '2.0');

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

Retrieve configuration by name

Overview

Use the getPricingConfigurationByName method to extract information on a specific pricing configuration you set for a product.

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.

productCode

Required (string)

 

The editable code that you control at product-level, not the unique, system-generated product ID.

pricingConfigurationName

Required (string)

 

The name of the pricing configuration.

schemaType

Required (string)

 

  • FLAT (without Base Price)
  • DYNAMIC (with Base Price)

priceType

Optional (string)

 

Possible values: NET or GROSS

Response

Parameters Type/Description

PricingConfiguration

Object

Request

<?php

require ('PATH_TO_AUTH');

$productCode = 'subscr1';
$pricingConfigurationName = 'EU prices';
$schemaType = 'DYNAMIC';// FLAT or DYNAMIC
$priceType = 'NET'; // or GROSS

try {
    $ProductPricingConfiguration = $client-> getPricingConfigurationByName ($sessionID, $ProductCode, $PricingConfigurationName, $SchemaType, $PriceType);
}

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

var_dump("Pricing Configuration", $ProductPricingConfiguration);


?>

 

Use Credit cards

Overview

Use the placeOrder method to create an order using products defined in your Control Panel and collect the payment using credit card based payment methods.

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.

Requirements

For credit card orders placed using API 5.0, 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:

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.

Response

Parameters Type/Description

Order information

Object

  Object containing order information.

Request

<?php

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->Currency = 'usd';
$Order->Country = 'US';
$Order->Language = 'en';
$Order->CustomerIP = '91.220.121.21';
$Order->ExternalReference = NULL;
$Order->Source = NULL;
$Order->AffiliateId = NULL;
$Order->CustomerReference = NULL;

$Order->Items = array();
$Order->Items[0] = new stdClass();
$Order->Items[0]->Code = 'my_subscription_1';
$Order->Items[0]->Quantity = 1;
$Order->Items[0]->PriceOptions = NULL;
$Order->Items[0]->SKU = NULL;
$Order->Items[0]->Price = NULL;
$Order->Items[0]->CrossSell = NULL;
$Order->Items[0]->Trial = false;
$Order->Items[0]->AdditionalFields = NULL;
$Order->Items[0]->SubscriptionStartDate = NULL; //If empty or null, subscriptions become active when purchase is made.

$Order->BillingDetails = new stdClass();
$Order->BillingDetails->FirstName = 'First';
$Order->BillingDetails->LastName = 'Last';
$Order->BillingDetails->CountryCode = 'us';
$Order->BillingDetails->State = 'California';
$Order->BillingDetails->City = 'LA';
$Order->BillingDetails->Address1 = 'Address example';
$Order->BillingDetails->Address2 = NULL;
$Order->BillingDetails->Zip = '90210';
$Order->BillingDetails->Email = 'email@address.com';
$Order->BillingDetails->Phone = NULL;
$Order->BillingDetails->Company = NULL;
$Order->DeliveryDetails = NULL;

$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'CC';
$Order->PaymentDetails->Currency = 'usd';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '10.10.10.10';
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$Order->PaymentDetails->PaymentMethod->CardNumber = "4111111111111111";
$Order->PaymentDetails->PaymentMethod->CardType = 'visa';
$Order->PaymentDetails->PaymentMethod->ExpirationYear = '2019';
$Order->PaymentDetails->PaymentMethod->ExpirationMonth = '12';
$Order->PaymentDetails->PaymentMethod->CCID = '123';
$Order->PaymentDetails->PaymentMethod->HolderName = 'John';
$Order->PaymentDetails->PaymentMethod->CardNumberTime = 83.21; // can be null - high value in seconds is a red flag for fraud attempts.
$Order->PaymentDetails->PaymentMethod->HolderNameTime = 13.35; // can be null - high value in seconds is a red flag for fraud attempts.
$Order->PaymentDetails->PaymentMethod->Vendor3DSReturnURL = "http://www.success.ro";
$Order->PaymentDetails->PaymentMethod->Vendor3DSCancelURL = "http://www.error.ro"; 



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

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

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