PayPal is the most popular payment gateway to send and receive payment worldwide. PayPal payment gateway is the easiest option for the web developer to implement payment system on the website.
Once the user clicks on the Buy Now/Payment button, they will be redirected to the PayPal where the payment will complete.
After payment completion, the user will be redirected back to the website and the transaction details to be shown to the user.
Also, the transaction information would be stored in the MySQL database.
PayPal has two environments such as
- Sandbox
- Live.
PayPal Sandbox allows developers to do their test transaction before the project go live.
Create a sandbox account from the below link :
https://developer.paypal.com/docs/classic/lifecycle/sb_create-accounts/
Live environment is used after project live. Once PayPal payment process is working fine on Sandbox environment, you can set PayPal to Live environment.
Database Tables Creation
To store payment transaction information table need to be created in MySQL database. payments table is used for storing the transaction information provided by PayPal.
CREATE TABLE `payments` ( `payment_id` int(11) NOT NULL AUTO_INCREMENT, `item_number` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `payment_gross` float(10,2) NOT NULL, `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL, `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`payment_id`) )
Submit a form with some predefined PayPal HTML form field variable. Follow the comment tags (<!– –>) to know about the form hidden fields.
<?php //Set useful variables for paypal form $paypalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //Test PayPal API URL $paypalID = 'Insert_PayPal_Email'; //Business Email ?> <img src="images/<?php echo $row['image']; ?>"/> Name: <?php echo $row['name']; ?> Price: <?php echo $row['price']; ?> <form action="<?php echo $paypalURL; ?>" method="post"> <!-- Identify your business so that you can collect the payments. --> <input type="hidden" name="business" value="<?php echo $paypalID; ?>"> <!-- Specify a Buy Now button. --> <input type="hidden" name="cmd" value="_xclick"> <!-- Specify details about the item that buyers will purchase. --> <input type="hidden" name="item_name" value="WP Database Backup"> <input type="hidden" name="item_number" value="12345"> <input type="hidden" name="amount" value="22"> <input type="hidden" name="currency_code" value="USD"> <!-- Specify URLs : replace with your site url --> <input type='hidden' name='cancel_return' value='http://walkeprashant.in/cancel.php'> <input type='hidden' name='return' value='http://walkeprashant.in/success.php'> <!-- Display the payment button. --> <input type="image" name="submit" border="0" src="button_url" alt="PayPal - The safer, easier way to pay online"> </form>
Change the cancel_return and return input field value with your desired URL in PayPal HTML form.
Payment Success (success.php)
Once the PayPal payment is successful, the buyer is redirected to this page. The transaction information is received using $_GET method and inserts payment data into the database.
Create success.php file and show appropriate message.
Payment Cancel (cancel.php)
If the buyer wishes to cancel payment at the PayPal payment page, the buyer is redirected to this page.
Your PayPal transaction has been canceled.
IPN
To make the PayPal Standard Payment more secure, Instant Payment Notification (IPN) should be used to validate the transaction.
Enable IPN
To Use this feature, IPN must be enabled in PayPal account.
Please go to the below link.
https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNSetup/
Add Notify URL in PayPal Form
Add the following input field (notify_url) HTML along with the other PayPal HTML Variables.
Validate Transaction
Once IPN is enabled PayPal will send the transaction data to the Notify URL (http://walkeprashant.in/ipn.php). Place the following code in ipn.php file to validate and insert payment information into the database
<php
//Database credentials $dbHost = 'localhost'; $dbUsername = 'root'; $dbPassword = ''; $dbName = 'walkeprashantdb'; //Connect with the database $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); //Display error if failed to connect if ($db->connect_errno) { printf("Connect failed: %s\n", $db->connect_error); exit(); }
$raw_post_data = file_get_contents('php://input'); $raw_post_array = explode('&', $raw_post_data); $myPost = array(); foreach ($raw_post_array as $keyval) { $keyval = explode ('=', $keyval); if (count($keyval) == 2) $myPost[$keyval[0]] = urldecode($keyval[1]); } // Read the post from PayPal system and add 'cmd' $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 to validate the IPN data is genuine * Without this step anyone can fake IPN data */ $paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr"; $ch = curl_init($paypalURL); 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); // Set TCP timeout to 30 seconds curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close', 'User-Agent: company-name')); $res = curl_exec($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) { //Payment data $item_number = $_POST['item_number']; $txn_id = $_POST['txn_id']; $payment_gross = $_POST['mc_gross']; $currency_code = $_POST['mc_currency']; $payment_status = $_POST['payment_status']; //Check if payment data exists with the same TXN ID. $prevPayment = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'"); if($prevPayment->num_rows > 0){ exit(); }else{ //Insert tansaction data into the database $insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')"); } }
Make PayPal Payment Gateway Live
When your application payment flow testing is completed, you need to modify two files to make PayPal payment gateway live.
Leave A Comment