PayPal Checkout

Get Transaction Details

Note: This guide assumes you have completed a basic Smart Payment Buttons integration.

On the server

Use this fully-annotated code sample to:

  1. Set up your server to make calls to PayPal
  2. Set up your server to receive a call from the client with the order ID
  3. Call PayPal to get the transaction details
  4. Handle any errors from the call
  5. Validate the transaction details are as expected
  6. Save the transaction in your database
  7. Return a successful response to the client

Note: To install the PayPal SDK on your server, see the Set up Server-Side SDK guide. If you are calling the API directly, you do not need to install the SDK.

// Note: This code is intended as a *pseudocode* example. Each server platform and programming language has a different way of handling requests, making HTTP API calls, and serving responses to the browser.

// 1. Set up your server to make calls to PayPal

// 1a. Add your client ID and secret
PAYPAL_CLIENT = 'PAYPAL_SANDBOX_CLIENT';
PAYPAL_SECRET = 'PAYPAL_SANDBOX_SECRET';

// 1b. Point your server to the PayPal API
PAYPAL_OAUTH_API = 'https://api.sandbox.paypal.com/v1/oauth2/token/';
PAYPAL_ORDER_API = 'https://api.sandbox.paypal.com/v2/checkout/orders/';

// 1c. Get an access token from the PayPal API
basicAuth = base64encode(`${ PAYPAL_CLIENT }:${ PAYPAL_SECRET }`);
auth = http.post(PAYPAL_OAUTH_API {
  headers: {
    Accept:        `application/json`,
    Authorization: `Basic ${ basicAuth }`
  },
  data: `grant_type=client_credentials`
});

// 2. Set up your server to receive a call from the client
function handleRequest(request, response) {

  // 2a. Get the order ID from the request body
  orderID = request.body.orderID;

  // 3. Call PayPal to get the transaction details
  details = http.get(PAYPAL_ORDER_API + orderID, {
    headers: {
      Accept:        `application/json`,
      Authorization: `Bearer ${ auth.access_token }`
    }
  });

  // 4. Handle any errors from the call
  if (details.error) {
    return response.send(500);
  }

  // 5. Validate the transaction details are as expected
  if (details.purchase_units[0].amount.value !== '5.77') {
    return response.send(400);
  }

  // 6. Save the transaction in your database
  database.saveTransaction(orderID);

  // 7. Return a successful response to the client
  return response.send(200);
}
curl -v -X GET https://api.sandbox.paypal.com/v2/checkout/orders/5O190127TN364715T \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Access-Token"
// 1. Set up your server to make calls to PayPal

// 1a. Import the SDK package
const checkoutNodeJssdk = require('@paypal/checkout-server-sdk');

// 1b. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
/**
 *
 * PayPal HTTP client dependency
 */
const payPalClient = require('../Common/payPalClient');

// 2. Set up your server to receive a call from the client
module.exports = async function handleRequest(req, res) {

  // 2a. Get the order ID from the request body
  const orderID = req.body.orderID;

  // 3. Call PayPal to get the transaction details
  let request = new checkoutNodeJssdk.orders.OrdersGetRequest(orderID);

  let order;
  try {
    order = await payPalClient.client().execute(request);
  } catch (err) {

    // 4. Handle any errors from the call
    console.error(err);
    return res.send(500);
  }

  // 5. Validate the transaction details are as expected
  if (order.result.purchase_units[0].amount.value !== '220.00') {
    return res.send(400);
  }

  // 6. Save the transaction in your database
  // await database.saveTransaction(orderID);

  // 7. Return a successful response to the client
  return res.send(200);
}
<?php

namespace Sample;

require __DIR__ . '/vendor/autoload.php';
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;

class GetOrder
{

  // 2. Set up your server to receive a call from the client
  /**
   *You can use this function to retrieve an order by passing order ID as an argument.
   */
  public static function getOrder($orderId)
  {

    // 3. Call PayPal to get the transaction details
    $client = PayPalClient::client();
    $response = $client->execute(new OrdersGetRequest($orderId));
    /**
     *Enable the following line to print complete response as JSON.
     */
    //print json_encode($response->result);
    print "Status Code: {$response->statusCode}\n";
    print "Status: {$response->result->status}\n";
    print "Order ID: {$response->result->id}\n";
    print "Intent: {$response->result->intent}\n";
    print "Links:\n";
    foreach($response->result->links as $link)
    {
      print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
    }
    // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";

    // To print the whole response body, uncomment the following line
    // echo json_encode($response->result, JSON_PRETTY_PRINT);
  }
}

/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create a new order
 *and then uses the newly-created order ID with GetOrder.
 */
if (!count(debug_backtrace()))
{
  GetOrder::getOrder('REPLACE-WITH-ORDER-ID', true);
}
?>
# 1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
from sample import PayPalClient
from paypalcheckoutsdk.orders import OrdersGetRequest

class GetOrder(PayPalClient):

  #2. Set up your server to receive a call from the client
  """You can use this function to retrieve an order by passing order ID as an argument"""   
  def get_order(self, order_id):
    """Method to get order"""
    request = OrdersGetRequest(order_id)
    #3. Call PayPal to get the transaction
    response = self.client.execute(request)
    #4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print 'Status Code: ', response.status_code
    print 'Status: ', response.result.status
    print 'Order ID: ', response.result.id
    print 'Intent: ', response.result.intent
    print 'Links:'
    for link in response.result.links:
      print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href, link.method))
    print 'Gross Amount: {} {}'.format(response.result.purchase_units[0].amount.currency_code,
                       response.result.purchase_units[0].amount.value)

"""This driver function invokes the get_order function with
   order ID to retrieve sample order details. """
if __name__ == '__main__':
  GetOrder().get_order('REPLACE-WITH-VALID-ORDER-ID')
# 1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
require_relative '../paypal_client'
require 'json'
require 'ostruct'

include PayPalCheckoutSdk::Orders

module Samples
  class GetOrder

  #2. Set up your server to receive a call from the client
  # You can use this function to retrieve an order by passing order ID as an argument
  def get_order(order_id)
    request = OrdersGetRequest::new(order_id)
    #3. Call PayPal to get the transaction
    response = PayPalClient::client::execute(request)
    #4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    puts "Status Code: " + response.status_code.to_s
    puts "Status: " + response.result.status
    puts "Order ID: " + response.result.id
    puts "Intent: " + response.result.intent
    puts "Links:"
    for link in response.result.links
    # You could also call this link.rel or link.href, but method is a reserved keyword for RUBY. Avoid calling link.method.
    puts "\t#{link["rel"]}: #{link["href"]}\tCall Type: #{link["method"]}"
    end
    puts "Gross Amount: " + response.result.purchase_units[0].amount.currency_code + response.result.purchase_units[0].amount.value
  end
  end
end

# This driver function invokes the get_order function
# with order ID to retrieve sample order details.
if __FILE__ == $0
   Samples::GetOrder::new::get_order('REPLACE-WITH-VALID-ORDER-ID')
end
package com.paypal;

import java.io.IOException;

import org.json.JSONObject;

import com.braintreepayments.http.HttpResponse;
import com.braintreepayments.http.serializer.Json;
import com.paypal.orders.Order;
import com.paypal.orders.OrdersGetRequest;

/*
*
*1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
*This step extends the SDK client.  It's not mandatory to extend the client, you can also inject it.
*/
public class GetOrder extends PayPalClient {

  //2. Set up your server to receive a call from the client
  /**
   *Method to perform sample GET on an order
   *
   *@throws IOException Exceptions from the API, if any
   */
  public void getOrder(String orderId) throws IOException {
    OrdersGetRequest request = new OrdersGetRequest(orderId);
    //3. Call PayPal to get the transaction
    HttpResponse<Order> response = client().execute(request);
    //4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    System.out.println("Full response body:");
    System.out.println(new JSONObject(new Json().serialize(response.result())).toString(4));
  }

  /**
   *This driver method invokes the getOrder function with
   *order ID to retrieve order details.
   *
   *To get the correct order ID, this sample uses createOrder to create
   *a new order and then uses the newly-created order ID as a
   *parameter to getOrder.
   *
   *@param args
   *@throws IOException
   */
  public static void main(String[] args) throws IOException {
    new GetOrder().getOrder("REPLACE-WITH-VALID-ORDER-ID");
  }
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
using BraintreeHttp;
using PayPalCheckoutSdk.Core;
using PayPalCheckoutSdk.Orders;

namespace Samples
{
  public class GetOrderSample
  {

    //2. Set up your server to receive a call from the client
    /*
      You can use this method to retrieve an order by passing the order ID.
     */
    public async static Task<HttpResponse> GetOrder(string orderId, bool debug = false)
    {
      OrdersGetRequest request = new OrdersGetRequest(orderId);
      //3. Call PayPal to get the transaction
      var response = await PayPalClient.client().Execute(request);
      //4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
      var result = response.Result<Order>();
      Console.WriteLine("Retrieved Order Status");
      Console.WriteLine("Status: {0}", result.Status);
      Console.WriteLine("Order Id: {0}", result.Id);
      Console.WriteLine("Intent: {0}", result.Intent);
      Console.WriteLine("Links:");
      foreach (LinkDescription link in result.Links)
      {
        Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
      }
      AmountWithBreakdown amount = result.PurchaseUnits[0].Amount;
      Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);

      return response;
    }

    /*
      This driver method invokes the getOrder function with
      order ID to retrieve order details.

      To get the correct order ID, this sample uses createOrder to create
      a new order and then uses the newly-created order ID with GetOrder.
     */
    static void Main(string[] args)
    {
      GetOrder("REPLACE-WITH-VALID-ORDER-ID").Wait();
    }
  }
}

For the full list of keys you can retrieve from /v2/checkout/orders/, see the Orders Get API reference.

On the client

Next, change the onApprove function on your client. This function should call your server with the order ID, and no longer call actions.order.get().

onApprove: function(data) {
  return fetch('/my-server/get-paypal-transaction', {
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      orderID: data.orderID
    })
  }).then(function(res) {
    return res.json();
  }).then(function(details) {
    alert('Transaction approved by ' + details.payer_given_name);

}

Now your client and server are set up to call the PayPal Orders API to get transaction details.

Feedback