In this article, I am going to show you How to Integrate PayPal Payment Gateway in PHP. It is easily registered debit/credit card(s) with your PayPal account. This PayPal account is used for a variety of businesses including e-commerce websites, freelancers, digital marketing, and more. Scroll down to the page so you can see the full source code available for this.
PayPal is an online secure payment platform and easy-to-use payment processing worldwide. It is best features that PayPal offers include
- International money transfer
- Create an online invoice
- Create an Individual and Business accounts
- Accept Debit Cards and Credit Cards
- Mobile Payments
- Cart
Step 1 : Create a PayPal account type below.
1. Individual Account
-Send payments only
-Pay for your shopping worldwide- 2. Business Account
-Receive and send payments
-Suitable for individuals who want to receive payments, sellers, business and freelancers.
select business on account creation.
Step 2 : Go to this link paypal developer dashboard and login into your PayPal developer account. See The Below Images.
Step 3 : Go to Download this link PayPal PHP SDK 1.13.0
Next, Project structure your folder as follows.
src
├── composer
├── paypal
├── psr
├── autoload.php
├── config.php
├── db_connection.php
├── index.php
├── payment-cancelled.html
├── PaypalSuccess.php
├── request.php
├── response.php
└── style.css
MySQL database
In the following example, we will start how to PayPal REST API Payment Gateway into the MySQL database using PHP.
- Database Name – codeat21
- Table Name – products, payments
productsCREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `price` float(10,2) NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
paymentsCREATE TABLE `payments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `product_id` float(10,2) NOT NULL, `transaction_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `payment_amount` float(10,2) NOT NULL, `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL, `payment_status` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `invoice_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `product_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `createdtime` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
db_connection.php<?php $db_conn = mysqli_connect("localhost", "root", "", "codeat21"); // Check connection if($db_conn === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } error_reporting(E_ALL); ini_set('display_errors','Off'); ?>
config.php<?php use PayPal\Rest\ApiContext; use PayPal\Auth\OAuthTokenCredential; require './autoload.php'; // For test payments we want to enable the sandbox mode. If you want to put live // payments through then this setting needs changing to `false`. $enableSandbox = true; // PayPal settings. Change these to your account details and the relevant URLs // for your site. $paypalConfig = [ 'client_id' => 'your paypal client id', 'client_secret' => 'your paypal secret id', 'return_url' => 'http://localhost/paypal-rest-api/response.php', 'cancel_url' => 'http://localhost/paypal-rest-api/payment-cancelled.html' ]; // Database settings. Change these for your database configuration. $dbConfig = [ 'host' => 'localhost', 'username' => 'root', 'password' => '', 'name' => 'codeat21' ]; $apiContext = getApiContext($paypalConfig['client_id'], $paypalConfig['client_secret'], $enableSandbox); /** * Set up a connection to the API * * @param string $clientId * @param string $clientSecret * @param bool $enableSandbox Sandbox mode toggle, true for test payments * @return \PayPal\Rest\ApiContext */ function getApiContext($clientId, $clientSecret, $enableSandbox = false) { $apiContext = new ApiContext( new OAuthTokenCredential($clientId, $clientSecret) ); $apiContext->setConfig([ 'mode' => $enableSandbox ? 'sandbox' : 'live' ]); return $apiContext; }
Next, open up the index.php file located in the src folder. You should see this:
index.php<?php include_once 'db_connection.php'; ?> <!DOCTYPE html> <html> <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 REST API Example</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body class="App"> <h1>How to Integrate PayPal REST API Payment Gateway in PHP</h1> <div class="wrapper"> <?php $results = mysqli_query($db_conn,"SELECT * FROM products where status=1"); while($row = mysqli_fetch_array($results)){ ?> <div class="col__box"> <h5><?php echo $row['name']; ?></h5> <h6>Price: <span> $<?php echo $row['price']; ?> </span> </h6> <form class="paypal" action="request.php" method="post" id="paypal_form"> <input type="hidden" name="item_number" value="<?php echo $row['id']; ?>" > <input type="hidden" name="item_name" value="<?php echo $row['name']; ?>" > <input type="hidden" name="amount" value="<?php echo $row['price']; ?>" > <input type="hidden" name="currency_code" value="USD" > <input type="submit" name="submit" value="Buy Now" class="btn__default"> </form> </div> <?php } ?> </div> </body> </html>
request.php<?php use PayPal\Api\Amount; use PayPal\Api\Payer; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Api\Transaction; use PayPal\Api\ItemList; require 'config.php'; if (empty($_POST['item_number'])) { throw new Exception('This script should not be called directly, expected post data'); } $payer = new Payer(); $payer->setPaymentMethod('paypal'); // Set some example data for the payment. $currency = 'USD'; $item_qty = 1; $amountPayable = $_POST['amount']; $product_name = $_POST['item_name']; $item_code = $_POST['item_number']; $description = 'Paypal transaction'; $invoiceNumber = uniqid(); $my_items = array( array('name'=> $product_name, 'quantity'=> $item_qty, 'price'=> $amountPayable, 'sku'=> $item_code, 'currency'=> $currency) ); $amount = new Amount(); $amount->setCurrency($currency) ->setTotal($amountPayable); $items = new ItemList(); $items->setItems($my_items); $transaction = new Transaction(); $transaction->setAmount($amount) ->setDescription($description) ->setInvoiceNumber($invoiceNumber) ->setItemList($items); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($paypalConfig['return_url']) ->setCancelUrl($paypalConfig['cancel_url']); $payment = new Payment(); $payment->setIntent('sale') ->setPayer($payer) ->setTransactions([$transaction]) ->setRedirectUrls($redirectUrls); try { $payment->create($apiContext); } catch (Exception $e) { throw new Exception('Unable to create link for payment'); } header('location:' . $payment->getApprovalLink()); exit(1);
response.php<?php use PayPal\Api\Payment; use PayPal\Api\PaymentExecution; require 'config.php'; if (empty($_GET['paymentId']) || empty($_GET['PayerID'])) { throw new Exception('The response is missing the paymentId and PayerID'); } $paymentId = $_GET['paymentId']; $payment = Payment::get($paymentId, $apiContext); $execution = new PaymentExecution(); $execution->setPayerId($_GET['PayerID']); try { // Take the payment $payment->execute($execution, $apiContext); try { $db = new mysqli($dbConfig['host'], $dbConfig['username'], $dbConfig['password'], $dbConfig['name']); $payment = Payment::get($paymentId, $apiContext); $data = [ 'product_id' => $payment->transactions[0]->item_list->items[0]->sku, 'transaction_id' => $payment->getId(), 'payment_amount' => $payment->transactions[0]->amount->total, 'currency_code' => $payment->transactions[0]->amount->currency, 'payment_status' => $payment->getState(), 'invoice_id' => $payment->transactions[0]->invoice_number, 'product_name' => $payment->transactions[0]->item_list->items[0]->name, 'description' => $payment->transactions[0]->description, ]; if (addPayment($data) !== false && $data['payment_status'] === 'approved') { // Payment successfully added, redirect to the payment complete page. $inserids =$db->insert_id; header("location:http://localhost/paypal-rest-api/PaypalSuccess.php?payid=$inserids"); exit(1); } else { // Payment failed header("location:http://localhost/paypal-rest-api/PaypalFailed.php"); exit(1); } } catch (Exception $e) { // Failed to retrieve payment from PayPal } } catch (Exception $e) { // Failed to take payment } /** * Add payment to database * * @param array $data Payment data * @return int|bool ID of new payment or false if failed */ function addPayment($data) { global $db; if (is_array($data)) { //'isdsssss' --- i - integer, d - double, s - string, b - BLOB $stmt = $db->prepare('INSERT INTO `payments` (product_id,transaction_id, payment_amount,currency_code, payment_status, invoice_id, product_name, createdtime) VALUES(?, ?, ?, ?, ?, ?, ?, ?)'); $stmt->bind_param( 'isdsssss', $data['product_id'], $data['transaction_id'], $data['payment_amount'], $data['currency_code'], $data['payment_status'], $data['invoice_id'], $data['product_name'], date('Y-m-d H:i:s') ); $stmt->execute(); $stmt->close(); return $db->insert_id; } return false; }
PaypalSuccess.php<?php include_once 'db_connection.php'; ?> <!DOCTYPE html> <html> <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 REST API Example</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body class="App"> <h1>Your Payment has been Successful</h1> <div class="wrapper"> <?php $paymentid = $_GET['payid']; $results = mysqli_query($db_conn,"SELECT * FROM payments where id='$paymentid' "); $row = mysqli_fetch_array($results); ?> <div class="status"> <h4>Payment Information</h4> <p>Reference Number: <?php echo $row['invoice_id']; ?></p> <p>Transaction ID: <?php echo $row['transaction_id']; ?></p> <p>Paid Amount: <?php echo $row['payment_amount']; ?></p> <p>Payment Status: <?php echo $row['payment_status']; ?></p> <h4>Product Information</h4> <p>Product id: <?php echo $row['product_id']; ?></p> <p>Product Name: <?php echo $row['product_name']; ?></p> </div> </div> </body> </html>
Conclusion
In this tutorial, you learned about How to Integrate PayPal Payment Gateway in PHP step by step add a success page and error page to the application we created.
Related keywords
'client_id' => 'AUJoKVGO3q1WA1tGgAKRdY6qx0qQNIQ6vl6D3k7y64T4qh5WozIQ7V3dl3iusw5BwXYg_T5FzLCRguP8', 'client_secret' => 'EOw8LNwDhM7esrQ3nHfzKc7xiWnJc83Eawln4YLfUgivfx1LGzu9Mj0F5wlarilXDqdK9Q5aHVo-VGjJ',- How to Automate Online Payments Within PayPal
- Rest Api PayPal Integration code in PHP
- How to PayPal Payment Gateway Integration in PHP using PayPal REST API
- PayPal PHP SDK not working for Subscriptions, get RESOURCE_NOT_FOUND
- php paypal integration not work latest version of php
- codeat21 PayPal Integration code in PHP source code download
- This website show country are united states, France, Canada, japan, New york, london, Los Angeles, Russia, Italy, Spain, Ukraine, Poland, Romania, Finland, Slovakia, Ireland, Croatia, Netherlands, Belgium, Czech Republic(Czechia), Greece, Portugal, Estonia, Montenegro, Andorra, Monaco, Liechtenstein, Sweden, Hungary, Belarus, San Marino, Austria, Serbia, Moldova, Bosnia and Herzegovina, Albania, Lithuania, North Macedonia, Slovenia,Latvia, Holy See, Luxembourg, Malta, Iceland, Channel Islands,Switzerland, Bulgaria, Denmark, Isle of Man, Faeroe Islands, Gibraltar, Germany,United Kingdom.