PayPal Standard Checkout in PHP (Venmo, Debit/Credit Card, Pay Later Options)
PayPal is a globally recognized electronic payment gateway that allows people to shop online and send and receive money using their PayPal accounts. It has become a "must be included" payment gateway for web applications due to its advanced features and services.

PayPal offers different REST APIs that enable web applications to create and manage customer orders, capture, authorize, and refund payments, send money to multiple recipients, and receive automatic notifications. The most commonly used APIs are Orders API, Payments API, Payouts API, Subscriptions API, Invoicing API, and Webhooks API. This post demonstrates how to add a PayPal checkout button in a PHP application to integrate a checkout experience.
What are Payment Buttons, and How Do They Work?
PayPal payment buttons are customizable buttons that PayPal offers to allow web applications to accept payments for orders, subscriptions, and donations with ease. The workflow of these buttons is as follows:
- We place the payment buttons on the checkout page.
- The user clicks the buttons to make the payment.
- The checkout experience launches in a pop-up window with configured options.
- The user makes and approves the payment, and the orders API is called to finalize the transaction.
- The user is presented with an order confirmation page upon successful transaction.
How to Integrate PayPal Checkout in PHP?
PayPal is one of the popular payment gateways that web applications use to allow users to make instant payments for their orders. The standard checkout integration involves the use of the Orders API with the JavaScript SDK for client-side processing. We will create an HTML page with a container for payment buttons and create and capture the order in a PHP script on the server side. The following are the steps for the implementation:
- We must first have a PayPal sandbox account.
- Get the OAuth 2.0 client ID and client secret of this sandbox account.
- Create a PHP class to handle API requests for creating and capturing orders.
- Create an HTML page with cart items and add PayPal checkout buttons.
- Render the payment buttons with JavaScript and send a request to the server-side script.
- Create and save the order to PayPal in the server-side script.
- Show a success page when an order is successfully created.
We are going to set a static array in the session that will hold the cart products. In this example, we are not saving the order to the database, and we are not demonstrating the shopping cart implementation itself. We will create the following files :
- constants.php: This file contains PayPal credential constants.
- paypal-sdk/paypal_client.php: A PHP class responsible for making API requests.
- index.php: An HTML page that displays the cart items and checkout buttons.
- javascript.js: Our client-side JavaScript to render the payment buttons.
- paypal-request.php: The file that processes the order requests and uses the
paypal_clientclass to create and capture orders. - style.css: CSS styles for our entire user interface.
Step 1: Create a PayPal Sandbox App and Get API Credentials
- Log in to the PayPal developer account and navigate to the PayPal Developer dashboard.
- Click "Sandbox Accounts" under "Testing Tools" in the top navigation menu.
- Click the "Create Account" button. We need two accounts: one for the buyer and another for the merchant.
- Now click "App & Credentials" in the top navigation menu.
- Click "Create App", enter the App Name, and assign a merchant account to the App.

- After we have created our app, we will see a screen like this. We need to copy the Client ID and Client Secret for use in our application.

Now that we have our Sandbox Client ID & Secret, we are ready for the next to integrate payment buttons.
Step 2: Add PayPal Credential Constants
Since we will be using the PayPal credentials to communicate with API endpoints, we need to store these credentials in a constants file. We will define PAYPAL_ENVIRONMENT, PAYPAL_CLIENT_ID, and PAYPAL_CLIENT_SECRET constants.
constants.php
<?php
define('PAYPAL_ENVIRONMENT', 'sandbox');
define('PAYPAL_CLIENT_ID', 'PAYPAL_CLIENT_ID');
define('PAYPAL_CLIENT_SECRET', 'PAYPAL_CLIENT_SECRET');
Step 3: Create a PayPal Client Class to Send API Requests
The application will need to access different API endpoints, so we need a reusable and centralized class that is capable of handling different types of API requests. This class will generate and refresh access tokens and create and capture orders. The class definition is as follows:
$base_url: Contains the sandbox or production endpoint URL.$client_id: Client ID created in previous steps.$client_secret: Client secret created in previous steps.$access_token: Access token for PayPal requests authorization.$token_type: The type of token, i.e. "Bearer".$expires_in: The expiration time of the current access token. Used to refresh/recreate the token when it expires.$created_at: The creation time of the current access token. Used to refresh/recreate the token when it expires.
The methods implemented in our paypal_client class are:
__construct(): The class constructor is triggered when an instance of the class is created. Sets the$client_id,$client_secret,$base_url, and$access_tokenproperties of the class.set_access_token(): Sends the request to PayPal's authorization endpoint to retrieve the access token for future requests. Sets the$access_token,$token_type,$expires_in, and$created_atproperties of class.curl_request(): A reusable function used to send cURL requests to PayPal API endpoints.
paypal_client.php
<?php
class paypal_client
{
public string $base_url;
private string $client_id;
private string $client_secret;
private ?string $access_token;
private string $token_type;
private int $expires_in;
private int $created_at;
public function __construct($client_id, $client_secret, $sandbox = false)
{
$this->client_id = $client_id;
$this->client_secret = $client_secret;
$this->base_url = $sandbox
? 'https://api-m.sandbox.paypal.com'
: 'https://api-m.paypal.com';
$this->access_token = null;
}
/**
* @throws Exception
*/
public function set_access_token(): stdClass|array
{
$headers = [
'content-type' => 'application/x-www-form-urlencoded'
];
$curl_options = [
CURLOPT_USERPWD => $this->client_id . ':' . $this->client_secret
];
$body = [
'grant_type' => 'client_credentials'
];
$response = $this->curl_request('/v1/oauth2/token', 'POST', $headers, http_build_query($body), $curl_options);
$response = json_decode($response);
$this->access_token = $response->access_token;
$this->token_type = $response->token_type;
$this->expires_in = $response->expires_in;
$this->created_at = time();
return $response;
}
/**
* @param string $path
* @param string $method
* @param array $headers
* @param array|string $body
* @param array $curl_options
* @return bool|string
* @throws Exception
*/
public function curl_request(string $path, string $method, array $headers = [], array|string $body = [], array $curl_options = []): bool|string
{
$curl = curl_init();
array_change_key_case($headers);
$headers = array_merge(['accept' => 'application/json'], $headers);
curl_setopt($curl, CURLOPT_URL, $this->base_url . $path);
curl_setopt($curl, CURLOPT_TIMEOUT, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if (str_starts_with($this->base_url, 'https://')) {
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
}
if (!array_key_exists('authorization', $headers) && !str_ends_with($path, 'v1/oauth2/token')) {
if (is_null($this->access_token) || time() > ($this->created_at + $this->expires_in)) {
$this->set_access_token();
}
$headers['authorization'] = sprintf('%s %s', $this->token_type, $this->access_token);
}
// If any headers are set, add them to cURL request
if (!empty($headers)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array_map(function ($key, $value) {
return $key . ': ' . $value;
}, array_keys($headers), array_values($headers)));
}
// Set the request type, GET, POST, PUT, or DELETE
switch (strtoupper($method)) {
case 'POST':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
break;
case 'PUT':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default:
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
break;
}
// If any data is supposed to be sent along with the request, add it to the cURL request
if (!empty($body)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}
// Any extra cURL options to add to the cURL object
if (!empty($curl_options)) {
foreach ($curl_options as $option_key => $option_value) {
curl_setopt($curl, $option_key, $option_value);
}
}
$response = curl_exec($curl);
$error = curl_error($curl);
$error_code = curl_errno($curl);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($error_code > 0) {
throw new Exception($error, $error_code);
}
if ($status_code < 200 || $status_code >= 300) {
throw new Exception($response, $status_code);
}
curl_close($curl);
return $response;
}
}
Step 4: Create the Checkout Page with PayPal Buttons
Create an HTML page that displays cart items in a table and contains the container element for checkout buttons. Loop through the products in the session and calculate the total tax amount and the total items amount (without tax). The following code snippet uses a static array as an example.
index.php
<?php
if (!session_id()) {
session_start();
}
include __DIR__ . '/constants.php';
$products = [];
// Static array of products
$products[] = ['product_title' => 'Javascript Book - PDF', 'product_price' => 10.00, 'product_tax' => 2.00, 'product_quantity' => 3];
$products[] = ['product_title' => 'PHP Book - PDF', 'product_price' => 15.00, 'product_tax' => 3.00, 'product_quantity' => 2];
$items_total = $tax_total = 0.00;
// Loop through products and calculate tax total & items total
foreach ($products as $product) {
$tax_total += floatval($product['product_tax'] * $product['product_quantity']);
$items_total += floatval($product['product_price'] * $product['product_quantity']);
}
// Function to show amount in price format
function to_price($amount = 0.00, $locale = 'en_US', $currency_code = 'USD'): bool|string
{
return numfmt_format_currency(numfmt_create($locale, NumberFormatter::CURRENCY), $amount, $currency_code);
}
// Create a cart session
$_SESSION['cart']['products'] = $products;
$_SESSION['cart']['items_total'] = $items_total;
$_SESSION['cart']['tax_total'] = $tax_total;
$_SESSION['cart']['cart_total'] = $tax_total + $items_total;
?>
<!DOCTYPE html>
<html>
<head>
<title>PayPal Standard Checkout in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
<script src="https://www.paypal.com/sdk/js?client-id=<?= PAYPAL_CLIENT_ID ?>" defer="defer"></script>
<script src="js/javascript.js" defer="defer"></script>
</head>
<body>
<section class="section py-4">
<div class="container">
<table class="table table-bordered mb-4">
<thead>
<tr>
<th colspan="2">Product</th>
<th style="width: 120px">Price</th>
<th style="width:120px;">Tax</th>
<th style="width:100px;">Quantity</th>
<th style="width: 120px;">Item Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($_SESSION['cart']['products'] as $product) {
$item_total = $product['product_price'] * $product['product_quantity'];
$item_tax = $product['product_tax'] * $product['product_quantity'];
?>
<tr>
<td width="31">
<img src="images/pdf-book.png"/>
</td>
<td>
<?= $product['product_title']; ?>
</td>
<td>
<?= to_price($product['product_price']); ?>
</td>
<td>
<?= to_price($product['product_tax']); ?>
</td>
<td>
<?= $product['product_quantity'] ?>
</td>
<td>
<?= to_price($item_total + $item_tax); ?>
</td>
</tr>
<?php } ?>
<tr>
<th colspan="5" class="text-right">
Tax Total
</th>
<th class="text-right">
<?= to_price($_SESSION['cart']['tax_total']); ?>
</th>
</tr>
<tr>
<th colspan="5" class="text-right">
Items Total
</th>
<th class="text-right">
<?= to_price($_SESSION['cart']['items_total']); ?>
</th>
</tr>
<tr>
<th colspan="5" class="text-right">
Cart Total
</th>
<th class="text-right">
<?= to_price($_SESSION['cart']['cart_total']); ?>
</th>
</tr>
</tbody>
</table>
<div id="paypal-buttons"></div>
</div>
</section>
</body>
</html>
Step 5: Initialize PayPal Payment Buttons on Checkout Page (JavaScript)
We render the PayPal payment buttons in this step using the JavaScript SDK. The number of buttons depends on the App configuration. It will render the PayPal Checkout by default, but other methods such as basic Debit/Credit card, Pay Later, or Pay in 4 installments, Apple Pay, and Google Pay can also be added. Some of these methods require special conditions to be met, like Venmo can be added for US-only users, Google Pay will work in Chrome browsers, and Apple Pay will work in Safari browsers or IOS devices. The following are the steps to render buttons with the JavaScript SDK:
- Listen to the window load event and render PayPal buttons.
- Define an endpoint for
createOrderto create an order in our server-side script. - Define
onApproveto capture the order and redirect the user to a success page after a successful transaction.
javascript.js
window.addEventListener("load", function () {
// Render PayPal Buttons
paypal.Buttons({
style: {
layout: "horizontal"
},
// Call the server to create an order
createOrder: function (data, actions) {
return fetch("paypal-request.php", {
mode: "no-cors",
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
action: "create-order",
})
}).then(function (res) {
return res.json();
}).then(function (data) {
if (!data.success && data.message) {
console.error(data.message);
}
return data.id;
});
},
// Call the server to save the transaction
onApprove: function (data, actions) {
return fetch("paypal-request.php", {
mode: "no-cors",
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
action: "save-order",
id: data.orderID
})
}).then(function (res) {
return res.json();
}).then(function (data) {
// Redirect to thank you/success page after saving transaction
if (data.success) {
window.location.assign("payment-success.php");
}
});
}
}).render("#paypal-buttons");
});Step 6: Create and Capture an Order on Server Side
When user triggers the to make a payment using the method/option of their choice, the request will sent to server-side URL defined in createOrder method. The server-side script will utilize the paypal_client class to create and save an order (upon a successful transaction).
paypal-request.php
<?php
if (!session_id()) {
session_start();
}
include __DIR__ . '/constants.php';
// Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
include __DIR__ . '/paypal-sdk/paypal_client.php';
// Capture the input received from fetch() request
$json_data = file_get_contents('php://input');
$request = json_decode($json_data);
$paypal_client = new paypal_client(PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PAYPAL_ENVIRONMENT === 'sandbox');
switch ($request->action) {
case 'create-order':
$headers = [
'prefer' => 'return=representation',
'content-type' => 'application/json'
];
// Assign cart from session to a variable
$cart = $_SESSION['cart'];
// Set currency code used in transaction
$currency_code = 'USD';
$request_body = [];
$application_context = [];
$purchase_units = [];
$pu_amount = [];
// Prepare context of our request
$application_context['locale'] = 'en-US';
$application_context['user_action'] = 'PAY_NOW';
// Prepare amount & breakdown of amount for order
$pu_amount['currency_code'] = $currency_code;
$pu_amount['value'] = floatval($cart['cart_total']);
// Items total breakdown without tax
$pu_amount['breakdown']['item_total']['currency_code'] = $currency_code;
$pu_amount['breakdown']['item_total']['value'] = number_format($cart['items_total'], 2);
// Total tax of all products
$pu_amount['breakdown']['tax_total']['currency_code'] = $currency_code;
$pu_amount['breakdown']['tax_total']['value'] = number_format($cart['tax_total'], 2);
$purchase_units['amount'] = $pu_amount;
$items = [];
// Loop through all products in session and prepare items array for order request
if (!empty($cart['products'])) {
foreach ($cart['products'] as $product) {
$item['name'] = $product['product_title'];
$item['quantity'] = $product['product_quantity'];
$item['category'] = 'DIGITAL_GOODS';
// Unit amount of product (without tax)
$item['unit_amount']['currency_code'] = $currency_code;
$item['unit_amount']['value'] = number_format($product['product_price'], 2);
$items[] = $item;
}
}
$purchase_units['items'] = $items;
// Finally create request body array assigning context & purchase units created above
$request_body['intent'] = 'CAPTURE';
$request_body['application_context'] = $application_context;
$request_body['purchase_units'][] = $purchase_units;
try {
$response = $paypal_client->curl_request('/v2/checkout/orders', 'POST', $headers, json_encode($request_body));
die($response);
} catch (Exception $e) {
echo $e->getMessage();
}
break;
case 'save-order':
$headers = [
'prefer' => 'return=minimal',
'content-type' => 'application/json'
];
try {
$response = $paypal_client->curl_request(sprintf('/v2/checkout/orders/%s/capture', $request->id), 'POST', $headers);
// Save order to database here
// unset cart session
unset($_SESSION['cart']);
echo json_encode(['success' => 1], JSON_PRETTY_PRINT);
} catch (Exception $e) {
echo $e->getMessage();
}
break;
}
Step 7: Add CSS Styles for Checkout Page
PayPal adds necessary styling for the payment methods/buttons it renders via the JavaScript SDK. We still need to add CSS styles for the rest of the user interface.
style.css
* {
box-sizing: border-box;
}
html,body {
margin: 0;
padding: 0;
}
body {
background-color: #f6f6f6;
font-family: "Segoe UI", "Roboto", "Helvetica", sans-serif;
font-size: 15px;
font-weight: normal;
font-style: normal;
line-height: 1.5;
}
.container {
width: 100%;
max-width: 1140px;
margin-right: auto;
margin-left: auto;
padding-right: 15px;
padding-left: 15px;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.text-right {
text-align: right;
}
.table {
width: 100%;
border-collapse: collapse;
background-color: #fff;
margin-bottom: 1rem;
}
.table tr th,
.table tr td {
border: 1px solid #dddddd;
padding: 10px;
}
#paypal-buttons {
max-width: 750px;
margin-right: auto;
margin-left: auto;
}After we place an order and log in to our sandbox buyer/merchant account, we will be able to see the transactions as in the screenshot below:

PayPal offers an easy, secure, and convenient way for a web application to securely receive online payments. We demonstrated PayPal checkout integration in PHP using the Orders API v2 and JavaScript SKD that allows customers to approve payments, allows us to create orders, and capture the transactions from our application. The implementation can be further modified to save orders to a database and add notification hooks to programmatically update the status of orders.