On this page
No Headings
Last updated: June 17, 2026
Here's an example PayPal integration with all possible customizations enabled.
The server-side examples below show a standard integration without vault. If your account has vault enabled and you want to save payment methods, see Save payment methods to add vault configuration. Including vault by default can block other products like Pay Later messaging for merchants who don't have vault enabled.
Create and capture a PayPal order with complete customization options including shipping and payment source details.
curl -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-d '{
"intent": "CAPTURE",
"purchase_units": [
{
"reference_id": "d9f80740-38f0-11e8-b467-0ed5f89f718b",
"amount": {
"currency_code": "USD",
"value": "100.00"
},
"payee": {
"email_address": "payee@example.com",
"merchant_id": "MERCHANT-ID"
},
"soft_descriptor": "PAYPAL *TEST STORE",
"shipping": {
"name": {
"full_name": "Firstname Lastname"
},
"address": {
"address_line_1": "123 Main St.",
"admin_area_1": "CA",
"admin_area_2": "Anytown",
"postal_code": "12345",
"country_code": "US"
}
}
}
],
"payment_source": {
"paypal": {
"experience_context": {
"return_url": "https://example.com/return",
"cancel_url": "https://example.com/cancel",
"brand_name": "EXAMPLE INC",
"locale": "en-US",
"landing_page": "BILLING",
"shipping_preference": "SET_PROVIDED_ADDRESS",
"user_action": "PAY_NOW"
}
}
}
}'import { Client, orders } from '@paypal/checkout-server-sdk';
const client = new Client({
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
environment: 'sandbox'
});
const createOrderRequest = new orders.OrdersCreateRequest();
createOrderRequest.prefer("return=representation");
createOrderRequest.requestBody({
intent: "CAPTURE",
purchase_units: [
{
reference_id: "d9f80740-38f0-11e8-b467-0ed5f89f718b",
amount: {
currency_code: "USD",
value: "100.00"
},
payee: {
email_address: "payee@example.com",
merchant_id: "MERCHANT-ID"
},
soft_descriptor: "PAYPAL *TEST STORE",
shipping: {
name: {
full_name: "Firstname Lastname"
},
address: {
address_line_1: "123 Main St.",
admin_area_1: "CA",
admin_area_2: "Anytown",
postal_code: "12345",
country_code: "US"
}
}
}
],
payment_source: {
paypal: {
experience_context: {
return_url: "https://example.com/return",
cancel_url: "https://example.com/cancel",
brand_name: "EXAMPLE INC",
locale: "en-US",
landing_page: "BILLING",
shipping_preference: "SET_PROVIDED_ADDRESS",
user_action: "PAY_NOW"
}
}
}
});
const response = await client.execute(createOrderRequest);
const order = response.result;
console.log(`Order ID: ${order.id}`);
console.log(`Order Status: ${order.status}`);from paypalrestsdk import Api, Order
import os
api = Api({
'mode': 'sandbox',
'client_id': os.environ['PAYPAL_CLIENT_ID'],
'client_secret': os.environ['PAYPAL_CLIENT_SECRET']
})
order = Order({
"intent": "CAPTURE",
"purchase_units": [
{
"reference_id": "d9f80740-38f0-11e8-b467-0ed5f89f718b",
"amount": {
"currency_code": "USD",
"value": "100.00"
},
"payee": {
"email_address": "payee@example.com",
"merchant_id": "MERCHANT-ID"
},
"soft_descriptor": "PAYPAL *TEST STORE",
"shipping": {
"name": {
"full_name": "Firstname Lastname"
},
"address": {
"address_line_1": "123 Main St.",
"admin_area_1": "CA",
"admin_area_2": "Anytown",
"postal_code": "12345",
"country_code": "US"
}
}
}
],
"payment_source": {
"paypal": {
"experience_context": {
"return_url": "https://example.com/return",
"cancel_url": "https://example.com/cancel",
"brand_name": "EXAMPLE INC",
"locale": "en-US",
"landing_page": "BILLING",
"shipping_preference": "SET_PROVIDED_ADDRESS",
"user_action": "PAY_NOW"
}
}
}
})
if order.create():
print(f"Order ID: {order.id}")
print(f"Order Status: {order.status}")
else:
print(f"Error: {order.error}")import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import com.paypal.orders.*;
import java.util.List;
HttpClient httpClient = new PayPalHttpClient(
new SandboxEnvironment(
System.getenv("PAYPAL_CLIENT_ID"),
System.getenv("PAYPAL_CLIENT_SECRET")
)
);
OrdersCreateRequest request = new OrdersCreateRequest();
request.header("Prefer", "return=representation");
request.body(new OrderRequest()
.intent("CAPTURE")
.purchaseUnits(List.of(
new PurchaseUnitRequest()
.referenceId("d9f80740-38f0-11e8-b467-0ed5f89f718b")
.amount(new Money()
.currencyCode("USD")
.value("100.00")
)
.payee(new Payee()
.emailAddress("payee@example.com")
.merchantId("MERCHANT-ID")
)
.softDescriptor("PAYPAL *TEST STORE")
.shipping(new ShippingDetail()
.name(new Name().fullName("Firstname Lastname"))
.address(new AddressPortable()
.addressLine1("123 Main St.")
.adminArea1("CA")
.adminArea2("Anytown")
.postalCode("12345")
.countryCode("US")
)
)
))
.paymentSource(new PaymentSourceDefinition()
.paypal(new PayPalWallet()
.experienceContext(new PayPalExperienceContext()
.returnUrl("https://example.com/return")
.cancelUrl("https://example.com/cancel")
.brandName("EXAMPLE INC")
.locale("en-US")
.landingPage("BILLING")
.shippingPreference("SET_PROVIDED_ADDRESS")
.userAction("PAY_NOW")
)
)
)
);
HttpResponse<Order> response = httpClient.execute(request);
Order order = response.result();
System.out.println("Order ID: " + order.id());
System.out.println("Order Status: " + order.status());<?php
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
$environment = new SandboxEnvironment(
getenv('PAYPAL_CLIENT_ID'),
getenv('PAYPAL_CLIENT_SECRET')
);
$client = new PayPalHttpClient($environment);
$request = new OrdersCreateRequest();
$request->prefer("return=representation");
$request->body = [
"intent" => "CAPTURE",
"purchase_units" => [
[
"reference_id" => "d9f80740-38f0-11e8-b467-0ed5f89f718b",
"amount" => [
"currency_code" => "USD",
"value" => "100.00"
],
"payee" => [
"email_address" => "payee@example.com",
"merchant_id" => "MERCHANT-ID"
],
"soft_descriptor" => "PAYPAL *TEST STORE",
"shipping" => [
"name" => [
"full_name" => "Firstname Lastname"
],
"address" => [
"address_line_1" => "123 Main St.",
"admin_area_1" => "CA",
"admin_area_2" => "Anytown",
"postal_code" => "12345",
"country_code" => "US"
]
]
]
],
"payment_source" => [
"paypal" => [
"experience_context" => [
"return_url" => "https://example.com/return",
"cancel_url" => "https://example.com/cancel",
"brand_name" => "EXAMPLE INC",
"locale" => "en-US",
"landing_page" => "BILLING",
"shipping_preference" => "SET_PROVIDED_ADDRESS",
"user_action" => "PAY_NOW"
],
]
]
];
$response = $client->execute($request);
echo "Order ID: " . $response->result->id . "\n";
echo "Order Status: " . $response->result->status . "\n";require 'paypal-sdk'
PayPal::SDK.configure(
:mode => "sandbox",
:app_id => ENV['PAYPAL_APP_ID'],
:client_id => ENV['PAYPAL_CLIENT_ID'],
:client_secret => ENV['PAYPAL_CLIENT_SECRET']
)
order = PayPal::SDK::OrdersApi::Order.new(
intent: "CAPTURE",
purchase_units: [
{
reference_id: "d9f80740-38f0-11e8-b467-0ed5f89f718b",
amount: {
currency_code: "USD",
value: "100.00"
},
payee: {
email_address: "payee@example.com",
merchant_id: "MERCHANT-ID"
},
soft_descriptor: "PAYPAL *TEST STORE",
shipping: {
name: {
full_name: "Firstname Lastname"
},
address: {
address_line_1: "123 Main St.",
admin_area_1: "CA",
admin_area_2: "Anytown",
postal_code: "12345",
country_code: "US"
}
}
}
],
payment_source: {
paypal: {
experience_context: {
return_url: "https://example.com/return",
cancel_url: "https://example.com/cancel",
brand_name: "EXAMPLE INC",
locale: "en-US",
landing_page: "BILLING",
shipping_preference: "SET_PROVIDED_ADDRESS",
user_action: "PAY_NOW"
}
}
}
)
order.create
puts "Order ID: #{order.id}"
puts "Order Status: #{order.status}"After creating the order, you'll receive a complete response with order details, payer information, and payment confirmation:
{
"id": "0KD30046EH157382X",
"intent": "CAPTURE",
"status": "COMPLETED",
"payment_source": {
"paypal": {
"email_address": "payer@example.com",
"account_id": "PAYER-ID",
"account_status": "UNVERIFIED",
"name": {
"given_name": "Firstname",
"surname": "Lastname"
},
"address": {
"address_line_1": "2211 N First Street",
"address_line_2": "17.3.160",
"admin_area_2": "San Jose",
"admin_area_1": "CA",
"postal_code": "95131",
"country_code": "US"
}
}
},
"purchase_units": [
{
"reference_id": "d9f80740-38f0-11e8-b467-0ed5f89f718b",
"amount": {
"currency_code": "USD",
"value": "100.00"
},
"payee": {
"email_address": "payee@example.com",
"merchant_id": "MERCHANT-ID"
},
"soft_descriptor": "PAYPAL *TEST STORE",
"shipping": {
"name": {
"full_name": "Firstname Lastname"
},
"address": {
"address_line_1": "123 Main St.",
"admin_area_1": "CA",
"admin_area_2": "Anytown",
"postal_code": "12345",
"country_code": "US"
}
},
"payments": {
"captures": [
{
"id": "CAPTURE-ID",
"status": "COMPLETED",
"amount": {
"currency_code": "USD",
"value": "100.00"
},
"final_capture": true,
"seller_protection": {
"status": "ELIGIBLE",
"dispute_categories": [
"ITEM_NOT_RECEIVED",
"UNAUTHORIZED_TRANSACTION"
]
},
"seller_receivable_breakdown": {
"gross_amount": {
"currency_code": "USD",
"value": "100.00"
},
"paypal_fee": {
"currency_code": "USD",
"value": "3.98"
},
"net_amount": {
"currency_code": "USD",
"value": "96.02"
}
},
"links": [
{
"href": "https://api.sandbox.paypal.com/v2/payments/captures/CAPTURE-ID",
"rel": "self",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v2/payments/captures/CAPTURE-ID/refund",
"rel": "refund",
"method": "POST"
},
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/ORDER-ID",
"rel": "up",
"method": "GET"
}
],
"create_time": "2024-03-15T20:41:04Z",
"update_time": "2024-03-15T20:41:04Z"
}
]
}
}
],
"payer": {
"name": {
"given_name": "Firstname",
"surname": "Lastname"
},
"email_address": "payer@example.com",
"payer_id": "PAYER-ID",
"address": {
"address_line_1": "123 Main St.",
"admin_area_1": "CA",
"admin_area_2": "Anytown",
"postal_code": "12345",
"country_code": "US"
}
},
"create_time": "2024-03-15T19:57:25Z",
"update_time": "2024-03-15T20:41:04Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/ORDER-ID",
"rel": "self",
"method": "GET"
}
]
}Complete client-side implementation using the PayPal JavaScript SDK with support for PayPal, Pay Later, and PayPal Credit payment methods.
async function onPayPalWebSdkLoaded() {
try {
// Get client token for authentication
const clientToken = await getBrowserSafeClientToken();
// Create PayPal SDK instance
const sdkInstance = await window.paypal.createInstance({
clientToken,
components: ["paypal-payments"],
pageType: "checkout",
});
// Check eligibility for all payment methods
const paymentMethods = await sdkInstance.findEligibleMethods({
currencyCode: "USD",
});
// Set up PayPal button if eligible
if (paymentMethods.isEligible("paypal")) {
configurePayPalButton(sdkInstance);
}
// Set up Pay Later button if eligible
if (paymentMethods.isEligible("paylater")) {
const payLaterPaymentMethodDetails = paymentMethods.getDetails("paylater");
setUpPayLaterButton(sdkInstance, payLaterPaymentMethodDetails);
}
// Set up PayPal Credit button if eligible
if (paymentMethods.isEligible("credit")) {
const paypalCreditPaymentMethodDetails = paymentMethods.getDetails("credit");
setUpPayPalCreditButton(sdkInstance, paypalCreditPaymentMethodDetails);
}
} catch (error) {
console.error("SDK initialization error:", error);
}
}
// Shared payment session options for all payment methods
const paymentSessionOptions = {
// Called when user approves a payment
async onApprove(data) {
console.log("Payment approved:", data);
try {
const orderData = await captureOrder({
orderId: data.orderId,
});
console.log("Payment captured successfully:", orderData);
} catch (error) {
console.error("Payment capture failed:", error);
}
},
// Called when user cancels a payment
onCancel(data) {
console.log("Payment cancelled:", data);
},
// Called when an error occurs during payment
onError(error) {
console.error("Payment error:", error);
},
};
// Set up standard PayPal button
async function configurePayPalButton(sdkInstance) {
const paypalPaymentSession = sdkInstance.createPayPalOneTimePaymentSession(
paymentSessionOptions,
);
const paypalButton = document.querySelector("paypal-button");
paypalButton.removeAttribute("hidden");
paypalButton.addEventListener("click", async () => {
try {
await paypalPaymentSession.start(
{ presentationMode: "auto" }, // Auto-detects best presentation mode
createOrder(),
);
} catch (error) {
console.error("PayPal payment start error:", error);
}
});
}
// Set up Pay Later button
async function setUpPayLaterButton(sdkInstance, payLaterPaymentMethodDetails) {
const payLaterPaymentSession = sdkInstance.createPayLaterOneTimePaymentSession(
paymentSessionOptions
);
const { productCode, countryCode } = payLaterPaymentMethodDetails;
const payLaterButton = document.querySelector("paypal-pay-later-button");
// Configure button with Pay Later specific details
payLaterButton.productCode = productCode;
payLaterButton.countryCode = countryCode;
payLaterButton.removeAttribute("hidden");
payLaterButton.addEventListener("click", async () => {
try {
await payLaterPaymentSession.start(
{ presentationMode: "auto" },
createOrder(),
);
} catch (error) {
console.error("Pay Later payment start error:", error);
}
});
}
// Set up PayPal Credit button
async function setUpPayPalCreditButton(sdkInstance, paypalCreditPaymentMethodDetails) {
const paypalCreditPaymentSession = sdkInstance.createPayPalCreditOneTimePaymentSession(
paymentSessionOptions
);
const { countryCode } = paypalCreditPaymentMethodDetails;
const paypalCreditButton = document.querySelector("paypal-credit-button");
// Configure button with PayPal Credit specific details
paypalCreditButton.countryCode = countryCode;
paypalCreditButton.removeAttribute("hidden");
paypalCreditButton.addEventListener("click", async () => {
try {
await paypalCreditPaymentSession.start(
{ presentationMode: "auto" },
createOrder(),
);
} catch (error) {
console.error("PayPal Credit payment start error:", error);
}
});
}Implement these server-side functions to support the client-side integration:
# Get client token
curl -X POST https://api-m.sandbox.paypal.com/v1/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Authorization: Basic BASE64_ENCODED_CLIENT_ID_SECRET" \
-d "grant_type=client_credentials&target_customer_id=CUSTOMER_ID"
# Capture order
curl -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders/ORDER_ID/capture \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-d '{}'import { Client, orders } from '@paypal/checkout-server-sdk';
const client = new Client({
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
environment: 'sandbox'
});
// Generate client token for browser
async function getBrowserSafeClientToken() {
const tokenResponse = await fetch(
'https://api-m.sandbox.paypal.com/v1/oauth2/token',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(
`${process.env.PAYPAL_CLIENT_ID}:${process.env.PAYPAL_CLIENT_SECRET}`
).toString('base64')}`
},
body: 'grant_type=client_credentials'
}
);
const data = await tokenResponse.json();
return data.access_token;
}
// Capture order after approval
async function captureOrder({ orderId }) {
const captureRequest = new orders.OrdersCaptureRequest(orderId);
captureRequest.prefer("return=representation");
const response = await client.execute(captureRequest);
return response.result;
}from paypalrestsdk import Api, Order
import os
import base64
import requests
api = Api({
'mode': 'sandbox',
'client_id': os.environ['PAYPAL_CLIENT_ID'],
'client_secret': os.environ['PAYPAL_CLIENT_SECRET']
})
def get_browser_safe_client_token():
"""Generate client token for browser"""
auth = base64.b64encode(
f"{os.environ['PAYPAL_CLIENT_ID']}:{os.environ['PAYPAL_CLIENT_SECRET']}".encode()
).decode()
response = requests.post(
'https://api-m.sandbox.paypal.com/v1/oauth2/token',
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': f'Basic {auth}'
},
data='grant_type=client_credentials'
)
return response.json()['access_token']
def capture_order(order_id):
"""Capture order after approval"""
order = Order.find(order_id)
if order.execute():
return order.to_dict()
else:
raise Exception(order.error)import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import com.paypal.orders.*;
import java.util.Base64;
import java.net.http.*;
import java.net.URI;
public class PayPalHelpers {
private static HttpClient httpClient = new PayPalHttpClient(
new SandboxEnvironment(
System.getenv("PAYPAL_CLIENT_ID"),
System.getenv("PAYPAL_CLIENT_SECRET")
)
);
public static String getBrowserSafeClientToken() throws Exception {
String auth = Base64.getEncoder().encodeToString(
(System.getenv("PAYPAL_CLIENT_ID") + ":" +
System.getenv("PAYPAL_CLIENT_SECRET")).getBytes()
);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api-m.sandbox.paypal.com/v1/oauth2/token"))
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Basic " + auth)
.POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
// Parse JSON and return access_token
return parseAccessToken(response.body());
}
public static Order captureOrder(String orderId) throws Exception {
OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
request.prefer("return=representation");
HttpResponse<Order> response = httpClient.execute(request);
return response.result();
}
}<?php
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
$environment = new SandboxEnvironment(
getenv('PAYPAL_CLIENT_ID'),
getenv('PAYPAL_CLIENT_SECRET')
);
$client = new PayPalHttpClient($environment);
function getBrowserSafeClientToken() {
$auth = base64_encode(
getenv('PAYPAL_CLIENT_ID') . ':' . getenv('PAYPAL_CLIENT_SECRET')
);
$ch = curl_init('https://api-m.sandbox.paypal.com/v1/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . $auth
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
return $data['access_token'];
}
function captureOrder($orderId) {
global $client;
$request = new OrdersCaptureRequest($orderId);
$request->prefer("return=representation");
$response = $client->execute($request);
return $response->result;
}require 'paypal-sdk'
require 'base64'
require 'net/http'
require 'json'
PayPal::SDK.configure(
:mode => "sandbox",
:app_id => ENV['PAYPAL_APP_ID'],
:client_id => ENV['PAYPAL_CLIENT_ID'],
:client_secret => ENV['PAYPAL_CLIENT_SECRET']
)
def get_browser_safe_client_token
auth = Base64.strict_encode64(
"#{ENV['PAYPAL_CLIENT_ID']}:#{ENV['PAYPAL_CLIENT_SECRET']}"
)
uri = URI('https://api-m.sandbox.paypal.com/v1/oauth2/token')
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/x-www-form-urlencoded'
request['Authorization'] = "Basic #{auth}"
request.body = 'grant_type=client_credentials'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
data = JSON.parse(response.body)
data['access_token']
end
def capture_order(order_id)
order = PayPal::SDK::OrdersApi::Order.new(id: order_id)
order.capture
order
endSee the JavaScript SDK reference for more details on available options and features.