- Payment code in php
- Payment Gateway PHP Steps to Follow
- Usage
- Passing URL for Payment
- Payment Gateway Process
- Payment Gateway PHP
- PayPal Payment Integration in PHP
- Steps to Integration PayPal Payment Gateway using PHP
- 1. Create a Database, Tables and Dump Sample Data
- 2. Create a config.php File & Make Necessary Changes
- 3. Create an index.php File & Display Some Products to Buy
- 4. Create a notify.php File, Handle IPN & Insert Payment Record in DB
- 5. Create a cancel.php File
- 6. Create a return.php File
- 7. Create a style.css File
- Conclusion
Payment code in php
In this article let’s see how implement Payment Gateway PHP Source Code project. Nowadays most of peoples are sell their products on online, so we need payment gateways for accept the amounts. Currently lot of gateways are available like CCAvenue, Payumoney, Razorpay, payubiz, Instamojo, citrus pay, paypal and more.
Recent days Razor Pay recommended by more developers because easy documentation & user friendly navigation. Another major reason accept international payments like US, UK etc.
Already we have clearly explained the procedure in one article which is integrated in Python language. But the steps are same in all technology. Therefore read here for the integration guides. Actually the steps are easy, we have to enter just merchant key & salt.
Here I have using framework, because payment gateway is not like easy process. Manually we need to setup some changes & implement code. So when we use CORE PHP, more difficulties to facing for handle the errors. That’s why most of developers are suggest some frameworks like Laravel, Codeigniter etc.
Payment Gateway PHP Steps to Follow
If you are beginner on this category once read the official documentation. After that you got some idea for build the code. The initial step is select one of the best payment gateway providers. For example in this project we have to select Razorpay software private limited.
I hope already you have download node on your system, to extract the dependency manager. So first create Laravel project via command prompt.
use Shipu\Aamarpay\Aamarpay; $config = [ 'store_id' => 'Your store id', 'signature_key' => 'Your signature key', 'sandbox' => true, 'redirect_url' => [ 'success' => [ 'route' => 'payment.success' ], 'cancel' => [ 'route' => 'payment.cancel' ] ] ]; $payment = new Aamarpay($config);
Above code is explained the mandatory field of modules which is connected to on the database. Then only we able to communicate with database system. Otherwise the exact data not transfer & on back-end communication.
Usage
Usage means which is mostly used for back-end process like how data accessed & stored on server side. In this project I have using MySQL database. It was mostly recommended language for 95 percentage peoples of developers.
- Customer Name
- Email-id / Phone Number
- Card Details
- Currency
- Bank Details
- Confirmation Receipt.
- Money Transfer Status
- Check Balance
- Offers (optional)
Passing URL for Payment
To pass the URL for payment gateway server who are totally manage the back-end process. Which means get full permission for transfer & receive the amount from customers.
use \Shipu\Aamarpay\Aamarpay; . $payment = new Aamarpay(config('aamarpay')); return $payment->customer([ 'cus_name' => 'Shipu Ahamed', // Customer name 'cus_phone' => '01616022669' // Customer Phone 'cus_email' => 'shipuahamed01@gmail.com', // Customer email ])->transactionId()->amount(3500)->hiddenValue(); or return $payment->customer([ 'cus_name' => 'Shipu Ahamed', // Customer name 'cus_phone' => '9854345483' // Customer Phone 'cus_email' => 'shipuahamed01@gmail.com', // Customer email ])->amount(3500)->hiddenValue();
For the demo purpose, in the above section provide unverified details. But in the live process, we must give the validated information. After that only the particular customers able to send and receive the payments. These days most of peoples make online payments like Payumoney, CCAvenue, Net Banking, Phonepe and more applications are available.
Payment Gateway Process
Generally when we make online payments, there are three possibilities when our transaction will be failed. That was,
- Success Message (Amount will be credited/Debited Successfully)
- Failed (Server Busy)
- Canceled (It was raised by client itself)
Route::post('payment/success', 'YourMakePaymentsController@paymentSuccess')->name('payment.success'); Route::post('payment/failed', 'YourMakePaymentsController@paymentFailed')->name('payment.failed'); Route::post('payment/cancel', 'YourMakePaymentsController@paymentCancel')->name('payment.cancel');
Payment Gateway PHP
Above all code helps to build this project. Moreover surely issues are raised when develop on our own risk. Because in some places we make connection process. So through the online documentation helps, we easily do it on our end. In below get Payment Gateway PHP Source code in free of cost.
PayPal Payment Integration in PHP
In this tutorial, I will explain how to do PayPal Payment Integration in PHP. As of now, it is the most popular online American payment system which makes it easy to send and receive money over the internet.
The PayPal provides various ways to send and receive money online, you can directly send money to your friend or family member and you can also make payment to several services on the internet by using PayPal.
It is also most popular online payment gateway, use to accept payments through web and mobile applications.
There are some other popular online payment gateways, if you want to offer multiple payment options to your customer then you can also allow them to make payment using Authorize.Net.
I have shared a separate and detailed tutorial about Authorize.Net payment gateway integration using PHP.
Stripe is also popular payment gateway, learn how to integrate stripe payment gateway using PHP.
PayPal offers several ways to Integrate PayPal Payment Gateway to your website, some of them are listed below:
- PayPal Payments Standard
- Checkout
- Subscriptions & Recurring Payments
- PayPal Invoicing
- Payouts
I will focus on PayPal Payments Standard, as it is the most easiest way to integrate PayPal payment using PHP. So lets start integration of PayPal payment standards in PHP.
I will use my previous tutorial PHP CRUD Operations to access database and perform all database related operations using class dbclass.php.
I will skip rewriting of the same class to avoid duplication of code. However, I will include the same class in download file, so you do not need to worry about the dbclass.php class.
Steps to Integration PayPal Payment Gateway using PHP
I will follow the below steps to integrate PayPal payment gateway on my website using PHP.
- Create a Database, Tables and Dump Sample Data
- Create a config.php File & Make Necessary Changes
- Create an index.php File & Display Some Products to Buy
- Create a notify.php File, Handle IPN & Insert Payment Record in DB
- Create a cancel.php File
- Create a return.php File
- Create a style.css File
1. Create a Database, Tables and Dump Sample Data
To create database run the following query in MySQL.
CREATE DATABASE allphptricks;
To create the tables run the following queries.
CREATE TABLE `products` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(250) NOT NULL, `code` varchar(100) NOT NULL, `price` double(9,2) NOT NULL, `image` varchar(250) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `code` (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Note: I have already attached the SQL file of this table with dummy data, just download the complete zip file of this tutorial.
CREATE TABLE `payment_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `item_number` varchar(255) NOT NULL, `item_name` varchar(255) NOT NULL, `payment_status` varchar(255) NOT NULL, `amount` double(10,2) NOT NULL, `currency` varchar(255) NOT NULL, `txn_id` varchar(255) NOT NULL, `create_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Dump sample data into `products` table.
INSERT INTO `products` (`id`, `name`, `code`, `price`, `image`) VALUES (1, 'Laptop Core i5', 'Laptop01', 100.00, 'product-images/laptop.jpg'), (2, 'Laptop Bag', 'Bag01', 10.00, 'product-images/laptop-bag.jpg'), (3, 'iPhone X', 'iphone01', 50.00, 'product-images/iphone.jpg');
2. Create a config.php File & Make Necessary Changes
Create a config.php file, copy paste the following code and make necessary changes like update your database credentials, database name, username, password, also update your PayPal business email, return, cancel, notify URLs etc.
else < $paypal_url = "https://www.paypal.com/cgi-bin/webscr"; >// PayPal IPN Data Validate URL define('PAYPAL_URL', $paypal_url);
3. Create an index.php File & Display Some Products to Buy
Create an index.php file, copy paste the following code in it. This page will display all products from `products` table, so that user can easily buy any product.
query("SELECT * FROM `products`"); $products = $db->resultSet(); $db->close(); ?> PayPal Payment Integration in PHP
4. Create a notify.php File, Handle IPN & Insert Payment Record in DB
Create a notify.php file, copy paste the following code in it. This page will handle all PayPal Instant Payment Notification (IPN), validate the data and add record into ` payment_info ` table.
// Build the body of the verification post request, // adding the _notify-validate command. $req = 'cmd=_notify-validate'; if(function_exists('get_magic_quotes_gpc')) < $get_magic_quotes_exists = true; >foreach ($myPost as $key => $value) < if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) < $value = urlencode(stripslashes($value)); >else < $value = urlencode($value); >$req .= "&$key=$value"; > /* Post IPN data back to PayPal using curl to validate the IPN data is valid & genuine Anyone can fake IPN data, if you skip it. */ $ch = curl_init(PAYPAL_URL); if ($ch == FALSE) < return FALSE; >curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_SSLVERSION, 6); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); /* This is often required if the server is missing a global cert bundle, or is using an outdated one. Please download the latest 'cacert.pem' from http://curl.haxx.se/docs/caextract.html */ if (LOCAL_CERTIFICATE == TRUE) < curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem"); >// Set TCP timeout to 30 seconds curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Connection: Close', 'User-Agent: PHP-IPN-Verification-Script' )); $res = curl_exec($ch); // cURL error if (curl_errno($ch) != 0) < curl_close($ch); exit; >else < curl_close($ch); >/* * Inspect IPN validation result and act accordingly * Split response headers and payload, a better way for strcmp */ $tokens = explode("\r\n\r\n", trim($res)); $res = trim(end($tokens)); if (strcmp($res, "VERIFIED") == 0 || strcasecmp($res, "VERIFIED") == 0) < // assign posted variables to local variables $item_number = $_POST['item_number']; $item_name = $_POST['item_name']; $payment_status = $_POST['payment_status']; $amount = $_POST['mc_gross']; $currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; $receiver_email = $_POST['receiver_email']; // $payer_email = $_POST['payer_email']; // check that receiver_email is your PayPal business email if (strtolower($receiver_email) != strtolower(PAYPAL_EMAIL)) < error_log(date('[Y-m-d H:i e] '). "Invalid Business Email: $req" . PHP_EOL, 3, IPN_LOG_FILE); exit(); >// check that payment currency is correct if (strtolower($currency) != strtolower(CURRENCY)) < error_log(date('[Y-m-d H:i e] '). "Invalid Currency: $req" . PHP_EOL, 3, IPN_LOG_FILE); exit(); >//Check Unique Transcation ID $db = new DB; $db->query("SELECT * FROM `payment_info` WHERE txn_id=:txn_id"); $db->bind(':txn_id', $txn_id); $db->execute(); $unique_txn_id = $db->rowCount(); if(!empty($unique_txn_id)) < error_log(date('[Y-m-d H:i e] '). "Invalid Transaction ID: $req" . PHP_EOL, 3, IPN_LOG_FILE); $db->close(); exit(); >else< $db->query("INSERT INTO `payment_info` (`item_number`, `item_name`, `payment_status`, `amount`, `currency`, `txn_id`) VALUES (:item_number, :item_name, :payment_status, :amount, :currency, :txn_id)"); $db->bind(":item_number", $item_number); $db->bind(":item_name", $item_name); $db->bind(":payment_status", $payment_status); $db->bind(":amount", $amount); $db->bind(":currency", $currency); $db->bind(":txn_id", $txn_id); $db->execute(); /* error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, IPN_LOG_FILE); */ > $db->close(); > else if (strcmp($res, "INVALID") == 0) < //Log invalid IPN messages for investigation error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, IPN_LOG_FILE); >?>
5. Create a cancel.php File
Create a cancel.php file, copy paste the following code in it. Customer will be redirected here if he/she cancels payment from PayPal payment page.
Sorry! Your PayPal Payment has been cancelled.
6. Create a return.php File
Create a return.php file, copy paste the following code in it. Customer will be redirected here when the payment is successful.
Your paymeny has been received successfully.
Thank you!
7. Create a style.css File
Create a style.css file, copy paste the following code in it. This is the stylesheet of your index page where all products are displayed nicely.
body < font-family: Arial, sans-serif; line-height: 1.6; >.product_wrapper < float:left; padding: 10px; text-align: center; >.product_wrapper:hover < box-shadow: 0 0 0 2px #e5e5e5; cursor:pointer; >.product_wrapper .name < font-weight:bold; >.product_wrapper .pay < text-transform: uppercase; background: #F68B1E; border: 1px solid #F68B1E; cursor: pointer; color: #fff; padding: 8px 40px; margin-top: 10px; >.product_wrapper .pay:hover
Conclusion
By following the above step by step guide, anyone can easily integrate PayPal payment gateway in PHP. PayPal Payments Standard is the easiest payment integration which can enable online payment on your website within a day or in a few hours.
I try to keep my code easy and simple as possible, but if anyone of you still having any trouble so feel free to comment below, I try my best to reply all comments and questions of my blog readers.
If you found this tutorial helpful, share it with your friends and developers group.
I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook, Twitter and share it.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.