PayPal Checkout

Set Up Server-Side SDK

Use the PayPal REST SDKs to get started quickly with the PayPal REST APIs and complete common actions.

The PayPal REST SDKs are available in Java, PHP, Node, Python, Ruby, and .NET.

SDK benefits

Using an SDK over a direct integration allows the SDK to handle authentication for you. The SDK obtains your OAuth 2.0 access token and automatically reflects any Orders and Payments API updates.

Install the SDK

To begin working with the PayPal REST APIs, install one of the SDKs in your preferred language.

//Create a Node.js project in your directory, then run the following command to install the PayPal JavaScript SDK.
npm install @paypal/checkout-server-sdk
//Create a PHP project in your directory, then run the following command to install the PayPal JavaScript SDK.
composer require paypal/paypal-checkout-sdk 1.0.0
# Create a Python project in your directory, then run the following command to install the PayPal JavaScript SDK.
pip install paypal-checkout-serversdk
# Create a Ruby project in your directory, then run the following command to install the PayPal JavaScript SDK.
gem install paypal-checkout-sdk
//Create a Java Maven or Gradle project in your directory, then add the following dependency to the project from Maven Central.
PAYPAL CHECKOUT SDK:
 groupId: com.paypal.sdk
 artifactId: checkout-sdk
 version: 1.0.0
// Include the following dependencies, which are used as samples only.
JSON:
 groupId: org.json
 artifactId: json
 version: 20180813
APACHE COMMONS LANG:
 groupId: org.apache.commons
 artifactId: commons-lang3
 version: 3.6
//Create a DotNet project in your directory, then run the following command to install the PayPal JavaScript SDK.
dotnet add package PayPalCheckoutSdk --version 1.0.0

Set up the environment

After you install the SDK, make it available to your app and configure your environment. Configuration details include either sandbox for testing or live for production, and your client ID and secret for your app.

Note: Learn how to get your REST API credentials for sandbox and live environments in the developer dashboard.

In the directory where you installed the SDK, create a file in your preferred language. Include this code to make the SDK available and configure your environment with your application credentials.

'use strict';

/**
 *
 * PayPal Node JS SDK dependency
 */
const checkoutNodeJssdk = require('@paypal/checkout-server-sdk');

/**
 *
 * Returns PayPal HTTP client instance with environment that has access
 * credentials context. Use this instance to invoke PayPal APIs, provided the
 * credentials have access.
 */
function client() {
    return new checkoutNodeJssdk.core.PayPalHttpClient(environment());
}

/**
 *
 * Set up and return PayPal JavaScript SDK environment with PayPal access credentials.
 * This sample uses SandboxEnvironment. In production, use LiveEnvironment.
 *
 */
function environment() {
    let clientId = process.env.PAYPAL_CLIENT_ID || 'PAYPAL-SANDBOX-CLIENT-ID';
    let clientSecret = process.env.PAYPAL_CLIENT_SECRET || 'PAYPAL-SANDBOX-CLIENT-SECRET';

    return new checkoutNodeJssdk.core.SandboxEnvironment(
        clientId, clientSecret
    );
}

async function prettyPrint(jsonData, pre=""){
    let pretty = "";
    function capitalize(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
    for (let key in jsonData){
        if (jsonData.hasOwnProperty(key)){
            if (isNaN(key))
              pretty += pre + capitalize(key) + ": ";
            else
              pretty += pre + (parseInt(key) + 1) + ": ";
            if (typeof jsonData[key] === "object"){
                pretty += "\n";
                pretty += await prettyPrint(jsonData[key], pre + "    ");
            }
            else {
                pretty += jsonData[key] + "\n";
            }

        }
    }
    return pretty;
}

module.exports = {client: client, prettyPrint:prettyPrint};

<?php

namespace Sample;

use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;

ini_set('error_reporting', E_ALL); // or error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

class PayPalClient
{
    /**
     * Returns PayPal HTTP client instance with environment that has access
     * credentials context. Use this instance to invoke PayPal APIs, provided the
     * credentials have access.
     */
    public static function client()
    {
        return new PayPalHttpClient(self::environment());
    }

    /**
     * Set up and return PayPal PHP SDK environment with PayPal access credentials.
     * This sample uses SandboxEnvironment. In production, use LiveEnvironment.
     */
    public static function environment()
    {
        $clientId = getenv("CLIENT_ID") ?: "PAYPAL-SANDBOX-CLIENT-ID";
        $clientSecret = getenv("CLIENT_SECRET") ?: "PAYPAL-SANDBOX-CLIENT-SECRET";
        return new SandboxEnvironment($clientId, $clientSecret);
    }
}
from paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment

import sys

class PayPalClient:
    def __init__(self):
        self.client_id = "PAYPAL-SANDBOX-CLIENT-ID"
        self.client_secret = "PAYPAL-SANDBOX-CLIENT-SECRET"

        """Set up and return PayPal Python SDK environment with PayPal access credentials.
           This sample uses SandboxEnvironment. In production, use LiveEnvironment."""

        self.environment = SandboxEnvironment(client_id=self.client_id, client_secret=self.client_secret)

        """ Returns PayPal HTTP client instance with environment that has access
            credentials context. Use this instance to invoke PayPal APIs, provided the
            credentials have access. """
        self.client = PayPalHttpClient(self.environment)

    def object_to_json(self, json_data):
        """
        Function to print all json data in an organized readable manner
        """
        result = {}
        if sys.version_info[0] < 3:
            itr = json_data.__dict__.iteritems()
        else:
            itr = json_data.__dict__.items()
        for key,value in itr:
            # Skip internal attributes.
            if key.startswith("__"):
                continue
            result[key] = self.array_to_json_array(value) if isinstance(value, list) else\
                        self.object_to_json(value) if not self.is_primittive(value) else\
                         value
        return result;
    def array_to_json_array(self, json_array):
        result =[]
        if isinstance(json_array, list):
            for item in json_array:
                result.append(self.object_to_json(item) if  not self.is_primittive(item) \
                              else self.array_to_json_array(item) if isinstance(item, list) else item)
        return result;

    def is_primittive(self, data):
        return isinstance(data, str) or isinstance(data, unicode) or isinstance(data, int)
require 'paypal-checkout-sdk'

module PayPalClient
  class << self

    # Set up and return PayPal Ruby SDK environment with PayPal access credentials.
    # This sample uses SandboxEnvironment. In production, use LiveEnvironment.
    def environment
      client_id = ENV['PAYPAL_CLIENT_ID'] || 'PAYPAL-CLIENT-ID'
      client_secret = ENV['PAYPAL_CLIENT_SECRET'] || 'PAYPAL-CLIENT-SECRET'

      PayPal::SandboxEnvironment.new(client_id, client_secret)
    end

    # Returns PayPal HTTP client instance with environment that has access
    # credentials context. Use this instance to invoke PayPal APIs, provided the
    # credentials have access.
    def client
      PayPal::PayPalHttpClient.new(self.environment)
    end

    # Utility to convert Openstruct Object to JSON hash.
    def openstruct_to_hash(object, hash = {})
      object.each_pair do |key, value|
        hash[key] = value.is_a?(OpenStruct) ? openstruct_to_hash(value) : value.is_a?(Array) ? array_to_hash(value) : value
      end
      hash
    end

    # Utility to convert array of OpenStruct to hash.
    def array_to_hash(array, hash= [])
      array.each do |item|
        x = item.is_a?(OpenStruct) ? openstruct_to_hash(item) : item.is_a?(Array) ? array_to_hash(item) : item
        hash << x
      end
      hash
    end
  end
end
package com.paypal;

import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Iterator;

public class PayPalClient {

  /**
   *Set up the PayPal Java SDK environment with PayPal access credentials.  
   *This sample uses SandboxEnvironment. In production, use LiveEnvironment.
   */
  private PayPalEnvironment environment = new PayPalEnvironment.Sandbox(
    "YOUR APPLICATION CLIENT ID",
    "YOUR APPLICATION CLIENT SECRET");

  /**
   *PayPal HTTP client instance with environment that has access
   *credentials context. Use to invoke PayPal APIs.
   */
  PayPalHttpClient client = new PayPalHttpClient(environment);

  /**
   *Method to get client object
   *
   *@return PayPalHttpClient client
   */
  public PayPalHttpClient client() {
    return this.client;
  }
}
using System;
using PayPalCheckoutSdk.Core;
using BraintreeHttp;

using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;

namespace Samples
{
    public class PayPalClient
    {
        /**
            Set up PayPal environment with sandbox credentials.
            In production, use LiveEnvironment.
         */
        public static PayPalEnvironment environment()
        {
            return new SandboxEnvironment("PAYPAL-SANDBOX-CLIENT-ID","PAYPAL-SANDBOX-CLIENT-SECRET");
        }

        /**
            Returns PayPalHttpClient instance to invoke PayPal APIs.
         */
        public static HttpClient client()
        {
            return new PayPalHttpClient(environment());
        }

        public static HttpClient client(string refreshToken)
        {
            return new PayPalHttpClient(environment(), refreshToken);
        }

        /**
            Use this method to serialize Object to a JSON string.
        */
        public static String ObjectToJSONString(Object serializableObject)
        {
            MemoryStream memoryStream = new MemoryStream();
            var writer = JsonReaderWriterFactory.CreateJsonWriter(
                        memoryStream, Encoding.UTF8, true, true, "  ");
            DataContractJsonSerializer ser = new DataContractJsonSerializer(serializableObject.GetType(), new DataContractJsonSerializerSettings{UseSimpleDictionaryFormat = true});
            ser.WriteObject(writer, serializableObject);
            memoryStream.Position = 0;
            StreamReader sr = new StreamReader(memoryStream);
            return sr.ReadToEnd();
        }
    }
}

HTTP request headers

You might need to modify required and optional HTTP request headers for your integration.

Use the server-side SDKs to pass the headers:

const request = new checkoutNodeJssdk.orders.OrdersCreateRequest();
request.headers["prefer"] = "return=representation";
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
request = OrdersCreateRequest()
request.headers['prefer'] = 'return=representation'
request = OrdersCreateRequest::new
request.headers["prefer"] = "return=representation"
OrdersCreateRequest request = new OrdersCreateRequest();
request.header("prefer","return=representation");
var request = new OrdersCreateRequest();
request.Headers.Add("prefer", "return=representation");

Pass the Partner Attribution ID

The PayPal partner attribution ID Identifies the caller as a PayPal partner. To receive revenue attribution, specify a unique build notation (BN) code. BN codes provide tracking on all transactions that originate or are associated with a particular partner. To learn more or to request a BN code, contact your partner manager or visit the PayPal Partner Portal.

Pass PayPal Partner Attribution ID in the HTTP request header:

const request = new checkoutNodeJssdk.orders.OrdersCreateRequest();
request.headers["PayPal-Partner-Attribution-Id"] = "PARTNER_ID_ASSIGNED_BY_YOUR_PARTNER_MANAGER";
$request = new OrdersCreateRequest();
$request->headers["PayPal-Partner-Attribution-Id"] = "PARTNER_ID_ASSIGNED_BY_YOUR_PARTNER_MANAGER";
request = OrdersCreateRequest()
request.headers['PayPal-Partner-Attribution-Id'] = 'PARTNER_ID_ASSIGNED_BY_YOUR_PARTNER_MANAGER'
request = OrdersCreateRequest::new
request.headers["PayPal-Partner-Attribution-Id"] = "PARTNER_ID_ASSIGNED_BY_YOUR_PARTNER_MANAGER"
OrdersCreateRequest request = new OrdersCreateRequest();
request.header("PayPal-Partner-Attribution-Id","PARTNER_ID_ASSIGNED_BY_YOUR_PARTNER_MANAGER");
var request = new OrdersCreateRequest();
request.Headers.Add("PayPal-Partner-Attribution-Id", "PARTNER_ID_ASSIGNED_BY_YOUR_PARTNER_MANAGER");

Additional information