php tutorial - PayPal Express Checkout in PHP for Single Product - php programming - learn php - php code - php script



  • Express Checkout is a fast and very easy way for buyer to pay for the product they are buying.
  • In our previous blog post we have covered the PayPal Integration in PHP Using PDO using which you can sell products via PayPal securely without SDK.
  • But in this post we will be doing same task using PayPal PHP SDK with Express Checkout, which will help to collect more user information entered at the time of purchase.
  • According to PayPal adding the Express Checkout button to your website can increase your sales up to 18 percent.

Paypal Express Checkout for Single Product using PayPal PHP SDK

 paypal-express-checkout-single-product1

Learn php - php tutorial - paypal-express-checkout-single-product1 - php examples - php programs

PayPal Review Page Order Details

When a buyer logs in to PayPal to check out, you can present the buyer with detailed information about the item being purchased. PayPal order details are available with API version 53.0 or later.

The following diagram shows all of the details that you can include:

 paypal-review-page-order-details

Learn php - php tutorial - paypal-review-page-order-details - php examples - php programs

  1. Product name
  2. Showing Product prize
  3. Showing product quantity
  4. Total payable amount.

Tutorial Scripts in detail:

Below are the details of the code used in this tutorial with proper explanation.

MY-SQL Code

CREATE TABLE IF NOT EXISTS `tbl_product_detail` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`item_number` varchar(255) NOT NULL,
`product_name` varchar(255) NOT NULL,
`product_img` varchar(255) NOT NULL,
`product_price` varchar(255) NOT NULL,
`product_currency` varchar(255) NOT NULL,
`product_dec` text NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
click below button to copy the code. php tutorial - team

Connection.php

This is the file used for database connectivity. It is used for making connection variable by PDO (PHP Data Objects).

<?php
function connection_open() {
// Database credential
$servername = "localhost";
$username = "root";
$password = "";
//Data base name
$dbname = "express_chekout";
try {
global $conn;
// Open the connection using PDO.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// echo $sql . "<br>" . $e->getMessage();
die();
}
}
function connection_close() {
global $conn;
$conn = null;
}
?>
click below button to copy the code. php tutorial - team

Function.php

This file contains all required function for database operation.

<?php
//This function is used for fetching all the records from the table
function Select_All_Records($table_name) {
global $conn;
$sql = "select * from $table_name";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}
//This function is used for fetching record with one Filter.
function Select_Record_By_One_Filter($data,$table_name){
global $conn;
$key = array_keys($data);
$value = array_values($data);
$sql = "select * from $table_name where $key[0] = '$value[0]'";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}
?>
click below button to copy the code. php tutorial - team

Bootstrap.php

This file help to load and connect PayPal PHP SDK with your application.

<?php
// Include the composer Autoloader
// The location of your project's vendor autoloader.
$composerAutoload = 'PayPal-PHP-SDK/autoload.php';
if (!file_exists($composerAutoload)) {
//If the project is used as its own project, it would use rest-api-sdk-php composer autoloader.
$composerAutoload = 'PayPal-PHP-SDK/vendor/autoload.php';
if (!file_exists($composerAutoload)) {
echo "The 'vendor' folder is missing. You must run 'composer update' to resolve application dependencies.\nPlease see the README for more information.\n";
exit(1);
}
}
require $composerAutoload;
require __DIR__ . '/common.php';

use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

error_reporting(E_ALL);
ini_set('display_errors', '1');

// Replace these values by entering your own ClientId and Secret by visiting https://developer.paypal.com/webapps/developer/applications/myapps
$clientId = 'Your PayPal App Id';
$clientSecret = 'Your PayPal App Secret';
$mode = 'sandbox';

/** @var \Paypal\Rest\ApiContext $apiContext */
$apiContext = getApiContext($clientId, $clientSecret);

return $apiContext;

function getApiContext($clientId, $clientSecret) {

// ### Api context
// Use an ApiContext object to authenticate
// API calls. The clientId and clientSecret for the
// OAuthTokenCredential class can be retrieved from
// developer.paypal.com

$apiContext = new ApiContext(
new OAuthTokenCredential(
$clientId, $clientSecret
)
);

// Comment this line out and uncomment the PP_CONFIG_PATH
// 'define' block if you want to use static file
// based configuration
global $mode;
$apiContext->setConfig(
array(
'mode' => $mode,
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => 'DEBUG', // PLEASE USE `FINE` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
'validation.level' => 'log',
'cache.enabled' => true,
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
)
);

// Partner Attribution Id
// Use this header if you are a PayPal partner. Specify a unique BN Code to receive revenue attribution.
// To learn more or to request a BN Code, contact your Partner Manager or visit the PayPal Partner Portal
// $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', '123123123');
return $apiContext;
}
click below button to copy the code. php tutorial - team

Index.php

This is the first file showing products details.

<?php
include('include/function.php');
include('include/connection.php');
echo connection_open();
?>
<html>
<head>
<title>Paypal Express Checkout for single product using PayPal PHP SDK</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/popup-style.css" />
<script src="js/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<div id = "main">
<h1>PayPal Express Checkout : Single Product</h1>
<?php
//Select_All_Records function is used for fetching all the records from the table
$query = Select_All_Records('tbl_product_detail');
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $query->fetch()) {
?>
<div id = "login">
<h2><?php echo $result['product_name']; ?></h2>
<hr/>
<form action = "process.php" method = "post">
<input type = "hidden" value = "<?php echo $result['item_number']; ?>" name = "product_id">
<img id = "product_img" src = "images/<?php echo $result['product_img']; ?>"/><br><br>
<div id = "product_content">
<h4 style="margin: 0px;">Description</h4>
<p><?php echo $result['product_dec']; ?></p>
</div>
<input type = "submit" value = " Buy Now $ <?php echo $result['product_price']; ?> " id="submit" name = "submit"/><br />
<span></span>
</form>
</div>
<?php } ?>
<img id="paypal_logo" style="margin-left: 722px;" src="images/secure-paypal-logo.jpg">
</div>
//This Pop-Up will called when we click on Buy Now Button
<div id="pop2" class="simplePopup">
<div id="loader"><img src="images/ajax-loader.gif"/><img id="processing_animation" src="images/processing_animation.gif"/></div>
</div>
<script src="js/jquery.simplePopup.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('input#submit').click(function() {
$('#pop2').simplePopup();
});
});
</script>
</body>
</html>
click below button to copy the code. php tutorial - team

Process.php

This file contains code to process payment to PayPal.

<?php
require __DIR__ . '/bootstrap.php';

use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;

include('include/function.php');
include('include/connection.php');
if (isset($_POST['submit'])) {
echo connection_open();
if (isset($_POST['product_id'])) {
$product_id = base64_decode($_POST['product_id']);
$data = array(
'product_id' => $product_id
);
$query = Select_Record_By_One_Filter($data, 'tbl_product_detail');
$query->setFetchMode(PDO::FETCH_ASSOC);
$result = $query->fetch();
$product_name = $result['product_name'];
$product_price = $result['product_price'];
$product_currency = $result['product_currency'];
echo connection_close();
}
// ### Payer
// A resource representing a Payer that funds a payment
// For paypal account payments, set payment method
// to 'paypal'.
$payer = new Payer();
$payer->setPaymentMethod("paypal");

// ### Itemized information
// (Optional) Lets you specify item wise
// information
$item1 = new Item();
$item1->setName($product_name)
->setCurrency($product_currency)
->setQuantity(1)
->setPrice($product_price);

$itemList = new ItemList();
$itemList->setItems(array($item1));

// ### Additional payment details
// Use this optional field to set additional
// payment information such as tax, shipping
// charges etc.
$details = new Details();
$details->setShipping(0)
->setTax(0)
->setSubtotal($product_price);

// ### Amount
// Lets you specify a payment amount.
// You can also specify additional details
// such as shipping, tax.
$amount = new Amount();
$amount->setCurrency($product_currency)
->setTotal($product_price)
->setDetails($details);

// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it.
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());

// ### Redirect urls
// Set the urls that the buyer must be redirected to after
// payment approval/ cancellation.
$baseUrl = getBaseUrl();
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("http://localhost/express-checkout-single-product/success.php?success=true")
->setCancelUrl("http://localhost/express-checkout-single-product/index.php");

// ### Payment
// A Payment Resource; create one using
// the above types and intent set to 'sale'
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
// For Sample Purposes Only.
$request = clone $payment;
// url to which the buyer must be redirected to
// for payment approval
try {
$payment->create($apiContext);
} catch (Exception $ex) {
//ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
exit(1);
}

// ### Get redirect url
// The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $payment->getApprovalLink()
// method
$approvalUrl = $payment->getApprovalLink();
header('Location: ' . $approvalUrl);
}
?>
click below button to copy the code. php tutorial - team

Success.php

PayPal calls this file when payment gets successfully completed and provide detailed transaction information as response in json format.

<?php
require __DIR__ . '/bootstrap.php';

use PayPal\Api\ExecutePayment;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;

// ### Approval Status
// Determine if the user approved the payment or not
if (isset($_GET['success']) && $_GET['success'] == 'true') {
// Get the payment Object by passing paymentId
// payment id was previously stored in session in
// CreatePaymentUsingPayPal.php
$paymentId = $_GET['paymentId'];
$payment = Payment::get($paymentId, $apiContext);

// ### Payment Execute
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);
$result = $payment->execute($execution, $apiContext);
$obj = json_decode($payment);
?>
<html>
<head>
<title>Paypal Express Checkout for single product using PayPal PHP SDK</title>
<link rel = "stylesheet" type = "text/css" href = "css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("a.Show").click(function() {
$("div#return").css({'overflow': 'scroll'});
$("a.Show").hide();
$("a.hide").show();

});
$("a.hide").click(function() {
$("div#return").css({'overflow': 'hidden'});
$("a.Show").show();
$("a.hide").hide();

});
});
</script>
</head>
<body>

<div id="main">
<h1>PayPal Express Checkout : Single Product</h1>
<div id="return">
<h2>Payment Detail</h2>
<hr/>
<a href="index.php"><img style="float: left;" title="Back To Product" src="images/back.png"></a><a class="show" ><img title="Show All Paypal's Returned Data" style="float: right;"src="images/down.png"></a><a class="hide" style="display: none;" ><img title="Hide Paypal's Returned Data" style="float: right;"src="images/up.png"></a>
<div class="clearfix"></div>
<br/>
<ul>
<li><?php echo "Id --> " . $obj->id ?></li>
<li><?php echo "create_time --> " . $obj->create_time ?></li>
<li><?php echo "update_time --> " . $obj->update_time ?></li>
<li><?php echo "state --> " . $obj->state ?></li>
<li><?php echo "intent --> " . $obj->intent ?></li>
<li>payer</li>
<ul>
<li><?php echo "payment_method --> " . $obj->payer->payment_method ?></li>
<li>payer_info</li>
<ul>
<li><?php echo "email --> " . $obj->payer->payer_info->email ?></li>
<li><?php echo "first_name --> " . $obj->payer->payer_info->first_name ?></li>
<li><?php echo "last_name --> " . $obj->payer->payer_info->last_name ?></li>
<li><?php echo "payer_id --> " . $obj->payer->payer_info->payer_id ?></li>
<li><?php echo "shipping_address" ?></li>
<ul>
<li><?php echo "line1 --> " . $obj->payer->payer_info->shipping_address->line1 ?></li>
<li><?php echo "city --> " . $obj->payer->payer_info->shipping_address->city ?></li>
<li><?php echo "state --> " . $obj->payer->payer_info->shipping_address->state ?></li>
<li><?php echo "postal_code --> " . $obj->payer->payer_info->shipping_address->postal_code ?></li>
<li><?php echo "country_code --> " . $obj->payer->payer_info->shipping_address->country_code ?></li>
<li><?php echo "recipient_name --> " . $obj->payer->payer_info->shipping_address->recipient_name ?></li>
</ul>
</ul>
</ul>
<li>transactions</li>
<ul>
<li>amount</li>
<ul>
<li><?php echo "total --> " . $obj->transactions[0]->amount->total ?></li>
<li><?php echo "currency --> " . $obj->transactions[0]->amount->currency ?></li>
<li>details</li>
<ul>
<li><?php echo "subtotal --> " . $obj->transactions[0]->amount->details->subtotal ?></li>
</ul>
</ul>
<li><?php echo "description --> " . $obj->transactions[0]->description ?></li>
<li>item_list</li>
<ul>
<li>items</li>
<ul>
<li><?php echo "name --> " . $obj->transactions[0]->item_list->items[0]->name ?></li>
<li><?php echo "price --> " . $obj->transactions[0]->item_list->items[0]->price ?></li>
<li><?php echo "currency --> " . $obj->transactions[0]->item_list->items[0]->currency ?></li>
<li><?php echo "quantity --> " . $obj->transactions[0]->item_list->items[0]->quantity ?></li>
</ul>
<li>shipping_address</li>
<ul>
<li><?php echo "recipient_name --> " . $obj->transactions[0]->item_list->shipping_address->recipient_name ?></li>
<li><?php echo "line1 --> " . $obj->transactions[0]->item_list->shipping_address->line1 ?></li>
<li><?php echo "city --> " . $obj->transactions[0]->item_list->shipping_address->city ?></li>
<li><?php echo "state --> " . $obj->transactions[0]->item_list->shipping_address->state ?></li>
<li><?php echo "postal_code --> " . $obj->transactions[0]->item_list->shipping_address->postal_code ?></li>
<li><?php echo "country_code --> " . $obj->transactions[0]->item_list->shipping_address->country_code ?></li>
</ul>
</ul>
<li>related_resources</li>
<ul>
<li>sale</li>
<ul>
<li><?php echo "id --> " . $obj->transactions[0]->related_resources[0]->sale->id ?></li>
<li><?php echo "create_time --> " . $obj->transactions[0]->related_resources[0]->sale->create_time ?></li>
<li><?php echo "update_time --> " . $obj->transactions[0]->related_resources[0]->sale->update_time ?></li>
<li>amount</li>
<ul>
<li><?php echo "total- -> " . $obj->transactions[0]->related_resources[0]->sale->amount->total ?></li>
<li><?php echo "currency- -> " . $obj->transactions[0]->related_resources[0]->sale->amount->currency ?></li>
</ul>
<li><?php echo "payment_mode- -> " . $obj->transactions[0]->related_resources[0]->sale->payment_mode ?></li>
<li><?php echo "state- -> " . $obj->transactions[0]->related_resources[0]->sale->state ?></li>
<li><?php echo "protection_eligibility- -> " . $obj->transactions[0]->related_resources[0]->sale->protection_eligibility ?></li>
<li><?php echo "protection_eligibility_type- -> " . $obj->transactions[0]->related_resources[0]->sale->protection_eligibility_type ?></li>
<li><?php echo "parent_payment- -> " . $obj->transactions[0]->related_resources[0]->sale->parent_payment ?></li>
<li>transaction_fee</li>
<ul>
<li><?php echo "value --> " . $obj->transactions[0]->related_resources[0]->sale->transaction_fee->value ?></li>
<li><?php echo "currency --> " . $obj->transactions[0]->related_resources[0]->sale->transaction_fee->currency ?></li>
</ul>
<li>links</li>
<ul>
<li><?php echo "href --> " . $obj->transactions[0]->related_resources[0]->sale->links[0]->href ?></li>
<li><?php echo "rel --> " . $obj->transactions[0]->related_resources[0]->sale->links[0]->rel ?></li>
<li><?php echo "method --> " . $obj->transactions[0]->related_resources[0]->sale->links[0]->method ?></li>
</ul>
<ul>
<li><?php echo "href --> " . $obj->transactions[0]->related_resources[0]->sale->links[1]->href ?></li>
<li><?php echo "rel --> " . $obj->transactions[0]->related_resources[0]->sale->links[1]->rel ?></li>
<li><?php echo "method --> " . $obj->transactions[0]->related_resources[0]->sale->links[1]->method ?></li>
</ul>
<ul>
<li><?php echo "href --> " . $obj->transactions[0]->related_resources[0]->sale->links[2]->href ?></li>
<li><?php echo "rel --> " . $obj->transactions[0]->related_resources[0]->sale->links[2]->rel ?></li>
<li><?php echo "method --> " . $obj->transactions[0]->related_resources[0]->sale->links[2]->method ?></li>
</ul>
</ul>
</ul>
</ul>

</ul>
</div>
<!-- Right side div -->
<div id="wiki">
<a href=https://www.wikitechy.com/app><img src="images/wikitechy.jpg" alt="Online Form Builder"/></a>
</div>
</div>
</body>
</html>
<?php } ?>
 
click below button to copy the code. php tutorial - team

Style.css

Includes basic styling of HTML elements.

@import url(http://fonts.googleapis.com/css?family=Raleway);

#main{
width: 950PX;
margin: 50PX auto;
font-family:raleway;
}
span{
color:red;
}
h1{
margin-left: 14%;
}
#return {
width: 492px;
height: 350px;
float: left;
border-radius: 10px;
font-family: raleway;
border: 2px solid #ccc;
padding: 10px 40px 11px;
margin: 16PX;
}
h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
}
hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 30px;
}
#login{
width: 200px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 11px;
margin: 16PX;
}
input[type=text],input[type=password]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
#profile{
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7;
}
#logout{
float:right;
padding:5px;
border:dashed 1px gray;
}
a{
text-decoration:none;
color: cornflowerblue;
}
i{
color: cornflowerblue;
}
ul{
line-height: 22px;
}
#product_img{
width: 210px;

height: 230px;
}
#product_content{
width: 198px;
height: 116px;
padding: 10px;
margin-bottom: 23px;
font-size: 14px;
border: 1px solid rgba(128, 128, 128, 0.17);
}
#return{
width: 585px;
height: 507px;
float: left;
border-radius: 10px;
font-family: raleway;
border: 2px solid #ccc;
padding: 10px 40px 30px;
margin: 16PX;
overflow: hidden;
}
#return h3#success{
text-align: center;
font-size: 24px;
margin-top: 50px;
color: green;
}
#return h3#fail{
text-align: center;
font-size: 24px;
margin-top: 50px;
color: red;
}
#btn{
width: 100%;
background-color: #FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px 70px;
font-size: 20px;
cursor: pointer;
border-radius: 5px;
margin-bottom: 15px;
margin: 0 auto;
}
#return .back_btn{
margin-top: 51px;
margin-left: 19%;
}
#return P{
margin-left: 122px;
}
#wiki{
float:right;
margin-top: 20px;
}
#loader
{
margin-left: 8%;
margin-bottom: 45px;
}
#loader #processing_animation {
width: 70%;
height: 12%;
}
ul li{
margin-left: 90px;
}
#return img:hover{
opacity: .4;
}
 
click below button to copy the code. php tutorial - team


Related Searches to PayPal Express Checkout in PHP for Single Product