Skip to main content

Use PayPal

Last updated: 12-Oct-2020
Rate this article:

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
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
{
  "Country": "us",
  "Currency": "USD",
  "CustomerIP": "91.220.121.21",
  "ExternalReference": "RPC_API_AVANGTE",
  "Language": "en",
  "Source": "testAPI.com",
  "BillingDetails": {
    "Address1": "Test Address",
    "City": "LA",
    "State": "California",
    "CountryCode": "US",
    "Email": "testcustomer@2Checkout.com",
    "FirstName": "Customer",
    "LastName": "2Checkout",
    "Zip": "12345"
  },
  "Items": [
    {
      "Name": "Dynamic product",
      "Description": "Test description",
      "Quantity": 1,
      "IsDynamic": true,
      "Tangible": false,
      "PurchaseType": "PRODUCT",
      "Price": {
        "Amount": 100,
        "Type": "CUSTOM"
      },
      "PriceOptions": [
        {
          "Name": "OPT1",
          "Options": [
            {
              "Name": "Name LR",
              "Value": "Value LR",
              "Surcharge": 7
            }
          ]
        }
      ],
      "RecurringOptions": {
        "CycleLength": 2,
        "CycleUnit": "DAY",
        "CycleAmount": 12.2,
        "ContractLength": 3,
        "ContractUnit": "DAY"
      }
    }
  ],
  "PaymentDetails": {
    "Currency": "USD",
    "CustomerIP": "91.220.121.21",
    "PaymentMethod": {
      "RecurringEnabled": false,
      "ReturnURL": "http://secure.avangate.local/test/index.php",
      "CancelURL": "http://secure.avangate.local/test/create_order.php"
    },
    "Type": "PAYPAL"
  }
}
JSON;


}

class Client
{
    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, $payload, Configuration::ADDITIONAL_OPTIONS];
        }
        $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);

Rate this article:

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