Set up a Transaction
Note: This guide assumes you have completed a basic Smart Payment Buttons integration.
On the server
This code:
- Sets up your server to make calls to PayPal.
- Sets up your server to receive a call from the client.
- Calls PayPal to create an order.
- Handles any errors from the call.
- Returns a successful response to the client with the order ID.
// Note: This is example code. 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 APIs 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) { // 3. Call PayPal to set up a transaction order = http.post(PAYPAL_ORDER_API, { headers: { Accept: `application/json`, Authorization: `Bearer ${ auth.access_token }` }, data: { intent: 'CAPTURE', purchase_units: [{ amount: { currency_code: 'USD', value: '220.00' } }] } }); // 4. Handle any errors from the call if (order.error) { console.error(order.error); return response.send(500); } // 5. Return a successful response to the client with the order ID response.send(200, { orderID: order.id }); }
curl -v -X POST https://api.sandbox.paypal.com/v2/checkout/orders \ -H "Content-Type: application/json" \ -H "Authorization: Bearer Access-Token" \ -d '{ "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "USD", "value": "100.00" } } ] }'
// 1. Set up your server to make calls to PayPal // 1a. Import the SDK package const paypal = 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) { // 3. Call PayPal to set up a transaction const request = new paypal.orders.OrdersCreateRequest(); request.prefer("return=representation"); request.requestBody({ intent: 'CAPTURE', purchase_units: [{ amount: { currency_code: 'USD', value: '220.00' } }] }); 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. Return a successful response to the client with the order ID res.status(200).json({ orderID: order.result.id }); }
<?php namespace Sample\CaptureIntentExamples; 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\OrdersCreateRequest; class CreateOrder { // 2. Set up your server to receive a call from the client /** *This is the sample function to create an order. It uses the *JSON body returned by buildRequestBody() to create an order. */ public static function createOrder($debug=false) { $request = new OrdersCreateRequest(); $request->prefer('return=representation'); $request->body = self::buildRequestBody(); // 3. Call PayPal to set up a transaction $client = PayPalClient::client(); $response = $client->execute($request); if ($debug) { 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"; } // To print the whole response body, uncomment the following line // echo json_encode($response->result, JSON_PRETTY_PRINT); } // 4. Return a successful response to the client. return $response; } /** * Setting up the JSON request body for creating the order with minimum request body. The intent in the * request body should be "AUTHORIZE" for authorize intent flow. * */ private static function buildRequestBody() { return array( 'intent' => 'CAPTURE', 'application_context' => array( 'return_url' => 'https://example.com/return', 'cancel_url' => 'https://example.com/cancel' ), 'purchase_units' => array( 0 => array( 'amount' => array( 'currency_code' => 'USD', 'value' => '220.00' ) ) ) ); } } /** *This is the driver function that invokes the createOrder function to create *a sample order. */ if (!count(debug_backtrace())) { CreateOrder::createOrder(true); } ?>
# 1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`. from sample import PayPalClient from paypalcheckoutsdk.orders import OrdersCreateRequest class CreateOrder(PayPalClient): #2. Set up your server to receive a call from the client """ This is the sample function to create an order. It uses the JSON body returned by buildRequestBody() to create an order.""" def create_order(self, debug=False): request = OrdersCreateRequest() request.prefer('return=representation') #3. Call PayPal to set up a transaction request.request_body(self.build_request_body()) response = self.client.execute(request) if debug: 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 'Total Amount: {} {}'.format(response.result.purchase_units[0].amount.currency_code, response.result.purchase_units[0].amount.value) return response """Setting up the JSON request body for creating the order. Set the intent in the request body to "CAPTURE" for capture intent flow.""" @staticmethod def build_request_body(): """Method to create body with CAPTURE intent""" return \ { "intent": "CAPTURE", "application_context": { "brand_name": "EXAMPLE INC", "landing_page": "BILLING", "shipping_preference": "SET_PROVIDED_ADDRESS", "user_action": "CONTINUE" }, "purchase_units": [ { "reference_id": "PUHF", "description": "Sporting Goods", "custom_id": "CUST-HighFashions", "soft_descriptor": "HighFashions", "amount": { "currency_code": "USD", "value": "230.00", "breakdown": { "item_total": { "currency_code": "USD", "value": "180.00" }, "shipping": { "currency_code": "USD", "value": "30.00" }, "handling": { "currency_code": "USD", "value": "10.00" }, "tax_total": { "currency_code": "USD", "value": "20.00" }, "shipping_discount": { "currency_code": "USD", "value": "10" } } }, "items": [ { "name": "T-Shirt", "description": "Green XL", "sku": "sku01", "unit_amount": { "currency_code": "USD", "value": "90.00" }, "tax": { "currency_code": "USD", "value": "10.00" }, "quantity": "1", "category": "PHYSICAL_GOODS" }, { "name": "Shoes", "description": "Running, Size 10.5", "sku": "sku02", "unit_amount": { "currency_code": "USD", "value": "45.00" }, "tax": { "currency_code": "USD", "value": "5.00" }, "quantity": "2", "category": "PHYSICAL_GOODS" } ], "shipping": { "method": "United States Postal Service", "address": { "name": { "full_name":"John", "surname":"Doe" }, "address_line_1": "123 Townsend St", "address_line_2": "Floor 6", "admin_area_2": "San Francisco", "admin_area_1": "CA", "postal_code": "94107", "country_code": "US" } } } ] } """This is the driver function that invokes the createOrder function to create a sample order.""" if __name__ == "__main__": CreateOrder().create_order(debug=True)
# 1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`. require_relative '../paypal_client' include PayPalCheckoutSdk::Orders module Samples module CaptureIntentExamples class CreateOrder #2. Set up your server to receive a call from the client # This is the sample function to create an order. It uses the # sample JSON body to create an order. # Set the intent in the request body to "CAPTURE" for capture intent flow. def create_order (debug=false) body = { intent: 'CAPTURE', application_context: { brand_name: 'EXAMPLE INC', landing_page: 'BILLING', shipping_preference: 'SET_PROVIDED_ADDRESS', user_action: 'CONTINUE' }, purchase_units: [ { reference_id: 'PUHF', description: 'Sporting Goods', custom_id: 'CUST-HighFashions', soft_descriptor: 'HighFashions', amount: { currency_code: 'USD', value: '230.00', breakdown: { item_total: { currency_code: 'USD', value: '180.00' }, shipping: { currency_code: 'USD', value: '30.00' }, handling: { currency_code: 'USD', value: '10.00' }, tax_total: { currency_code: 'USD', value: '20.00' }, shipping_discount: { currency_code: 'USD', value: '10' } } }, items: [ { name: 'T-Shirt', description: 'Green XL', sku: 'sku01', unit_amount: { currency_code: 'USD', value: '90.00' }, tax: { currency_code: 'USD', value: '10.00' }, quantity: '1', category: 'PHYSICAL_GOODS' }, { name: 'Shoes', description: 'Running, Size 10.5', sku: 'sku02', unit_amount: { currency_code: 'USD', value: '45.00' }, tax: { currency_code: 'USD', value: '5.00' }, quantity: '2', category: 'PHYSICAL_GOODS' } ], shipping: { method: 'United States Postal Service', address: { name: { full_name: 'John', surname: 'Doe' }, address_line_1: '123 Townsend St', address_line_2: 'Floor 6', admin_area_2: 'San Francisco', admin_area_1: 'CA', postal_code: '94107', country_code: 'US' } } } ] } request = OrdersCreateRequest::new request.prefer("return=representation") request.request_body(body) #3. Call PayPal to set up a transaction response = PayPalClient::client.execute(request) if debug 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 # This could also be named link.rel or link.href, but method is a reserved keyword for Ruby. Avoid using 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 return response end end end end # This driver function invokes the createOrder function to create a sample order. if __FILE__ == $0 Samples::CaptureIntentExamples::CreateOrder::new::create_order(true) end
package com.paypal.CaptureIntentExamples; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.braintreepayments.http.HttpResponse; import com.paypal.PayPalClient; import com.paypal.orders.AddressPortable; import com.paypal.orders.AmountBreakdown; import com.paypal.orders.AmountWithBreakdown; import com.paypal.orders.ApplicationContext; import com.paypal.orders.Item; import com.paypal.orders.LinkDescription; import com.paypal.orders.Money; import com.paypal.orders.Name; import com.paypal.orders.Order; import com.paypal.orders.OrderRequest; import com.paypal.orders.OrdersCreateRequest; import com.paypal.orders.PurchaseUnitRequest; import com.paypal.orders.ShippingDetails; /* * *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 CreateOrder extends PayPalClient { //2. Set up your server to receive a call from the client /** *Method to create order * *@param debug true = print response data *@return HttpResponse<Order> response received from API *@throws IOException Exceptions from API if any */ public HttpResponse<Order> createOrder(boolean debug) throws IOException { OrdersCreateRequest request = new OrdersCreateRequest(); request.prefer("return=representation"); request.requestBody(buildRequestBody()); //3. Call PayPal to set up a transaction HttpResponse<Order> response = client().execute(request); if (debug) { if (response.statusCode() == 201) { System.out.println("Status Code: " + response.statusCode()); System.out.println("Status: " + response.result().status()); System.out.println("Order ID: " + response.result().id()); System.out.println("Intent: " + response.result().intent()); System.out.println("Links: "); for (LinkDescription link : response.result().links()) { System.out.println("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method()); } System.out.println("Total Amount: " + response.result().purchaseUnits().get(0).amount().currencyCode() + " " + response.result().purchaseUnits().get(0).amount().value()); } } return response; } /** *Method to generate sample create order body with CAPTURE intent * *@return OrderRequest with created order request */ private OrderRequest buildRequestBody() { OrderRequest orderRequest = new OrderRequest(); orderRequest.intent("CAPTURE"); ApplicationContext applicationContext = new ApplicationContext().brandName("EXAMPLE INC").landingPage("BILLING") .shippingPreference("SET_PROVIDED_ADDRESS"); orderRequest.applicationContext(applicationContext); List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<PurchaseUnitRequest>(); PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest().referenceId("PUHF") .description("Sporting Goods").customId("CUST-HighFashions").softDescriptor("HighFashions") .amount(new AmountWithBreakdown().currencyCode("USD").value("230.00") .breakdown(new AmountBreakdown().itemTotal(new Money().currencyCode("USD").value("180.00")) .shipping(new Money().currencyCode("USD").value("30.00")) .handling(new Money().currencyCode("USD").value("10.00")) .taxTotal(new Money().currencyCode("USD").value("20.00")) .shippingDiscount(new Money().currencyCode("USD").value("10.00")))) .items(new ArrayList<Item>() { { add(new Item().name("T-shirt").description("Green XL").sku("sku01") .unitAmount(new Money().currencyCode("USD").value("90.00")) .tax(new Money().currencyCode("USD").value("10.00")).quantity("1") .category("PHYSICAL_GOODS")); add(new Item().name("Shoes").description("Running, Size 10.5").sku("sku02") .unitAmount(new Money().currencyCode("USD").value("45.00")) .tax(new Money().currencyCode("USD").value("5.00")).quantity("2") .category("PHYSICAL_GOODS")); } }) .shipping(new ShippingDetails().name(new Name().fullName("John Doe")) .addressPortable(new AddressPortable().addressLine1("123 Townsend St").addressLine2("Floor 6") .adminArea2("San Francisco").adminArea1("CA").postalCode("94107").countryCode("US"))); purchaseUnitRequests.add(purchaseUnitRequest); orderRequest.purchaseUnits(purchaseUnitRequests); return orderRequest; } /** *This driver function invokes the createOrder function to create *a sample order. */ public static void main(String args[]) { try { new CreateOrder().createOrder(true); } catch (com.braintreepayments.http.exceptions.HttpException e) { System.out.println(e.getLocalizedMessage()); } 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 Server-Side SDK`. using PayPalCheckoutSdk.Core; using PayPalCheckoutSdk.Orders; using BraintreeHttp; namespace Samples.CaptureIntentExamples { public class CreateOrderSample { //2. Set up your server to receive a call from the client /* Method to create order @param debug true = print response data @return HttpResponse<Order> response received from API @throws IOException Exceptions from API if any */ public async static Task<HttpResponse> CreateOrder(bool debug = false) { var request = new OrdersCreateRequest(); request.Prefer("return=representation"); request.RequestBody(BuildRequestBody()); //3. Call PayPal to set up a transaction var response = await PayPalClient.client().Execute(request); if (debug) { var result = response.Result<Order>(); 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; } /* Method to generate sample create order body with CAPTURE intent @return OrderRequest with created order request */ private static OrderRequest BuildRequestBody() { OrderRequest orderRequest = new OrderRequest() { Intent = "CAPTURE", ApplicationContext = new ApplicationContext { BrandName = "EXAMPLE INC", LandingPage = "BILLING", UserAction = "CONTINUE", ShippingPreference = "SET_PROVIDED_ADDRESS" }, PurchaseUnits = new List<PurchaseUnitRequest> { new PurchaseUnitRequest{ ReferenceId = "PUHF", Description = "Sporting Goods", CustomId = "CUST-HighFashions", SoftDescriptor = "HighFashions", Amount = new AmountWithBreakdown { CurrencyCode = "USD", Value = "230.00", Breakdown = new AmountBreakdown { ItemTotal = new Money { CurrencyCode = "USD", Value = "180.00" }, Shipping = new Money { CurrencyCode = "USD", Value = "30.00" }, Handling = new Money { CurrencyCode = "USD", Value = "10.00" }, TaxTotal = new Money { CurrencyCode = "USD", Value = "20.00" }, ShippingDiscount = new Money { CurrencyCode = "USD", Value = "10.00" } } }, Items = new List<Item> { new Item { Name = "T-shirt", Description = "Green XL", Sku = "sku01", UnitAmount = new Money { CurrencyCode = "USD", Value = "90.00" }, Tax = new Money { CurrencyCode = "USD", Value = "10.00" }, Quantity = "1", Category = "PHYSICAL_GOODS" }, new Item { Name = "Shoes", Description = "Running, Size 10.5", Sku = "sku02", UnitAmount = new Money { CurrencyCode = "USD", Value = "45.00" }, Tax = new Money { CurrencyCode = "USD", Value = "5.00" }, Quantity = "2", Category = "PHYSICAL_GOODS" } }, Shipping = new ShippingDetails { Name = new Name { FullName = "John Doe" }, AddressPortable = new AddressPortable { AddressLine1 = "123 Townsend St", AddressLine2 = "Floor 6", AdminArea2 = "San Francisco", AdminArea1 = "CA", PostalCode = "94107", CountryCode = "US" } } } } }; return orderRequest; } /* This is the driver function that invokes the createOrder function to create a sample order. */ static void Main(string[] args) { CreateOrder(true).Wait(); } } }
Full parameters
{ "intent": "CAPTURE", "application_context": { "return_url": "https://example.com", "cancel_url": "https://example.com", "brand_name": "EXAMPLE INC", "locale": "en-US", "landing_page": "BILLING", "shipping_preference": "SET_PROVIDED_ADDRESS", "user_action": "CONTINUE" }, "purchase_units": [ { "reference_id": "PUHF", "description": "Sporting Goods", "custom_id": "CUST-HighFashions", "soft_descriptor": "HighFashions", "amount": { "currency_code": "USD", "value": "230.00", "breakdown": { "item_total": { "currency_code": "USD", "value": "180.00" }, "shipping": { "currency_code": "USD", "value": "30.00" }, "handling": { "currency_code": "USD", "value": "10.00" }, "tax_total": { "currency_code": "USD", "value": "20.00" }, "shipping_discount": { "currency_code": "USD", "value": "10" } } }, "items": [ { "name": "T-Shirt", "description": "Green XL", "sku": "sku01", "unit_amount": { "currency_code": "USD", "value": "90.00" }, "tax": { "currency_code": "USD", "value": "10.00" }, "quantity": "1", "category": "PHYSICAL_GOODS" }, { "name": "Shoes", "description": "Running, Size 10.5", "sku": "sku02", "unit_amount": { "currency_code": "USD", "value": "45.00" }, "tax": { "currency_code": "USD", "value": "5.00" }, "quantity": "2", "category": "PHYSICAL_GOODS" } ], "shipping": { "method": "United States Postal Service", "address": { "name": { "full_name":"John", "surname":"Doe" }, "address_line_1": "123 Townsend St", "address_line_2": "Floor 6", "admin_area_2": "San Francisco", "admin_area_1": "CA", "postal_code": "94107", "country_code": "US" } } } ] }
return { "intent": "CAPTURE", "application_context": { "return_url": "https://example.com", "cancel_url": "https://example.com", "brand_name": "EXAMPLE INC", "locale": "en-US", "landing_page": "BILLING", "shipping_preference": "SET_PROVIDED_ADDRESS", "user_action": "CONTINUE" }, "purchase_units": [ { "reference_id": "PUHF", "description": "Sporting Goods", "custom_id": "CUST-HighFashions", "soft_descriptor": "HighFashions", "amount": { "currency_code": "USD", "value": "230.00", "breakdown": { "item_total": { "currency_code": "USD", "value": "180.00" }, "shipping": { "currency_code": "USD", "value": "30.00" }, "handling": { "currency_code": "USD", "value": "10.00" }, "tax_total": { "currency_code": "USD", "value": "20.00" }, "shipping_discount": { "currency_code": "USD", "value": "10" } } }, "items": [ { "name": "T-Shirt", "description": "Green XL", "sku": "sku01", "unit_amount": { "currency_code": "USD", "value": "90.00" }, "tax": { "currency_code": "USD", "value": "10.00" }, "quantity": "1", "category": "PHYSICAL_GOODS" }, { "name": "Shoes", "description": "Running, Size 10.5", "sku": "sku02", "unit_amount": { "currency_code": "USD", "value": "45.00" }, "tax": { "currency_code": "USD", "value": "5.00" }, "quantity": "2", "category": "PHYSICAL_GOODS" } ], "shipping": { "method": "United States Postal Service", "address": { "name": { "full_name":"John", "surname":"Doe" }, "address_line_1": "123 Townsend St", "address_line_2": "Floor 6", "admin_area_2": "San Francisco", "admin_area_1": "CA", "postal_code": "94107", "country_code": "US" } } } ] };
return array( 'intent' => 'CAPTURE', 'application_context' => array( 'brand_name' => 'EXAMPLE INC', 'locale' => 'en-US', 'landing_page' => 'BILLING', 'shipping_preference' => 'SET_PROVIDED_ADDRESS', 'user_action' => 'PAY_NOW', ), 'purchase_units' => array( 0 => array( 'reference_id' => 'PUHF', 'description' => 'Sporting Goods', 'custom_id' => 'CUST-HighFashions', 'soft_descriptor' => 'HighFashions', 'amount' => array( 'currency_code' => 'USD', 'value' => '220.00', 'breakdown' => array( 'item_total' => array( 'currency_code' => 'USD', 'value' => '180.00', ), 'shipping' => array( 'currency_code' => 'USD', 'value' => '20.00', ), 'handling' => array( 'currency_code' => 'USD', 'value' => '10.00', ), 'tax_total' => array( 'currency_code' => 'USD', 'value' => '20.00', ), 'shipping_discount' => array( 'currency_code' => 'USD', 'value' => '10.00', ), ), ), 'items' => array( 0 => array( 'name' => 'T-Shirt', 'description' => 'Green XL', 'sku' => 'sku01', 'unit_amount' => array( 'currency_code' => 'USD', 'value' => '90.00', ), 'tax' => array( 'currency_code' => 'USD', 'value' => '10.00', ), 'quantity' => '1', 'category' => 'PHYSICAL_GOODS', ), 1 => array( 'name' => 'Shoes', 'description' => 'Running, Size 10.5', 'sku' => 'sku02', 'unit_amount' => array( 'currency_code' => 'USD', 'value' => '45.00', ), 'tax' => array( 'currency_code' => 'USD', 'value' => '5.00', ), 'quantity' => '2', 'category' => 'PHYSICAL_GOODS', ), ), 'shipping' => array( 'method' => 'United States Postal Service', 'address' => array( 'address_line_1' => '123 Townsend St', 'address_line_2' => 'Floor 6', 'admin_area_2' => 'San Francisco', 'admin_area_1' => 'CA', 'postal_code' => '94107', 'country_code' => 'US', ), ), ), ), );
return \ { "intent": "CAPTURE", "application_context": { "brand_name": "EXAMPLE INC", "landing_page": "BILLING", "shipping_preference": "SET_PROVIDED_ADDRESS", "user_action": "CONTINUE" }, "purchase_units": [ { "reference_id": "PUHF", "description": "Sporting Goods", "custom_id": "CUST-HighFashions", "soft_descriptor": "HighFashions", "amount": { "currency_code": "USD", "value": "230.00", "breakdown": { "item_total": { "currency_code": "USD", "value": "180.00" }, "shipping": { "currency_code": "USD", "value": "30.00" }, "handling": { "currency_code": "USD", "value": "10.00" }, "tax_total": { "currency_code": "USD", "value": "20.00" }, "shipping_discount": { "currency_code": "USD", "value": "10" } } }, "items": [ { "name": "T-Shirt", "description": "Green XL", "sku": "sku01", "unit_amount": { "currency_code": "USD", "value": "90.00" }, "tax": { "currency_code": "USD", "value": "10.00" }, "quantity": "1", "category": "PHYSICAL_GOODS" }, { "name": "Shoes", "description": "Running, Size 10.5", "sku": "sku02", "unit_amount": { "currency_code": "USD", "value": "45.00" }, "tax": { "currency_code": "USD", "value": "5.00" }, "quantity": "2", "category": "PHYSICAL_GOODS" } ], "shipping": { "method": "United States Postal Service", "address": { "name": { "full_name":"John", "surname":"Doe" }, "address_line_1": "123 Townsend St", "address_line_2": "Floor 6", "admin_area_2": "San Francisco", "admin_area_1": "CA", "postal_code": "94107", "country_code": "US" } } } ] }
body = { intent: 'CAPTURE', application_context: { brand_name: 'EXAMPLE INC', landing_page: 'BILLING', shipping_preference: 'SET_PROVIDED_ADDRESS', user_action: 'CONTINUE' }, purchase_units: [ { reference_id: 'PUHF', description: 'Sporting Goods', custom_id: 'CUST-HighFashions', soft_descriptor: 'HighFashions', amount: { currency_code: 'USD', value: '230.00', breakdown: { item_total: { currency_code: 'USD', value: '180.00' }, shipping: { currency_code: 'USD', value: '30.00' }, handling: { currency_code: 'USD', value: '10.00' }, tax_total: { currency_code: 'USD', value: '20.00' }, shipping_discount: { currency_code: 'USD', value: '10' } } }, items: [ { name: 'T-Shirt', description: 'Green XL', sku: 'sku01', unit_amount: { currency_code: 'USD', value: '90.00' }, tax: { currency_code: 'USD', value: '10.00' }, quantity: '1', category: 'PHYSICAL_GOODS' }, { name: 'Shoes', description: 'Running, Size 10.5', sku: 'sku02', unit_amount: { currency_code: 'USD', value: '45.00' }, tax: { currency_code: 'USD', value: '5.00' }, quantity: '2', category: 'PHYSICAL_GOODS' } ], shipping: { method: 'United States Postal Service', address: { name: { full_name: 'John', surname: 'Doe' }, address_line_1: '123 Townsend St', address_line_2: 'Floor 6', admin_area_2: 'San Francisco', admin_area_1: 'CA', postal_code: '94107', country_code: 'US' } } } ] }
OrderRequest orderRequest = new OrderRequest(); orderRequest.checkoutPaymentIntent("CAPTURE"); ApplicationContext applicationContext = new ApplicationContext().brandName("EXAMPLE INC").landingPage("BILLING") .shippingPreference("SET_PROVIDED_ADDRESS"); orderRequest.applicationContext(applicationContext); List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<PurchaseUnitRequest>(); PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest().referenceId("PUHF") .description("Sporting Goods").customId("CUST-HighFashions").softDescriptor("HighFashions") .amount(new AmountWithBreakdown().currencyCode("USD").value("230.00") .breakdown(new AmountBreakdown().itemTotal(new Money().currencyCode("USD").value("180.00")) .shipping(new Money().currencyCode("USD").value("30.00")) .handling(new Money().currencyCode("USD").value("10.00")) .taxTotal(new Money().currencyCode("USD").value("20.00")) .shippingDiscount(new Money().currencyCode("USD").value("10.00")))) .items(new ArrayList<Item>() { { add(new Item().name("T-shirt").description("Green XL").sku("sku01") .unitAmount(new Money().currencyCode("USD").value("90.00")) .tax(new Money().currencyCode("USD").value("10.00")).quantity("1") .category("PHYSICAL_GOODS")); add(new Item().name("Shoes").description("Running, Size 10.5").sku("sku02") .unitAmount(new Money().currencyCode("USD").value("45.00")) .tax(new Money().currencyCode("USD").value("5.00")).quantity("2") .category("PHYSICAL_GOODS")); } }) .shipping(new ShippingDetails().name(new Name().fullName("John Doe")) .addressPortable(new AddressPortable().addressLine1("123 Townsend St").addressLine2("Floor 6") .adminArea2("San Francisco").adminArea1("CA").postalCode("94107").countryCode("US"))); purchaseUnitRequests.add(purchaseUnitRequest); orderRequest.purchaseUnits(purchaseUnitRequests);
OrderRequest orderRequest = new OrderRequest() { checkoutPaymentIntent = "CAPTURE", ApplicationContext = new ApplicationContext { BrandName = "EXAMPLE INC", LandingPage = "BILLING", UserAction = "CONTINUE", ShippingPreference = "SET_PROVIDED_ADDRESS" }, PurchaseUnits = new List<PurchaseUnitRequest> { new PurchaseUnitRequest{ ReferenceId = "PUHF", Description = "Sporting Goods", CustomId = "CUST-HighFashions", SoftDescriptor = "HighFashions", Amount = new AmountWithBreakdown { CurrencyCode = "USD", Value = "230.00", Breakdown = new AmountBreakdown { ItemTotal = new Money { CurrencyCode = "USD", Value = "180.00" }, Shipping = new Money { CurrencyCode = "USD", Value = "30.00" }, Handling = new Money { CurrencyCode = "USD", Value = "10.00" }, TaxTotal = new Money { CurrencyCode = "USD", Value = "20.00" }, ShippingDiscount = new Money { CurrencyCode = "USD", Value = "10.00" } } }, Items = new List<Item> { new Item { Name = "T-shirt", Description = "Green XL", Sku = "sku01", UnitAmount = new Money { CurrencyCode = "USD", Value = "90.00" }, Tax = new Money { CurrencyCode = "USD", Value = "10.00" }, Quantity = "1", Category = "PHYSICAL_GOODS" }, new Item { Name = "Shoes", Description = "Running, Size 10.5", Sku = "sku02", UnitAmount = new Money { CurrencyCode = "USD", Value = "45.00" }, Tax = new Money { CurrencyCode = "USD", Value = "5.00" }, Quantity = "2", Category = "PHYSICAL_GOODS" } }, Shipping = new ShippingDetails { Name = new Name { FullName = "John Doe" }, AddressPortable = new AddressPortable { AddressLine1 = "123 Townsend St", AddressLine2 = "Floor 6", AdminArea2 = "San Francisco", AdminArea1 = "CA", PostalCode = "94107", CountryCode = "US" } } } } };
For the full list of parameters and example responses, see create order in the Orders 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 createOrder
function on your client. This function calls your server to create the order, instead of actions.order.create()
.
Note: PayPal recommends that you do not use jQuery's
ajax()
function as PayPal will expect yourcreateOrder
function to return a Promise, and jQuery'sajax()
function does not return a Promise. Usefetch()
to perform Ajax requests instead.
createOrder: function() {
return fetch('/my-server/create-paypal-transaction', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.id; // Use the key sent by your server's response, ex. 'id' or 'token'
});
}
Now your client and server are set up to call the PayPal Orders API to create a transaction.