Paypal Payment Gateway Integration in PHP Step by Step

Webs Codex
9 min readAug 16, 2023

--

In this tutorials you can quickly integrate PayPal in PHP apps if you run an online business. Payments can be accepted manually, through framework-based apps, or through plugins, addons, and extensions. You can also find built-in PHP libraries and composer packages with PayPal integrated in a PHP application to speed up development.

See also

What is PayPal?

PayPal is an online system that allows individuals and companies to send and receive money online. It provides a secure and useful alternative to transacting online, without providing sensitive financial information directly to the recipient.

Users can create a PayPal account using their email address and link it to their bank account, credit card, or debit card. Users may pay other PayPal users or businesses online after their accounts are set up. By safely processing payments and protecting users’ financial information, PayPal serves as an intermediary.

Here are some key features and aspects of PayPal:

  1. Online Payment: Users can pay online for goods and services on various websites that accept PayPal as a payment option.
  2. Money Transfer: This allows individuals to send money to friends, family or anyone with a PayPal account using their email address.
  3. International Transactions: PayPal supports transactions in multiple currencies, making it convenient for international money transfers.
  4. Buyer and Seller Protection: PayPal offers some protections to buyers and sellers to reduce potential fraud and disputes.
  5. Payment Processing for Businesses: PayPal provides payment solutions for businesses, which enable them to accept online payments from customers.

How to Integrate Paypal in PHP Application

To integrate PayPal into PHP websites, you can follow these general steps:

Create a PayPal Account and Get Sandbox Credentials

Sign up for PayPal account. If you don’t already have a PayPal account, go to the PayPal website and sign up for one. This will give you the required credentials and access to PayPal’s developer account.

Once you have a PayPal Account, log in to your account and navigate to the Developer Dashboard. Create a REST API app and obtain the API credentials, including the Client ID and Secret.

JavaScript SDK script configuration

The JavaScript SDK displays relevant, PayPal-supported payment methods on your page, providing your shoppers with a personalized and streamlined checkout experience.

Script tag

You can add the sdk to the script tag. This main object loads PayPal into the global window scope of the browser. Replace YOUR_CLIENT_IDYOUR_CLIENT_ID with your client ID.

If you want to more changes on your Palpal button or style go to the paypal javascript developer SDK JS official page.

To integrate PayPal payment gateway with your PHP website, follow the steps given below. The PHP sample app, which includes the following files, is used to demonstrate the integration process.

Create Database and Table by SQL query

We need to create database and table, so here I created webscodex database payment_transaction & products table. payment_transaction table holds the records which will be payment success or failed. You can simply create table as following SQL query.

-- Database: `webscodex`
--
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`product_name` varchar(100) NOT NULL,
`image` varchar(100) NOT NULL,
`description` text NOT NULL,
`price` int(50) NOT NULL,
`status` tinyint(4) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Table structure for table `payment_transaction`
--

CREATE TABLE `payment_transaction` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`order_id` varchar(100) NOT NULL,
`product_summary` varchar(100) NOT NULL,
`full_name` varchar(100) NOT NULL,
`mobile_number` varchar(100) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`currency` varchar(100) NOT NULL,
`status` varchar(100) NOT NULL,
`txns_id` varchar(100) NOT NULL,
`txns_date` datetime NOT NULL,
`address` varchar(50) NOT NULL,
`pincode` varchar(50) NOT NULL,
`city` varchar(50) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

Create Database Configuration

In this step, we require to create database configuration file, here we will set database name, server, username and password. So let’s create config.php file on your root directory and put bellow code:

config.php

<?php 
// Database configuration
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'webscodex');

// Connect with the database
$con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>

Create Add to cart or Buy Product

Create Product list or add to card list in our project for e-commerce feature then buy a product using Paypal payment gateway. We have created an index.php file for product listing for add to card or buy now.

index.php

<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paypal Payment Gateway Integration in PHP Step by Step</title>
<!-- Bootstrap CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="background:#f2f2f2;padding: 50px;">
<div class="py-5 text-center">
<h2> Products List (Paypal Payment Gateway Integration) </h2>
</div>
<div class="row">
<?php
// Include configuration
require "inc/config.php";

$sql = "SELECT * FROM products WHERE status = '1' order by id DESC";
$query = $con->query($sql);
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {

?>
<div class="col-md-4">
<div class="card" style="height: 543px;">
<img src="images/<?php echo $row['image']?>" style="width:325px; height: 250px;">
<div class="card-body">
<h5 class="card-title"><?php echo $row['product_name']?></h5>
<p class="card-text"><?php echo $row['description']?></p>
<a href="checkout.php?product_id=<?php echo $row['id']?>" class="btn btn-sm btn-primary">Buy Now</a>
<b><span style="float: right;"> $<?php echo $row['price']?></span></b>
</div>
</div>
</div>
<?php } } ?>
</div>
</div>
</body>
</html>

Create HTML Checkout Form

we have create a simple HTML checkout form that includes fields for name, email, phone, address, city, and pin code. The form uses the POST method to submit the data to a server-side script called checkout.php.

checkout.php

<?php

// Include configuration
require "inc/config.php";

if (!empty($_GET['product_id']) && isset($_GET['product_id'])) {
$pid = $_GET['product_id'];
}

$sql = "SELECT * FROM products WHERE id = $pid";
$query = $con->query($sql);

if ($count = $query->num_rows > 0) {

$row = $query->fetch_assoc();
}

?>

<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paypal Payment Gateway Integration in PHP Step by Step</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<body>
<div class="container" style="background: #f2f2f2; padding-bottom:20px; border: 1px solid #d9d9d9; border-radius: 5px;">
<div class="py-5 text-center">
<h2> Paypal Payment Gateway Integration Checkout</h2>
<p class="lead">This Checkout page using Paypal Payment Gateway for Testing purpose </p>
</div>
<form action="pay.php" method="POST">
<div class="row">
<div class="col-md-8">
<h4>Billing address</h4>
<div class="card p-3">
<div class="mb-3">
<label for="firstName">Full Name </label>
<input type="text" id="name" class="form-control" name="full_name" placeholder="Full Name" required="">
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="mobile">Mobile Number</label>
<input type="text" id="phone" class="form-control" name="phone" placeholder="Mobile Number" required="">
</div>
<div class="col-md-6 mb-3">
<label for="email">Email </label>
<input type="email" id="email" class="form-control" name="email_address" placeholder="Email">
</div>
</div>
<div class="mb-3">
<label for="address">Flat, House no. Area, Street, Sector, Village</label>
<input type="text" id="address" class="form-control" name="address" placeholder="Full Address" required="">
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="city">Town/City</label>
<input type="text" id="city" class="form-control" name="city" placeholder="Town/City">
</div>
<div class="col-md-6 mb-3">
<label for="pincode">Pincode</label>
<input type="text" id="pincode" class="form-control" name="pincode" placeholder="6 digits [0-9] Pin code" required="">
</div>
</div>
</div>
</div>
<div class="col-md-4">
<h4 class="d-flex justify-content-between align-items-center">
<span>Order Summary</span>
<span class="badge badge-secondary badge-pill"><?php echo $count; ?></span>
</h4>
<ul class="list-group mb-3 sticky-top">
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div class="product-list">
<img src="images/<?php echo $row['image']?>" style="width:100px; height: 100px;">
<h6><?php echo $row['product_name']?></h6>
<small class="text-muted"><?php echo $row['description']?></small>
</div>
<span class="text-muted">$<?php echo $row['price']?></span>
</li>
<li class="list-group-item d-flex justify-content-between">
<strong> Order Total: </strong>
<strong>$<?php echo $row['price']?></strong>
<input type="hidden" name="amount" value="<?php echo $row['price']?>" />
<input type="hidden" id="product_summary" name="product_summary" value="<?php echo $row['product_name']?>" />
</li>
</ul>
<div class="form-group">
<button type="submit" class="btn btn-success" name="check_out_btn" style="display: none;">Checkout</button>
<div id="paypal-button-container" class="mt-3"></div>
</div>
</div>
</div>
</form>
</div>
</body>
</html>

<!-- Replace "test" with your own sandbox Business account app client ID -->
<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"></script>

<script>
paypal.Buttons({
onClick(){
$('.text-danger').remove();
var counter = 0;
if ($("#name").val() == "") {
$("#name").after('<span class="text-danger">Name is required</span>');
counter++;
}
if ($("#phone").val() == "") {
$("#phone").after('<span class="text-danger">Phone is required</span>');
counter++;
}
if ($("#email").val() == "") {
$("#email").after('<span class="text-danger">Email is required</span>');
counter++;
}
if ($("#address").val() == "") {
$("#address").after('<span class="text-danger">Address is required</span>');
counter++;
}
if ($("#pincode").val() == "") {
$("#pincode").after('<span class="text-danger">Pincode is required</span>');
counter++;
}
if ($("#city").val() == "") {
$("#city").after('<span class="text-danger">City is required</span>');
counter++;
}

if (counter > 0) {
return false;
}else{
return true;
}
},

createOrder: (data, actions)=> {
return actions.order.create({
purchase_units:[{
amount:{
value: "<?php echo $row['price']?>",
currency_code: 'USD'
}
}]
});
},
onApprove: (data, actions)=> {
return actions.order.capture().then(function(orderData){
const transaction = orderData.purchase_units[0].payments.captures[0];
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var address = $("#address").val();
var city = $("#city").val();
var pincode = $("#pincode").val();
var productSummary = $("#product_summary").val();

var formData = {
'name' : name,
'email' : email,
'phone': phone,
'address' : address,
'city' : city,
'pincode' : pincode,
'product_summary' : productSummary,
'transaction_id' : transaction.id,
'payment_status' : transaction.status,
'check_out_btn' : true,
'amount' : transaction.amount.value,
'currency_code' : transaction.amount.currency_code,
'create_time' : transaction.create_time
};

$.ajax({
method: "POST",
url: "pay.php",
data: formData,
success:function(response){
if (response=="success") {
window.location.href = "success.php?txnsId=" + transaction.id;
}else{
window.location.href="cancel.php";
}
}
});
});
}
}).render('#paypal-button-container');
//This function displays payment buttons on your web page.
</script>

Here you can see a valid checkout form filled in with the product added to the card ready for purchase with PayPal.

ThecreateOrdercreateOrder parameter sets up the details of the transaction. This parameter is called when the buyer clicks the PayPal button, which launches the PayPal Checkout window where the buyer logs in and approves the transaction on the paypal.com website.

The onApprove parameter captures the payment of the transaction along with the payment status transaction ID and many other values are returned with this method.

Insert Payment details in Database

When buyer clicks on Paypal button Paypal login form is displayed to fill email and password and click on complete purchase button then create order and approve payment transaction. After running onApprove function call ajax pay.php action to insert or save payment details in payment_transaction table with payment status, transaction_id, transaction_date etc.

pay.php

<?php

// Include configuration
require "inc/config.php";

if (isset($_POST['check_out_btn'])) {

// Check whether the charge was successful
if ($_POST['payment_status'] == 'COMPLETED') {

$customerName = $_POST['name'];
$customerEmail = $_POST['email'];
$customerPhone = $_POST['phone'];
$description = $_POST['product_summary'];
$address = $_POST['address'];
$city = $_POST['city'];
$pincode = $_POST['pincode'];
$transaction_id = $_POST['transaction_id'];
$amount = $_POST['amount'];
$currency = $_POST['currency_code'];
$payment_status = $_POST['payment_status'];
$txnsDate = $_POST['create_time'];
$orderId = "WC".mt_rand(11111, 99999); // Random generate order Id

// Insert transaction data into the database
$query = "INSERT INTO payment_transaction (order_id, product_summary, full_name, mobile_number, email, amount, currency, status, txns_id, txns_date, address, pincode, city)
VALUES ('$orderId', '$description', '$customerName', '$customerPhone', '$customerEmail', '$amount', '$currency', '$payment_status', '$transaction_id', '$txnsDate', '$address', '$pincode', '$city')";

if ($con->query($query)) {
echo "success";
}else{
echo "failed";
}

}else{
echo "failed";
}
}
?>

Payment Success

If payment status is COMPLETED then payment page is redirected to success page with transaction id to show payment details. I have used this type of method which you can change as per your choice.

success.php

<?php 

// Include configuration
require "inc/config.php";

// If transaction data is available in the URL
if(!empty($_GET['txnsId']) ){

$txnsId = $_GET['txnsId'];

// Get transaction info from the database
$sqlQuery = "SELECT * FROM payment_transaction WHERE txns_id = '$txnsId'";

$query = $con->query($sqlQuery);
$rowValue = $query->fetch_array();
}
?>
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paypal Payment Gateway Integration in PHP Step by Step</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 offset-2 mt-5">
<?php if(!empty($rowValue['txns_id'])){ ?>
<h1 class="text-success">Your Payment has been Successful</h1>

<h4>Payment Information</h4>
<p><b>Transaction ID:</b> <?php echo $rowValue['txns_id']; ?></p>
<p><b>Paid Amount:</b> <?php echo $rowValue['amount']; ?></p>
<p><b>Payment Status:</b> <?php echo $rowValue['status']; ?></p>

<h4>Product Information</h4>
<p><b>Name:</b> <?php echo $rowValue['product_summary']; ?></p>
<p><b>Price:</b> $<?php echo $rowValue['amount']; ?></p>
<?php }else{ ?>
<h1 class="text-danger">Your Payment has Failed</h1>
<?php } ?>
<a href="index.php" class="btn-link">Back to Products</a>
</div>
</div>
</div>
</body>
</html>

Payment Cancellation or Failed

When a buyer cancels or failed a payment, they typically return to the cancel page. on the other hand, You can instead use the cancel.php page to show the cancellation or failed page.

cancel.php

<div class="container">
<div class="status">
<h1 class="error">Your PayPal Transaction has been Canceled</h1>
</div>
<a href="index.php" class="btn-link">Back to Products</a>
</div>

If you want to more details and better quality to learn the paypal payment gateway integration click on the below link and get more payment gateway integration in php

Paypal Payment gateway integration in PHP

Conclusion

In this tutorial, I have explain the process of How you can integrate PayPal in PHP application. I have explain the very simple way to Paypal payment integrate. You can extend this to more complex uses like online shops etc.

--

--

Webs Codex
Webs Codex

Written by Webs Codex

Webs Codex is programming and web development blog

No responses yet