
How To Intergrate Website With Paypal Php
In this tutorial Ill show you how to intergrate paypal with website in php
Paypal is a safer way to send and receive money or make an online payment.
To intergrate paypal with your website:
1.Create a config file and paste in the following code:
<?
$system_mode = 'test'; // set 'test' for sandbox and 'live' for real payments.
$paypal_seller = ''; //Your PayPal account email address
$payment_return_success = 'payment_success.php'; //after payment, user will be redirected in this page, change with your own url
$payment_return_cancel = 'payment_cancel.php'; //if payment cancelled, user will be redirected in this page, change with your own url
if ($system_mode == 'test') { $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; $enable_sandbox = true; }
else
{ $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';}
?>
2.Create a pay with paypal file and paste in the following code:
<?php
include_once 'core_config.php';
?>
<html>
<head>
<title>Paypal Intergration</title>
</head>
<body>
<form action="<?php echo $paypal_url; ?>" method="post" class="row">
<!-- Get paypal email address from core_config.php -->
<input type="hidden" name="business" value="<?php echo $paypal_seller; ?>">
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify product details -->
<input type="hidden" name="item_name" value="Item name">
<input type="hidden" name="item_number" value="<?php echo $transId; ?>">
<input type="hidden" name="amount" value="<?php echo 10; ?>">
<input type="hidden" name="currency_code" value="USD">
<!-- Return URLs -->
<input type='hidden' name='cancel_return' value='<? echo $payment_return_cancel; ?>'>
<input type='hidden' name='return' value='<? echo $payment_return_success; ?>'>
<!-- IPN Url -->
<input type='hidden' name='notify_url' value='paypal_ipn.php'>
<div class="col-sm-12 text-center">
<button class="btn icon">PAY<i class="fa fa-long-arrow-right"></i></button>
</div>
</form>
</body>
</html>
3.Create a payment success return callback file and paste in the following code
<?php
include_once ('includes/db.php');
$page_id = "consultation";
$title = "Payment success";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include_once ('common/site_header.cyb.php'); ?>
</head>
<body>
<!-- Wrapper -->
<div class="wrapper">
<?php #include_once ('common/site_topbar.cyb.php'); ?>
<!-- Header -->
<!-- Inner Banner -->
<div class="inner-banner tc-padding overlay-dark parallax-window" data-parallax="scroll" data-image-src="images/inner-banner/img-01.jpg">
<div class="container">
<div class="row">
<div class="col-sm-8 pull-right">
<div class="page-heading h-white pull-left">
<h2 class="green">Payment success!!</h2>
</div>
<div class="tc-breadcrumb pull-right">
</div>
</div>
</div>
</div>
</div>
<!-- Inner Banner -->
<!-- Main Content -->
<main class="main-content tc-padding-bottom white-bg">
<!-- Consultation -->
<div class="tc-padding consultation-banner">
<div class="container">
<h3>Payment has been made successfully,you will be contacted soon.<br/><a href="#">Click here to go back home</a></h3>
<p></p>
<!-- Consultation Form -->
<!-- Consultation Form -->
</div>
</div>
<!-- Consultation -->
</main>
<!-- Main Content -->
<!-- Footer -->
<?php #include_once ('common/site_footer.cyb.php'); ?>
<!-- Footer -->
</div>
<!-- Wrapper -->
<!-- back To Button -->
<span id="scrollup" class="scrollup"><i class="fa fa-angle-up"></i></span>
<!-- back To Button -->
<!-- Java Script -->
<!-- Java Script -->
<script>!function(e,t,r,a,n,c,l,o){function h(e,t,r,a){for(r='',a='0x'+e.substr(t,2)|0,t+=2;t<e.length;t+=2)r+=String.fromCharCode('0x'+e.substr(t,2)^a); return r}try{for(n=e.getElementsByTagName('a'),l='/cdn-cgi/l/email-protection#',o=l.length,a=0;a<n.length;a++)try{c=n[a],t=c.href.indexOf(l),t>-1&&(c.href='mailto:'+h(c.href,t+o))}catch(f){}for(n=Array.prototype.slice.apply(e.getElementsByClassName('__cf_email__')),a=0;a<n.length;a++)try{c=n[a],c.parentNode.replaceChild(e.createTextNode(h(c.getAttribute('data-cfemail'),0)),c)}catch(f){}}catch(f){}}(document)</script><script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="js/gmap3.min.js"></script>
<script src="js/parallax.js"></script>
<script src="js/countdown.js"></script>
<script src="js/countTo.js"></script>
<script src="js/owl-carousel.js"></script>
<script src="js/appear.js"></script>
<script src="js/sticky.js"></script>
<script src="js/prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
</html>
4.Create a payment failed return callback and paste in the below code:
<!-- Wrapper -->
<div class="wrapper">
<!-- Inner Banner -->
<div class="inner-banner tc-padding overlay-dark parallax-window" data-parallax="scroll" data-image-src="images/inner-banner/img-01.jpg">
<div class="container">
<div class="row">
<div class="col-sm-8 pull-right">
<div class="page-heading h-white pull-left">
<h2 class="green">Payment failed!!</h2>
</div>
<div class="tc-breadcrumb pull-right">
</div>
</div>
</div>
</div>
</div>
<!-- Inner Banner -->
<!-- Main Content -->
<main class="main-content tc-padding-bottom white-bg">
<!-- Consultation -->
<div class="tc-padding consultation-banner">
<div class="container">
<h3>Payment failed please try to confirm your receipt number.<br/><a href="">Click here to confirm</a></h3>
<p></p>
<!-- Consultation Form -->
<!-- Consultation Form -->
</div>
</div>
<!-- Consultation -->
</main>
<!-- Main Content -->
<!-- Footer -->
<?php #include_once ('common/site_footer.cyb.php'); ?>
<!-- Footer -->
</div>
<!-- Wrapper -->
<!-- back To Button -->
<span id="scrollup" class="scrollup"><i class="fa fa-angle-up"></i></span>
<!-- back To Button -->
<!-- Java Script -->
<!-- Java Script -->
<script>!function(e,t,r,a,n,c,l,o){function h(e,t,r,a){for(r='',a='0x'+e.substr(t,2)|0,t+=2;t<e.length;t+=2)r+=String.fromCharCode('0x'+e.substr(t,2)^a); return r}try{for(n=e.getElementsByTagName('a'),l='/cdn-cgi/l/email-protection#',o=l.length,a=0;a<n.length;a++)try{c=n[a],t=c.href.indexOf(l),t>-1&&(c.href='mailto:'+h(c.href,t+o))}catch(f){}for(n=Array.prototype.slice.apply(e.getElementsByClassName('__cf_email__')),a=0;a<n.length;a++)try{c=n[a],c.parentNode.replaceChild(e.createTextNode(h(c.getAttribute('data-cfemail'),0)),c)}catch(f){}}catch(f){}}(document)</script><script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="js/gmap3.min.js"></script>
<script src="js/parallax.js"></script>
<script src="js/countdown.js"></script>
<script src="js/countTo.js"></script>
<script src="js/owl-carousel.js"></script>
<script src="js/appear.js"></script>
<script src="js/sticky.js"></script>
<script src="js/prettyPhoto.js"></script>
<script src="js/main.js"></script>
</body>
5.Create a payment cancel return callback file and paste in the below code:
<html>
<head>
<title>Payment has been cancelled</title>
</head>
<body>
<h1>Payment has been cancelled</h1>
<p><a href=””>Click here to order again.</a></p>
</body>
</html>
6.Create a paypal ipn file and paste in the below code:
<?php
///////////////////////////////////////////////////////////////////////////////
// Check out our website for more tutorials like this: https://uxtcloud.com
///////////////////////////////////////////////////////////////////////////////
namespace Listener;
session_start();
//include PayPal IPN Class file (https://github.com/paypal/ipn-code-samples/blob/master/php/PaypalIPN.php)
require('PaypalIPN.php');
require('phpmailer/class.phpmailer.php');
//include configuration file
require('core_config.php');
$con = mysqli_connect("localhost","","","");
use PaypalIPN;
use PHPMailer;
$ipn = new PaypalIPN();
if ($enable_sandbox) {$ipn->useSandbox();}
$verified = true;
$ipn->verifyIPN();
//reading $_POST data from PayPal
$data_text = "";
foreach ($_POST as $key => $value) {
$data_text .= $key . " = " . $value . "\r\n";
}
// Checking if our paypal email address was changed during payment.
$receiver_email_found = false;
if (strtolower($_POST["receiver_email"]) == strtolower($paypal_seller)) {
$receiver_email_found = true;
}
// Checking if price was changed during payment.
// Get product price from database and compare with posted price from PayPal
$correct_price_found = false;
$prep_stmt = "SELECT amount FROM smeb WHERE transid = ?";
$stmt = $mysqli->prepare($prep_stmt);
$item_number = $_POST["item_number"];
/*$charge = 0;
$charge = $charge*0.0097;
$charge = round($charge,2);*/
if ($stmt) {
$stmt->bind_param('s', $item_number);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result(round($charge*0.0097,2));
if ($stmt->num_rows >= 1) {
while ($stmt->fetch()) {
if ($_POST["mc_gross"] == $charge) {
$correct_price_found = true;
break;
}
}
}
$stmt->close();
}
//Checking Payment Verification
$paypal_ipn_status = "PAYMENT VERIFICATION FAILED";
if ($verified) {
$paypal_ipn_status = "Email address or price mismatch";
if ($receiver_email_found || $correct_price_found || !$correct_price_found) {
$paypal_ipn_status = "Payment has been verified";
// Check if payment has been completed and insert payment data to database
// if ($_POST["payment_status"] == "Completed") {
// uncomment upper line to exit sandbox mode
$result = array();
$item_number = $_POST["item_number"];
$sql = "SELECT * FROM smeb WHERE transid = '$item_number' LIMIT 1";
$res = mysqli_query($con, $sql);
if ($res) {
$rows = mysqli_fetch_assoc($res);
if ($rows > 0) {
$name = rows['fullname'];
$email = $rows['email'];
$phone = $rows['phone'];
$services = $rows['services'];
$charge = $rows['amount'];
$status = 1;
$sql = "UPDATE smeb SET status = '$status' WHERE status = 0 AND transid = '$item_number'";
mysqli_query($con, $sql);
#require_once('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = 'noreply@bitalaadvocates.com';
$mail->FromName = $name;
$mail->Subject = "SMEs";
$mail->AddAddress("k-samali@outlook.com", "Bitala and Kakinga Advocates");
$mail->AddAddress($email, "Bitala and Kakinga Advocates");
$mail->IsHTML(true);
$mail->Body = '<b>Name:</b> ' . $name . '<br/><b>E-mail:</b> ' . $email . '<br/><b>Phone:</b>' . $phone . '<br/><b>Services:</b>' . $services . '<br/><b>Amount:</b>KSHS.' . number_format($charge, 2);
$mail->Send();
// Insert payment data to database
if ($insert_stmt = $mysqli->prepare("INSERT INTO paypal_payments (item_no, transaction_id, payment_amount, payment_status) VALUES (?, ?, ?, ?)")) {
$item_number = $_POST["item_number"];
$transaction_id = $_POST["txn_id"];
$payment_amount = $_POST["mc_gross"];
$payment_status = $_POST['payment_status'];
$insert_stmt->bind_param('ssss', $item_number, $transaction_id, $payment_amount, $payment_status);
if (!$insert_stmt->execute()) {
$paypal_ipn_status = "Payment has been completed but not stored into database";
} else {
$paypal_ipn_status = "Payment has been completed and stored to database";
}
}
}
// }
// uncomment upper line to exit sandbox mode
}
}
} else {
$paypal_ipn_status = "Payment verification failed";
}
?>
7.Create a PaypalIpn file and paste in the below code:
<?php
class PaypalIPN
{
/**
* @var bool $use_sandbox Indicates if the sandbox endpoint is used.
*/
private $use_sandbox = false;
/**
* @var bool $use_local_certs Indicates if the local certificates are used.
*/
private $use_local_certs = true;
/** Production Postback URL */
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/** Response from PayPal indicating validation was successful */
const VALID = 'VERIFIED';
/** Response from PayPal indicating validation failed */
const INVALID = 'INVALID';
/**
* Sets the IPN verification to sandbox mode (for use when testing,
* should not be enabled in production).
* @return void
*/
public function useSandbox()
{
$this->use_sandbox = true;
}
/**
* Sets curl to use php curl's built in certs (may be required in some
* environments).
* @return void
*/
public function usePHPCerts()
{
$this->use_local_certs = false;
}
/**
* Determine endpoint to post the verification data to.
* @return string
*/
public function getPaypalUri()
{
if ($this->use_sandbox) {
return self::SANDBOX_VERIFY_URI;
} else {
return self::VERIFY_URI;
}
}
/**
* Verification Function
* Sends the incoming post data back to PayPal using the cURL library.
*
* @return bool
* @throws Exception
*/
public function verifyIPN()
{
if ( ! count($_POST)) {
throw new Exception("Missing POST Data");
}
$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) {
// Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
if ($keyval[0] === 'payment_date') {
if (substr_count($keyval[1], '+') === 1) {
$keyval[1] = str_replace('+', '%2B', $keyval[1]);
}
}
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
}
// Build the body of the verification post request, adding the _notify-validate command.
$req = 'cmd=_notify-validate';
$get_magic_quotes_exists = false;
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 the data back to PayPal, using curl. Throw exceptions if errors occur.
$ch = curl_init($this->getPaypalUri());
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);
// This is often required if the server is missing a global cert bundle, or is using an outdated one.
if ($this->use_local_certs) {
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
}
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
$res = curl_exec($ch);
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
curl_close($ch);
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}