Paypalphpcoding
Paypalphpcoding
This tutorial will help you to integrate PayPal payment gateway using PHP with an example.
1. How to integrate PayPal payment gateway in your application and process payments.
2. What is PayPal IPN, why you should use it and an example implementation.
3. How to test PayPal payment gateway integration using PayPal sandbox.
In this example, we will use “PayPal Payments Standard” method for integrating the paymen
What is inside?
1. How it works?
2. Payment gateway integration steps
3. File Structure
4. About PHP example to integrate payment using PayPal Payments Standard
5. Database Script
6. Go live
7. Payment gateway integration output
How it works?
PayPal payment gateway integration steps
1. Render PayPal payment form HTML with required parameters and “custom Pay Now butt
2. Set the suitable values for the form fields to fill up item information, merchant email id, ca
3. Set suitable form action with PayPal sandbox/live URL endpoint to which the payment de
4. Handle payment response in IPN listener to update database or to send email to the cust
5. Acknowledge user appropriately with the return/cancel page after payment cycle.
If you wish to process card payments refer the Stripe payment gateway integration using PHP articles.
File structure
Below screenshot shows the file structure of this PHP example code created for integrating P
The landing page shows an entry point for proceeding with the PayPal payment transaction
The return.php and the cancel.php files are the acknowledgement pages to which the user w
DBController.php file contains the code to create database connection object and to handle
In this HTML code we can see the PayPal Payments Standard form fields with a custom Pay
The PayPal payment form must contain the business email address, order information like it
By submitting this form, the payment parameters will be posted to the PayPal server. So, the
<body>
<div id="payment-box">
<img src="images/camera.jpg" />
<h4 class="txt-title">A6900 MirrorLess Camera</h4>
<div class="txt-price">$289.61</div>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr"
method="post" target="_top">
<input type='hidden' name='business'
value='PayPal Business Email'> <input type='hidden'
name='item_name' value='Camera'> <input type='hidden'
name='item_number' value='CAM#N1'> <input type='hidden'
name='amount' value='10'> <input type='hidden'
name='no_shipping' value='1'> <input type='hidden'
name='currency_code' value='USD'> <input type='hidden'
name='notify_url'
value='http://sitename/paypal-payment-gateway-integration-in-php/notify.php'>
<input type='hidden' name='cancel_return'
value='http://sitename/paypal-payment-gateway-integration-in-php/cancel.php'>
<input type='hidden' name='return'
value='http://sitename/paypal-payment-gateway-integration-in-php/return.php'>
<input type="hidden" name="cmd" value="_xclick"> <input
type="submit" name="pay_now" id="pay_now"
Value="Pay Now">
</form>
</div>
</body>
PayPal Notifications
PayPal provides notifications using different mechanisms. It will be useful for updating your
1. Webhooks
2. IPN
3. PDT
Notifications should be used as part of the payment gateway integration process. Imagine y
You should not do this in the thank-you page. As there is no guarantee that this page will b
The dependable way of doing this is using PayPal notifications. You get a callback from PayP
PayPal notifies the merchants about the events related to their transactions. This automatic
Notifications are done by PayPal on different type of events like, payments received, authori
An integral part of the payment gateway integration process in the ability to receive PayPal
The order fulfillment is an important step in a shopping cart software. It should be done via the PayPal notification and never s
The notify.php is created as the instant payment notification listener. This listener URL will be sent to PayPal via the form seen
This listener will be called asynchronously by PayPal to notify payment processing response
Below code verifies the payment status from the response returned by PayPal. If the paymen
<?php
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 1);
define("LOG_FILE", "ipn.log");
// Read POST data
// reading posted data directly from $_POST causes serialization
// issues with array data in POST. Reading raw POST data from input stream instead.
$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
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE)
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." fo
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
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) {
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
include("DBController.php");
$db = new DBController();
}
// process payment and mark item as paid.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>
DBController.php
This file handles database related functions using prepared statement with MySQLi. This is im
<?php
class DBController
{
private $conn;
function __construct()
{
$this->conn = $this->connectDB();
}
function connectDB()
{
$conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
return $conn;
}
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}
if (! empty($resultset)) {
return $resultset;
}
}
Database script
This section shows the payment database table structure in .sql format. This is provided with
--
-- Table structure for table `payment`
--
Test! Test! Test! It is important. We are processing payments and you cannot be casual abou
PayPal provides excellent toolset to perform the end to end testing of the payment gateway
Testing the IPN is critical as it takes care of the order fulfilment process. Go through the belo
Go live
Once everything is working good with the entire payment transaction processing flow, then
1. Replace the sandbox business account email with live email address.
define("USE_SANDBOX", 1);
Below screenshot shows the product tile which includes PayPal payments standard form and
After successful payment transaction, the user will be automatically redirected to the return
The return url is nothing but a thank you page or order completion page. This is the last ste
An important thing to know is that the order fulfilment steps should not be done sequential
PHP with an example. I will walk you through a step by step process and make it easy for you do the
process payments.
eated for integrating Payment Gateway using PayPal Payments Standard method.
l payment transaction process. It will show a sample product tile containing PayPal payment fields fo
ges to which the user will be redirected appropriately. The notify.php is the IPN listener connect datab
ds with a custom Pay Now button. This example code targets the PayPal sandbox URL on the form ac
der information like item_number, name, amount, currency, and the callback and return page URLs.
e PayPal server. So, the user will be redirected to the PayPal Login and asked for payment confirmatio
eful for updating your backend processes, sending order notification and similar transactional jobs. F
on process. Imagine you are running a website that sells digital goods online. At the end of the paym
e that this page will be displayed in the user’s browser. There can be network failures, user’s might cl
et a callback from PayPal to your backend server (asynchronously) and you can manage the backend
ctions. This automatic callback can be used to perform administrative tasks and to fulfil orders.
ments received, authorizations made, recurring payments, subscriptions, chargebacks, disputes, revers
PayPal notification and never should be done as part of the thank you or order completion page.
nt to PayPal via the form seen above. It can also be set in the PayPal REST API app settings. Paypal provides the IPN listener code samples
cannot be casual about this implementation. Every bit of your PHP script should be tested thoroughl
the payment gateway integration. It provides a sandbox environment using which you can simulate
s. Go through the below steps to setup a PayPal Sandbox account and test you PHP code for payme
processing flow, then it will be a time to go live with your PayPal payment gateway integration using
nts standard form and custom Pay Now button.
directed to the return URL as specified in the payment form. The return page will acknowledge the u
age. This is the last step in the payment gateway integration process.
ot be done sequentially in the return URL call. It should be done via the IPN callback or the other Pay
it easy for you do the integration.
yPal payment fields following by a Pay Now button.
r payment confirmation.
ar transactional jobs. Following are the different types of notifications provided by PayPal.
At the end of the payment process, you are obliged to send the digital product via email.
ailures, user’s might close the browser and there are so many variables involved in this.
to fulfil orders.
hich you can simulate the complete payment process including the payments and fulfillments step.
eway integration using PHP code. Change the sandbox mode to live mode and do the following.
ill acknowledge the user as shown below.
via email.
ecurity of the application.
nd fulfillments step.
do the following.
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Share
Improve this answer
Follow
answered May 21 2018 at 5:12
Snowbases
2,11022 gold badges1818 silver badges2424 bronze badges
1
worked like a charm. Thanks for the answer :)
– Utpal - Ur Best Pal
Jul 13 2021 at 20:57
Add a comment
3
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
Share
Improve this answer
Follow
answered Dec 18 2010 at 23:45
Jakub
20.2k88 gold badges6363 silver badges9292 bronze badges
2
It's called an associative array, not a multidimensional array.
– BoltClock
Dec 18 2010 at 23:46
Add a comment
2
You can use array_merge to combine two arrays and then iterate over them.
Share
Improve this answer
Follow
answered May 17 2012 at 15:38
Haider Ali
84822 gold badges88 silver badges2525 bronze badges
Add a comment
2
All fully tested
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
<?php
</select>
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
CommunityBot
111 silver badge
answered Aug 7 2013 at 7:50
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
or combine
in select
demo
Share
Improve this answer
Follow
edited Mar 28 2014 at 1:30
answered Mar 25 2014 at 5:59
oLinkWebDevelopment
1,7411414 silver badges88 bronze badges
Add a comment
2
<?php
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
Share
Improve this answer
Follow
answered Sep 7 2015 at 2:19
r5d
57755 silver badges2424 bronze badges
Add a comment
2
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a
each() returns information about the current key and value of the array and increments the internal pointer by one
Share
Improve this answer
Follow
answered Jan 6 2017 at 18:53
PerceptorII
11911 gold badge11 silver badge55 bronze badges
Add a comment
2
Instead of foreach loop, try this (only when your arrays have same length).
Share
Improve this answer
Follow
answered Mar 12 2017 at 14:45
fchan
2111 bronze badge
Add a comment
1
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an at
Share
Improve this answer
Follow
edited Dec 21 2012 at 0:04
Dave Clemmer
3,7671212 gold badges4848 silver badges7272 bronze badges
answered Dec 20 2012 at 23:45
Calin Rusu
1111 bronze badge
Add a comment
1
I think that you can do something like:
$codes = array('tn','us','fr');
pashri
2133 bronze badges
Add a comment
1
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
Share
Improve this answer
Follow
answered Jul 16 2016 at 8:13
SeReGa
88788 silver badges2626 bronze badges
Add a comment
0
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}
if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}
$doors[$a]
$windows[$a]
....
}
Share
Improve this answer
Follow
answered Feb 7 2013 at 3:10
Gvice
38522 silver badges1010 bronze badges
Add a comment
0
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
Share
Improve this answer
Follow
answered Feb 19 2013 at 13:34
Ulugov
33733 silver badges99 bronze badges
Add a comment
0
You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty
@endforeach `
Share
Improve this answer
Follow
answered Mar 2 2015 at 10:43
JADAV AKASH
922 bronze badges
Add a comment
0
Few arrays can also be iterated like this:
Share
Improve this answer
Follow
answered Oct 20 2015 at 8:27
Тарас Костюк
322 bronze badges
Add a comment
0
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db
$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};
$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
Share
Improve this answer
Follow
answered Oct 30 2021 at 8:22
vivek raju
1
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how thi
– CommunityBot
Oct 30 2021 at 11:32
Add a comment
-2
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}
Share
Improve this answer
Follow
answered Jul 17 2013 at 16:44
mcjarod
1
Add a comment
Your Answer
$error3 = $_REQUEST['address'];
$error4 = $_REQUEST['email'];
re going about this wrong:
n from an array.
se the each() function in a while loop:
the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays