Skip to main content

Set custom CSS styles when generating the card component

Overview

Set up the 2Pay.js payments client to accept payments on your website. To collect payments you need to create a payment form, tokenize sensitive card information, and use that token to create a charge.

See the steps below on how to set a custom CSS when generating the card component.

Use case

1. Create a form with id="payment-form":

<form type="post" id="payment-form">
  <div class="form-group">
    <label for="name" class="label control-label">Name</label>
    <input type="text" id="name" class="field form-control">
  </div>
  <button class="btn btn-primary" type="submit">Generate token</button>
</form>

2. Inside the form, add an element with id="card-element". The form should now look like this:

<form type="post" id="payment-form">
  <div class="form-group">
    <label for="name" class="label control-label">Name</label>
    <input type="text" id="name" class="field form-control">
  </div>

  <div id="card-element">
    <!-- A TCO IFRAME will be inserted here. -->
  </div>

  <button class="btn btn-primary" type="submit">Generate token</button>
</form>

3. Include the 2Pay.js drop-in payments client JavaScript:

<script type="text/javascript" src="https://2pay-js.2checkout.com/v1/2pay.js"></script>

4. Insert the following configuration JavaScript to set the custom CSS when adding the card component, and generate the token request:

window.addEventListener('load', function() {
  // Initialize the JS Payments SDK client.
  let jsPaymentClient = new  TwoPayClient('AVLRNG');

  // Define a custom JSON Style
  let style = {
    margin                 : 0,
    fontFamily             : '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"',
    fontSize               : '1rem',
    fontWeight             : '400',
    lineHeight             : '1.5',
    color                  : '#212529',
    textAlign              : 'left',
    backgroundColor        : 'pink',
    '*'                    : {
      'boxSizing': 'border-box'
    },
    '.no-gutters'          : {
      marginRight: 0,
      marginLeft : 0
    },
    '.row'                 : {
      display : 'flex',
      flexWrap: 'wrap'
    },
    '.col'                 : {
      flexBasis: '0',
      flexGrow : '1',
      maxWidth : '100%',
      padding  : '.5rem 0 .5rem 0',
      position : 'relative',
      width    : '100%'
    },
    'div'                  : {
      display: 'block'
    },
    label                  : {
      display     : 'inline-block',
      marginBottom: '.5rem',
      color       : 'green',
      fontWeight  : '900'
    },
    'input'                : {
      overflow       : 'visible',
      margin         : 0,
      fontFamily     : 'inherit',
      display        : 'block',
      width          : '100%',
      height         : 'calc(1.5em + .75rem + 2px)',
      padding        : '.375rem .75rem',
      fontSize       : '1rem',
      fontWeight     : '400',
      lineHeight     : '1.5',
      color          : 'red',
      backgroundColor: '#eee',
      backgroundClip : 'padding-box',
      border         : '1px solid #ced4da',
      borderRadius   : '.25rem',
      transition     : 'border-color .15s ease-in-out,box-shadow .15s ease-in-out'
    },
    '.card-expiration-date': {
      paddingRight: '.5rem'
    }
  };
  
  // Create the component that will hold the card fields.
  let component = jsPaymentClient.components.create('card', style);
  
  // Mount the card fields component in the desired HTML tag. This is where the iframe will be located.
  component.mount('#card-element');

  // Handle form submission.
  document.getElementById('payment-form').addEventListener('submit', (event) => {
    event.preventDefault();
    
    // Extract the Name field value
    const billingDetails = {
      name: document.querySelector('#name').value
    };

    // Call the generate method using the component as the first parameter
    // and the billing details as the second one
    jsPaymentClient.tokens.generate(component, billingDetails).then((response) => {
      console.log(response.token);
    }).catch((error) => {
      console.error(error);
    });
  });
});

5. Place the order using the generated token. 

Demo

After performing the steps above, your implementation should look like this:

 

 

 

Update a subscription and assign it to another customer

Overview

Move a subscription from under a customer to another customer entity.

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

update_diagram.png

Requirements

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

  • Use 2Checkout customer references or External customer references belonging to the target customer. 2Checkout re-assigns the subscription to the target customer. 
  • Customer references must be valid and associated to the target customer entity under which you move the subscription.

If you provide both the 2Checkout customer reference and External customer reference they need to belong to the same target customer entity.

Parameters

Parameters

Type/Description

sessionID

Required (string)

 

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

Subscription

Required (Object)

 

To only move a subscription from a source customer to a target customer, send only the 2Checkout customer reference or the External customer reference.

Response

Boolean

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

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;
}
$SubscriptionReferenceTest = '0742B179DD';
try {
    $retrievedSubscription = $client->getSubscription($sessionID, $SubscriptionReferenceTest);
}
catch (SoapFault $e) {
    echo "retrievedSubscription: " . $e->getMessage();
    exit;
}
var_dump("retrievedSubscription", $retrievedSubscription);
var_dump ($retrievedSubscription);
$retrievedSubscription->2CheckoutCustomerReference = 172673064;
try {
    $updatedSubscription = $client->updateSubscription($sessionID, $retrievedSubscription);
}
catch (SoapFault $e) {
    echo "updatedSubscription: " . $e->getMessage();
    exit;
}
var_dump("updatedSubscription", $updatedSubscription);

 

Update and Assign a subscription

Overview

Move a subscription from under a customer to another customer entity.

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

update_diagram.png

Requirements

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

  • Use 2Checkout customer references or External customer references belonging to the target customer. 2Checkout re-assigns the subscription to the target customer. 
  • Customer references must be valid and associated with the target customer entity under which you move the subscription.

If you provide both the 2Checkout customer reference and External customer reference they need to belong to the same target customer entity.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

Subscription

Required (Object)

 

To only move a subscription from a source customer to a target customer, send only the 2Checkout customer reference or the External customer reference.

Response

Parameters Type/Description

Boolean

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

Request

<?php

require ('PATH_TO_AUTH');

$SubscriptionReference = 'YOUR_SUBSCRIPTION_REFERENCE';

try {
    $retrievedSubscription = $client->getSubscription($sessionID, $SubscriptionReference);
}
catch (SoapFault $e) {
    echo "retrievedSubscription: " . $e->getMessage();
    exit;
}
var_dump("retrievedSubscription", $retrievedSubscription);
var_dump ($retrievedSubscription);
$retrievedSubscription->AvangateCustomerReference = 172673064;
try {
    $updatedSubscription = $client->updateSubscription($sessionID, $retrievedSubscription);
}
catch (SoapFault $e) {
    echo "updatedSubscription: " . $e->getMessage();
    exit;
}
var_dump("updatedSubscription", $updatedSubscription);

 

One click (1-click) purchase - PayPal

Overview

Avangate supports 1-click purchases for returning customers who paid for their previous orders with PayPal. 

Availability

Select Avangate accounts. Contact Avangate for more details. 

Requirements

  • Shoppers enabled recurring billing (auto-renewal) for their initial purchase with PayPal. 
  • The Avangate risk department needs to have approved the initial order whose reference you're using to place another order. Avangate uses complex fraud detection technology that blocks fraudulent transactions. This process is expected to take a few seconds. The time is usually covered by the action of showing a new offer to shoppers, but we recommend  checking that ApproveStatus is OK. 

Workflow 

Validate previous order references

For 1-click purchase scenarios use the isValidOrderReference method. The initial order must meet the following requirements:

  • Shoppers enabled recurring billing (auto-renewal).
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
  • Its status is either COMPLETE or AUTHRECEIVED
  • The Avangate risk department approved the order. 

Create the order object

  • Populate the BillingDetails object with the same details as the billing info of the initial order. Make sure that at least the email addresses match.
  • Build your PaymentDetails object using the reference of the initial order as a payment method.
$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'PREVIOUS_ORDER';
$Order->PaymentDetails->Currency = 'usd';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '10.10.10.10';
$Order->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$Order->PaymentDetails->PaymentMethod->RefNo = $orderReference;

Place the new order 

Avangate charges returning customers using their payment-on-file information (their PayPal account). 

Cross-sell

If you need to track cross-sells, we recommend using additional fields to mark orders as such. With this particular flow, Avangate considers both the initial and the subsequent order, new purchases. 

Parameters

Response

Request

<?php
echo "<pre>";
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 = "MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php

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

$i = 1; // counter for api calls

// call login
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;

$sessionID = callRPC($jsonRpcRequest, $host);

var_dump($sessionID);

$refNo = '45452071';

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

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

$newOrder = new stdClass();

$newOrder->RefNo = NULL;
$newOrder->Currency = 'usd';
$newOrder->Country = 'US';
$newOrder->Language = 'en';
$newOrder->Items = array();
$newOrder->Items[0] = new stdClass();
$newOrder->Items[0]->Code = 'my_subscription_1';
$newOrder->Items[0]->Quantity = 1; 

$newOrder->BillingDetails = new stdClass();
$newOrder->BillingDetails->FirstName = 'FirstName';
$newOrder->BillingDetails->LastName = 'LastName';
$newOrder->BillingDetails->CountryCode = 'us';
$newOrder->BillingDetails->State = 'California';
$newOrder->BillingDetails->City = 'LA';
$newOrder->BillingDetails->Address1 = 'Address example';
$newOrder->BillingDetails->Zip = '90210';
$newOrder->BillingDetails->Email = 'shopper@avangate.com';

$newOrder->DeliveryDetails = NULL;

$newOrder->PaymentDetails = new stdClass ();
$newOrder->PaymentDetails->Type = 'PREVIOUS_ORDER';
$newOrder->PaymentDetails->Currency = 'usd';
$newOrder->PaymentDetails->PaymentMethod = new stdClass ();
$newOrder->PaymentDetails->CustomerIP = '10.10.10.10';
$newOrder->PaymentDetails->PaymentMethod->RecurringEnabled = true;
$newOrder->PaymentDetails->PaymentMethod->RefNo = $refNo;

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

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

Upgrade options

Array of objects

Request


<?php
 
 
function callRPC($Request, $hostUrl, $Debug = true) {
    $curl = curl_init($hostUrl);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSLVERSION, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
    $RequestString = json_encode($Request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString);
 
 
    if ($Debug) {
        $RequestString;
    }
    $ResponseString = curl_exec($curl);
    if ($Debug) {
        $ResponseString;
    }
 
    if (!empty($ResponseString)) {
        $Response = json_decode($ResponseString);
        if (isset($Response->result)) {
            return $Response->result;
        }
        if (!is_null($Response->error)) {
            var_dump($Request->method, $Response->error);
        }
    } else {
        return null;
    }
}
 
$host = 'https://api.avangate.com/rpc/3.0/';
 
$merchantCode = "YOUR_MERCHANT_CODE";// your account's merchant code available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
$key = "YOUR_SECRET_KEY";// your account's secret key available in the 'System settings' area of the cPanel: https://secure.avangate.com/cpanel/account_settings.php
 
$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');
$hash = hash_hmac('md5', $string, $key);
 
$i = 1; // counter for api calls
// call login
$jsonRpcRequest = new stdClass();
$jsonRpcRequest->jsonrpc = '2.0';
$jsonRpcRequest->method = 'login';
$jsonRpcRequest->params = array($merchantCode, gmdate('Y-m-d H:i:s'), $hash);
$jsonRpcRequest->id = $i++;
 
$sessionID = callRPC($jsonRpcRequest, $host);
 
var_dump($sessionID);
$subscriptionReference = '30E47F8699';

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

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

Add/Import subscriptions with credit/debit data

Overview

Include payment (credit/debit card) information that 2Checkout uses for recurring billing to renew imported subscriptions. Importing subscriptions with payment data is available only to eligible 2Checkout accounts. Contact 2Checkout directly for additional details.

Use the addSubscription method to import a subscription into the 2Checkout system.

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.

Subscription import

Required (Object)

 

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

CardPayment

Optional (Object)

 

Object containing card details.

Response

SubscriptionReference

String

 

Unique, system-generated subscription identifier.

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;
}
$Product = new stdClass ();
$Product->ProductCode = 'my_subscription_1';
$Product->ProductId = 4639321;
$Product->ProductName = '2Checkout 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@2checkout.com';
$EndUser->FirstName = 'Customer';
$EndUser->Language = 'en';
$EndUser->LastName = '2Checkout';
$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';

$PaymentCard = new stdClass ();
$PaymentCard->CardNumber = '4111111111111111' ;
$PaymentCard->CardType = 'VISA';
$PaymentCard->ExpirationYear = '2018';
$PaymentCard->ExpirationMonth = '12';
$PaymentCard->CCID = '123';
$PaymentCard->HolderName = 'John Doe';
$PaymentCard->HolderNameTime = '15';
$PaymentCard->CardNumberTime = '15';
$PaymentCard->AutoRenewal = true;
try {
    $importedSubscriptionWithPayData = $client->addSubscription($sessionID, $Subscription, $PaymentCard);
}
catch (SoapFault $e) {
    echo "importedSubscriptionWithPayData: " . $e->getMessage();
    exit;
}
var_dump("importedSubscriptionWithPayData", $importedSubscriptionWithPayData);

 

Add/Import subscriptions with credit/debit data

Overview

Include payment (credit/debit card) information that 2Checkout uses for recurring billing to renew imported subscriptions. Importing subscriptions with payment data is available only to eligible 2Checkout accounts. Contact 2Checkout directly for additional details.

Use the addSubscription method to import a subscription into the 2Checkout system.

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.

Subscription import

Required (Object)

 

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

CardPayment

Optional (Object)

 

Object containing card details.

Response

SubscriptionReference

String

 

Unique, system-generated subscription identifier.

Request


<?php
$host   = "https://api.2checkout.com";
$client = new SoapClient($host . "/soap/3.0/?wsdl", array(
    'location' => $host . "/soap/3.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;
}
$Product = new stdClass ();
$Product->ProductCode = 'my_subscription_1';
$Product->ProductId = 4639321;
$Product->ProductName = '2Checkout 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@2checkout.com';
$EndUser->FirstName = 'Customer';
$EndUser->Language = 'en';
$EndUser->LastName = '2Checkout';
$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';
$PaymentCard = new stdClass ();
$PaymentCard->CardNumber = '4111111111111111' ;
$PaymentCard->CardType = 'VISA';
$PaymentCard->ExpirationYear = '2018';
$PaymentCard->ExpirationMonth = '12';
$PaymentCard->CCID = '123';
$PaymentCard->HolderName = 'John Doe';
$PaymentCard->HolderNameTime = '15';
$PaymentCard->CardNumberTime = '15';
$PaymentCard->AutoRenewal = true;
try {
    $importedSubscriptionWithPayData = $client->addSubscription($sessionID, $Subscription, $PaymentCard);
}
catch (SoapFault $e) {
    echo "importedSubscriptionWithPayData: " . $e->getMessage();
    exit;
}
var_dump("importedSubscriptionWithPayData", $importedSubscriptionWithPayData);

 

Use PayPal

Overview

Place an order with dynamic product information, and collect the payment using PayPal.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

Order

Required (Object)

 

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

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

Workflow

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

Response

Order information Type/Description
Order Object containing order information.

Request 

<?php

require ('PATH_TO_AUTH');

$Order = new stdClass();
$Order->Currency = "EUR";
$Order->Language = "EN";
$Order->Country = "NL";
$Order->CustomerIP = '91.220.121.21';//"10.10.13.37";
$Order->Source = "sourceAPI.net";
$Order->LocalTime = date('Y-m-d H:i:s');
$Order->CustomerReference = 421820775;
$Order->Items = array();

/**
 * 1st Product
 */
$Order->Items[0] = new stdClass();
$Order->Items[0]->Code = null;
$Order->Items[0]->Quantity = 2;
$Order->Items[0]->PurchaseType = 'PRODUCT';
$Order->Items[0]->Tangible = true; // physical
$Order->Items[0]->IsDynamic = true;

$Order->Items[0]->Price = new stdClass();
$Order->Items[0]->Price->Amount = 100;
$Order->Items[0]->Price->Type = 'CUSTOM';

$Order->Items[0]->Name = 'Dynamic Product 1 '. date("Y-m-d H:i:s");
$Order->Items[0]->Description = 'Description Produs OTF';

$Order->Items[0]->PriceOptions = [];
$priceOption = new stdClass();
$priceOption->Name = 'Name';
$priceOption->Value = 'Value';
$priceOption->Surcharge = 10;
$Order->Items[0]->PriceOptions[] = $priceOption;

$priceOption1 = new stdClass();
$priceOption1->Name = 'Name';
$priceOption1->Value = 'Value123';
$priceOption1->Surcharge = 11;
$Order->Items[0]->PriceOptions[] = $priceOption1;

$priceOption2 = new stdClass();
$priceOption2->Name = 'Name1';
$priceOption2->Value = 'Value1';
$priceOption2->Surcharge = 12;
$Order->Items[0]->PriceOptions[] = $priceOption2;

$Order->Items[0]->RecurringOptions = new stdClass();
$Order->Items[0]->RecurringOptions->CycleLength = 1;
$Order->Items[0]->RecurringOptions->CycleUnit = 'MONTH';
$Order->Items[0]->RecurringOptions->CycleAmount = 1234;
$Order->Items[0]->RecurringOptions->ContractLength = 3;
$Order->Items[0]->RecurringOptions->ContractUnit = 'YEaR';

/**
 * 3rd Product - SHIPPING
 */
$Order->Items[2] = new stdClass();
$Order->Items[2]->Name = 'Shipping Item '. date("Y-m-d H:i:s");
$Order->Items[2]->PurchaseType = 'SHIPPING';
$Order->Items[2]->Quantity = 1;
$Order->Items[2]->Price = new stdClass();
$Order->Items[2]->Price->Amount = 123;
$Order->Items[2]->IsDynamic = true;

/**
 * 4th Product - TAX
 */
$Order->Items[3] = new stdClass();
$Order->Items[3]->Name = 'Tax Item '. date("Y-m-d H:i:s");
$Order->Items[3]->PurchaseType = 'TAX';
$Order->Items[3]->Quantity = 1;
$Order->Items[3]->Price = new stdClass();
$Order->Items[3]->Price->Amount = 456;
$Order->Items[3]->IsDynamic = true;
$Order->Items[3]->RecurringOptions = new stdClass();
$Order->Items[3]->RecurringOptions->CycleLength = 1;
$Order->Items[3]->RecurringOptions->CycleUnit = 'MONTH';
$Order->Items[3]->RecurringOptions->CycleAmount = 10.2;
$Order->Items[3]->RecurringOptions->ContractLength = 3;
$Order->Items[3]->RecurringOptions->ContractUnit = 'YEaR';

/**
 * 5th Product - COUPON
 */
$Order->Items[4] = new stdClass();
$Order->Items[4]->Name = 'Coupon Item '. date("Y-m-d H:i:s");
$Order->Items[4]->PurchaseType = 'COUPON';
$Order->Items[4]->Quantity = 1;
$Order->Items[4]->Price = new stdClass();
$Order->Items[4]->Price->Amount = 234;
$Order->Items[4]->IsDynamic = true;

/**/
$additionalField1 = new stdClass();
$additionalField1->Code = "additional_field_order_1";
$additionalField1->Text = "REST";
$additionalField1->Value = "1";

$additionalField2 = new stdClass();
$additionalField2->Code = "additional_field_order_2";
$additionalField2->Text = "REST";
$additionalField2->Value = "a";

$additionalField3 = new stdClass();
$additionalField3->Code = "additional_field_order_3";
$additionalField3->Text = "REST";
$additionalField3->Value = "a";

$Order->AdditionalFields = array();
$Order->AdditionalFields[0] = $additionalField1;
$Order->AdditionalFields[1] = $additionalField2;
$Order->AdditionalFields[2] = $additionalField3;

$additionalField1 = new stdClass();
$additionalField1->Code = "REST";
$additionalField1->Text = "REST";
$additionalField1->Value = "REST";



$Order->MachineId = 'machineIdTestDan';
$Order->Discount = null;
$Order->ExternalReference = null;

$Order->BillingDetails = new stdClass();
$Order->BillingDetails->Address1 = 'Address 1';
$Order->BillingDetails->Address2 = 'Address 2';
$Order->BillingDetails->City = 'Billing City';
$Order->BillingDetails->State = 'Billing State';
$Order->BillingDetails->CountryCode = 'NL';
$Order->BillingDetails->Phone = US;
$Order->BillingDetails->Email = 'shopper@2checkout.com';
$Order->BillingDetails->FirstName = 'John';
$Order->BillingDetails->LastName = 'Doe';
$Order->BillingDetails->Company = 'Billing Company';
$Order->BillingDetails->Zip = '12345';


/**/
$Order->DeliveryDetails = new stdClass();
$Order->DeliveryDetails->Address1 = 'Address 1';
$Order->DeliveryDetails->Address2 = 'Address 2';
$Order->DeliveryDetails->City = 'Billing City';
$Order->DeliveryDetails->State = 'Billing State';
$Order->DeliveryDetails->CountryCode = 'US';
$Order->DeliveryDetails->Phone = '12345';
$Order->DeliveryDetails->Email = 'customer@email.com';
$Order->DeliveryDetails->FirstName = 'John';
$Order->DeliveryDetails->LastName = 'Doe';
$Order->DeliveryDetails->Zip = 12345;
/**/

$Order->PaymentDetails = new stdClass ();
$Order->PaymentDetails->Type = 'PAYPAL';
$Order->PaymentDetails->Currency = 'eur';
$Order->PaymentDetails->PaymentMethod = new stdClass ();
$Order->PaymentDetails->CustomerIP = '91.220.121.21';
$Order->PaymentDetails->PaymentMethod->ReturnURL = 'http://yourreturnurl.com';
$Order->PaymentDetails->PaymentMethod->Email= 'email@2checkout.com';

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

$APIOrderFullInfo = callRPC((Object)$jsonRpcRequest, $host);

$url = $APIOrderFullInfo->PaymentDetails->PaymentMethod->RedirectURL;

header ("Location: $url");

Retrieve a customer’s subscriptions

Overview

Extract all subscriptions belonging to a customer. Use the getCustomerSubscriptions method to retrieve details about the subscriptions belonging to a specific customer.

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.

2CheckoutCustomerReference

Required (int)

 

System-generated customer reference. Required unless you prefer to use ExternalCustomerReference.

ExternalCustomerReference

Optional (string)

 

External customer reference that you control. Optional when you use 2CheckoutCustomerReference. If you include it, it needs to belong to the same customer as the 2CheckoutCustomerReference.

Response

Subscription

Array of objects

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;
}
$CustomerReference = 260015052;
try {
    $ListofSubscriptions = $client->getCustomerSubscriptions($sessionID, $CustomerReference);
}
catch (SoapFault $e) {
    echo "ListofSubscriptions: " . $e->getMessage();
    exit;
}
var_dump("ListofSubscriptions", $ListofSubscriptions);

 

Assign additional field

Overview

Use the addSubscriptionAdditionalInformationField method to assign an additional information field to a subscription.

Requirements

The maximum number of additional information fields that can be added on a subscription is 5, while the maximum field length is 100 characters.

Parameters

Parameters Type/Description

sessionID

Required (string)

 

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

SubscriptionReference Required (string)
  Unique, system-generated subscription identifier.

fieldName

Required (string)

 

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

fieldValue

Required (string)

 

The value of the additional information field.

Response

Parameters Type/Description
AdditionalSubscriptionInformation Object

 

Contains information related to the additional information field.

fieldName

String

 

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

fieldValue

String

 

The value of the additional information field.

Request

<?php

require('PATH_TO_AUTH');

$subscriptionReference = '351D4F557E';
$fieldName = 'subscription';
$fieldValue = 'test';

$jsonRpcRequest = array (
'method' => 'addSubscriptionAdditionalInformationField',
'params' => array($sessionID, $subscriptionReference, $fieldName, $fieldValue),
'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