Create an Authorization
Note: This guide assumes you have completed a basic Smart Payment Buttons integration.
On the server
- Set up your server to make calls to PayPal
- Set up your server to receive a call from the client with the order ID
- Call PayPal to create the authorization
- Save the authorization ID to your database
- Handle any errors from the call
- Return a successful response to the client
Note: To install the PayPal JavaScript SDK on your server, see the Set up the Server 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 create the authorization authorization = http.post(PAYPAL_ORDER_API + orderID + '/authorize', { headers: { Accept: `application/json`, Authorization: `Bearer ${ auth.access_token }` } }); // 4. Save the authorization ID to your database if (!authorization.error) { authorizationID = authorization.purchase_units[0] .payments.authorizations[0].id database.saveAuthorizationID(authorizationID); } // 5. Handle any errors from the call if (authorization.error) { return response.send(500); } // 6. Return a successful response to the client response.send(200); }
// 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 the Server 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 create the authorization const request = new checkoutNodeJssdk.orders.OrdersAuthorizeRequest(orderID); request.requestBody({}); try { const authorization = await payPalClient.client().execute(request); // 4. Save the authorization ID to your database const authorizationID = authorization.result.purchase_units[0] .payments.authorizations[0].id // await database.saveAuthorizationID(authorizationID); } catch (err) { // 5. Handle any errors from the call console.error(err); return res.send(500); } // 6. Return a successful response to the client res.send(200); }
<?php namespace Sample\AuthorizeIntentExamples; require __DIR__ . '/vendor/autoload.php'; //1. Import the PayPal SDK client that was created in `Set up the Server SDK`. use Sample\PayPalClient; use PayPalCheckoutSdk\Orders\OrdersAuthorizeRequest; class AuthorizeOrder { // 2. Set up your server to receive a call from the client /** *Use this function to perform authorization on the approved order *Pass a valid, approved order ID as an argument. */ public static function authorizeOrder($orderId, $debug=false) { $request = new OrdersAuthorizeRequest($orderId); $request->body = self::buildRequestBody(); // 3. Call PayPal to authorize an order $client = PayPalClient::client(); $response = $client->execute($request); // 4. Save the authorization ID to your database. Implement logic to save authorization to your database for future reference. if ($debug) { print "Status Code: {$response->statusCode}\n"; print "Status: {$response->result->status}\n"; print "Order ID: {$response->result->id}\n"; print "Authorization ID: {$response->result->purchase_units[0]->payments->authorizations[0]->id}\n"; print "Links:\n"; foreach($response->result->links as $link) { print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n"; } print "Authorization Links:\n"; foreach($response->result->purchase_units[0]->payments->authorizations[0]->links as $link) { print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n"; } // To toggle printing the whole response body comment/uncomment the following line echo json_encode($response->result, JSON_PRETTY_PRINT), "\n"; } return $response; } /** *Setting up request body for authorization. *Refer to API reference for details. */ public static function buildRequestBody() { return "{}"; } } /** *This driver function invokes authorize order. */ if (!count(debug_backtrace())) { AuthorizeOrder::authorizeOrder('REPLACE-WITH-VALID-APPROVED-ORDER-ID', true); } ?>
# 1. Import the PayPal SDK client that was created in `Set up the Server SDK`. from sample import PayPalClient from paypalcheckoutsdk.orders import OrdersAuthorizeRequest import json class AuthorizeOrder(PayPalClient): #2. Set up your server to receive a call from the client """Use this function to authorize an approved order. Pass a valid, authorized order ID as an argument to this function.""" def authorize_order(self, order_id, debug=False): """Method to authorize order using order_id""" request = OrdersAuthorizeRequest(order_id) request.prefer("return=representation") # 3. Call PayPal to authorize an order request.request_body(self.build_request_body()) response = self.client.execute(request) # 4. Save the authorization ID to your database. Implement logic to save authorization to your database for future reference. if debug: print 'Status Code: ', response.status_code print 'Status: ', response.result.status print 'Order ID: ', response.result.id print ('Authorization ID:', response.result.purchase_units[0].payments.authorizations[0].id) print 'Links:' for link in response.result.links: print('\t{}: {}\tCall Type: {}' .format(link.rel, link.href, link.method)) print 'Authorization Links:' for link in response.result.purchase_units[0].payments.authorizations[0].links: print('\t{}: {}\tCall Type: {}' .format(link.rel, link.href, link.method)) print "Buyer:" print ("\tEmail Address: {}\n\tPhone Number: {}" .format(response.result.payer.email_address, response.result.payer.phone.phone_number.national_number)) json_data = self.object_to_json(response.result) print "json_data: ", json.dumps(json_data,indent=4) return response """Sample request body to authorize order. You can update this with the required fields, as needed.""" @staticmethod def build_request_body(): return {} """This driver function invokes the authorize_order function with a valid, approved order ID to authorize the sample order. Replace the Order ID value with a valid, approved order ID""" if __name__ == "__main__": order_id = 'REPLACE-WITH-VALID-APPROVED-ORDER-ID' AuthorizeOrder().authorize_order(order_id, debug=True)
# 1. Import the PayPal SDK client that was created in `Set up the Server SDK`. require_relative '../paypal_client' include PayPalCheckoutSdk::Orders module Samples module AuthorizeIntentExamples class AuthorizeOrder #2. Set up your server to receive a call from the client # Use this function to authorize an approved order. def authorize_order (order_id, debug=false) request = OrdersAuthorizeRequest::new(order_id) request.prefer("return=representation") # You can update this request body with fields as needed. # Refer API docs for more information. request.request_body({}) # 3. Call PayPal to authorize an order response = PayPalClient::client::execute(request) # 4. Save the authorization ID to your database. Implement logic to save authorization your database for future reference. if debug puts "Status Code: #" puts "Status: #" puts "Order ID: #" puts "Authorization ID: #" puts "Intent: #" puts "Links:" for link in response.result.links # This could also be named 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 "Authorization Links:" for link in response.result.purchase_units[0].payments.authorizations[0].links # This could also be named 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 "Buyer:" buyer = response.result.payer puts "\tEmail Address: #\n\tName: # #\n\tPhone Number: #" puts PayPalClient::openstruct_to_hash(response.result).to_json end return response end end end end # This driver function invokes the authorize_order function with # approved order ID. Replace order ID with a valid, approved order ID if __FILE__ == $0 Samples::AuthorizeIntentExamples::AuthorizeOrder::new::authorize_order('REPLACE-WITH-VALID-APPROVED-ORDER-ID',true) end
package com.paypal.AuthorizeIntentExamples; import java.io.IOException; import org.json.JSONObject; import com.braintreepayments.http.HttpResponse; import com.braintreepayments.http.serializer.Json; import com.paypal.PayPalClient; import com.paypal.orders.LinkDescription; import com.paypal.orders.Order; import com.paypal.orders.OrderActionRequest; import com.paypal.orders.OrdersAuthorizeRequest; /* * *1. Import the PayPal SDK client that was created in `Set up the Server SDK`. *This step extends the SDK client. It's not mandatory to extend the client, you can also inject it. */ public class AuthorizeOrder extends PayPalClient { //2. Set up your server to receive a call from the client /** *Method to authorize order after creation * *@param orderId Valid Approved Order ID from createOrder response *@param debug true = print response data *@return HttpResponseOrder response received from API *@throws IOException Exceptions from API if any */ public HttpResponseOrder authorizeOrder(String orderId, boolean debug) throws IOException { OrdersAuthorizeRequest request = new OrdersAuthorizeRequest(orderId); request.requestBody(buildRequestBody()); // 3. Call PayPal to authorization an order HttpResponseOrder response = client().execute(request); // 4. Save the authorization ID to your database. Implement logic to save the authorization to your database for future reference. if (debug) { System.out.println("Authorization Ids:"); response.result().purchaseUnits() .forEach(purchaseUnit -> purchaseUnit.payments() .authorizations().stream() .map(authorization -> authorization.id()) .forEach(System.out::println)); System.out.println("Link Descriptions: "); for (LinkDescription link : response.result().links()) { System.out.println("\t" + link.rel() + ": " + link.href()); } System.out.println("Full response body:"); System.out.println(new JSONObject(new Json().serialize(response.result())).toString(4)); } return response; } /** *Building empty request body. * *@return OrderActionRequest with empty body */ private OrderActionRequest buildRequestBody() { return new OrderActionRequest(); } /** *This driver function invokes the authorizeOrder function to *create an sample order. * *@param args */ public static void main(String[] args) { try { new AuthorizeOrder().authorizeOrder("REPLACE-WITH-VALID-APPROVED-ORDER-ID", true); } catch (Exception e) { e.printStackTrace(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; //1. Import the PayPal SDK client that was created in `Set up the Server SDK`. using Samples; using PayPalCheckoutSdk.Orders; using BraintreeHttp; namespace Samples.AuthorizeIntentExamples { public class AuthorizeOrderSample { //2. Set up your server to receive a call from the client //Use this function to perform authorization on the approved order. public async static TaskHttpResponse AuthorizeOrder(string OrderId, bool debug = false) { var request = new OrdersAuthorizeRequest(OrderId); request.Prefer("return=representation"); request.RequestBody(new OrderActionRequest()); //3. Call PayPal to authorization an order var response = await PayPalClient.client().Execute(request); //4. Save the authorization ID to your database. Implement logic to save the authorization to your database for future reference. if (debug) { var result = response.ResultOrder(); Console.WriteLine("Status: {0}", result.Status); Console.WriteLine("Order Id: {0}", result.Id); Console.WriteLine("Authorization Id: {0}", result.PurchaseUnits[0].Payments.Authorizations[0].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("Buyer:"); Console.WriteLine("\tEmail Address: {0}", result.Payer.EmailAddress); Console.WriteLine("Response JSON: \n {0}", PayPalClient.ObjectToJSONString(result)); } return response; } static void Main(string[] args) { string OrderId = "REPLACE-WITH-VALID-APPROVED-ORDER-ID"; AuthorizeOrder(OrderId, true).Wait(); } } }
For the full list of parameters and example responses, read the Orders Authorize API reference.
Note: Remember to swap the credentials and API URL from sandbox to production when going live with your integration.
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.authorize()
.
onApprove: function(data) {
return fetch('/my-server/authorize-paypal-transaction', {
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Authorization created for ' + details.payer_given_name);
});
}
Now your client and server are set up to call the PayPal Orders API to authorize a future capture from a transaction.