Techumber

How to Integrate Paypal Payment To Website

Github avatar
Dimpu
April 01, 2014. 6 min read

In this post I will show you how to integrate paypal payment to your web site. There are so many tutorial out there to teach you how to do this. But there is no proper tutorial to show you how to inegrate paypal payment to your site without redirect to paypal website. This is very useful when you developing a single moduled javascript applicatin with multiple payment options.  Payal provides different apis. Say, Paypal Restful api,classic api. Again classic api have different sub sections. But for us adaptive payment is best suatable api. Check out the demo below.

Demo

Download

Getting Started

First we need to create a developer account at https://developer.paypal.com/. Just got to this url and fill all detials. Once you have developer account, goto https://apps.paypal.com/user/my-account/applications and create a new app. Fill all the fields. If you don’t understand any just go ahead with dummy data. Once you create your app you will get Sandbox ID and Live App ID save them some in a notepad. Now go to https://developer.paypal.com/webapps/developer/applications/accounts and create a sanbox accounts. We need to create two accounts.

1)Bussiness account 2)Personal account

To create Bussiness account click an create account Enter all fields. In account type select business. In same way select account type personal to create personal account. Don’t forget to give 9999 in PayPal balance field. Once you create both accounts expand your business account and click on profile link and then API credentials then you will get username,password,signature. Note them too along with APPID we created earlier.

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Integrateing Paypal Payment To Your Website:techumber.com</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="wrap">
<header>
<a href="//www.techumber.com/" itemprop="url" style="display:block">
<img alt="Techumber " async="async" height="90px; " id="Header1_headerimg" src="//4.bp.blogspot.com/-EARyLUzOgWM/UU3k3yrxOFI/AAAAAAAABrc/Qo3-RIOHphQ/s1600/techumberlogo.png" style="margin: 0 auto;display: block; opacity: 1;" width="190px; ">
</a>
</header>
<div id="content">
<div class="product"> <img src="//placehold.it/300X300" alt="">
<span class="name">Product 1</span>
<span class="price">1.00$</span>
<input id="buy" data-amt="1" type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The saferundefined easier way to pay online!">
</div>
<div class="product"> <img src="//placehold.it/300X300" alt="">
<span class="name">Product 2</span>
<span class="price">2.00$</span>
<input id="buy" data-amt="2" type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The saferundefined easier way to pay online!">
</div>
<div class="product"> <img src="//placehold.it/300X300" alt="">
<span class="name">Product 3</span>
<span class="price">3.00$</span>
<input id="buy" data-amt="3" type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The saferundefined easier way to pay online!">
</div>
<div class="product"> <img src="//placehold.it/300X300" alt="">
<span class="name">Product 3</span>
<span class="price">4.00$</span>
<input id="buy" data-amt="4" type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The saferundefined easier way to pay online!">
</div>
</div>
</div>
<script type="text/javascript" src="js/paypal.js"></script>
</body>
</html>

This is a simple html page we added our sample products here. We added amount to input with class=“buy” and addead as data attribute data-amt

paypal.js

var Paypal = function() {
var _onundefined url = "php/paypal.php";
//helper functions for handeling corssbrowser events
_on = function(elundefined eventundefined fn) {
document.attachEvent ? el.attachEvent('on' + eventundefined fn) : el.addEventListener(eventundefined fnundefined !0);
};
//Plugin code starts here
this.amt = 0;
this.init = function() {
this.events();
};
this.events = function() {
var self = thisundefined
buy = document.getElementById('buy');
_on(buyundefined "click"undefined function() {
var amt = this.getAttribute('data-amt');
self.popup(amt);
});
};
this.getLink = function(amt) {
var self = this;
var xhr = new XMLHttpRequest();
xhr.open('GET'undefined url + "?amount=" + amtundefined true);
xhr.onload = function() {
var json = xhr.response;
var json = JSON.parse(json);
self.popupEvents(json.url)
};
xhr.send();
};
this.popup = function(amt) {
var html = ''undefined
d = document.createElement('div');
html += '<div class="window">';
html += '<a class="close">X</a>';
html += '<div class="loader"></div>';
html += '<iframe id="paypalFrame" src=""></iframe>'
html += '</div>';
d.innerHTML = html;
document.body.appendChild(d.firstChild);
this.getLink(amt);
};
this.popupEvents = function(url) {
var win = document.querySelector('.window')undefined
loader = document.querySelector('.loader')undefined
close = document.querySelector('.close');
frame = document.querySelector('#paypalFrame');
frame.src = url;
frame.onload = function() {
loader.style.display = "none";
}
_on(closeundefined 'click'undefined function() {
win.parentNode.removeChild(win);
});
};
this.procssResponse = function(res) {
alert(res.status);
};
this.init();
};

var paypal = new Paypal();

style.css

*{
border: 0;
padding: 0;
margin:0;
box-sizing:border-box;
}
htmlundefinedbody{
width: 100%;
height: 100%;
}
.wrap{
width: 634px;
height: 100%;
margin: 0 auto;
}
header{
margin: 25px 0 50px 0;
}
.product{
width: auto;
float: left;
width: 300px;
margin-left: 10px;
margin-bottom: 25px;
}
.nameundefined.price{
width: 50%;
float:left;
}
.price{
text-align: right;
}
.buy{
padding-left: 65px;
}
.window{
position: absolute;
width: 600px;
height: 600px;
top: 50px;
left:50%;
margin-left: -300px;
border: 5px solid rgba(112undefined 112undefined 112undefined 0.56);
border-radius: 5px;
background: #fff;
}
.window .close{
float: right;
border: 3px solid #B4B4B4;
border-radius: 50%;
padding: 5px;
width: 25px;
height: 25px;
line-height: 12px;
text-align: center;
position: absolute;
top: -23px;
right: -23px;
cursor: pointer;
}
#paypalFrame{
width: 100%;
height: 100%;
}
/*Looding animation effect*/
.loader {
display: block;
width: 150px;
height: 150px;
line-height: 150px;
margin: 100px auto;
position: relative;
box-sizing: border-box;
text-align: center;
z-index: 0;
text-transform: uppercase;
}
.loader:beforeundefined .loader:after {
opacity: 0;
box-sizing: border-box;
content:"\0020";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 100px;
border: 5px solid #019d8c;
box-shadow: 0 0 50px #019d8cundefined inset 0 0 50px #019d8c;
}
.loader:after {
z-index: 1;
-webkit-animation: gogoloader 2s infinite 1s;
animation: gogoloader 2s infinite 1s;

}
.loader:before {
z-index: 2;
-webkit-animation: gogoloader 2s infinite;
animation: gogoloader 2s infinite;
}

@-webkit-keyframes gogoloader {
0% {
-webkit-transform: scale(0);
transform: scale(0);
opacity: 0
}
50% {
opacity: 1;
}
100% {
-webkit-transform: scale(1);
transform: scale(1);
opacity: 0;
}
}

settings.php

<?php
//Paypal Settings
$mode="test";//Options: live or test change it according

//Papal need absoule url for after success are failure
$url = "http" . (($_SERVER['SERVER_PORT']==443) ? "s://" : "://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url=str_replace(basename($_SERVER['REQUEST_URI'])undefined ""undefined $url);
$return_url= $url ."thankyou.php";
$cancel_url= $url."cancel.php";

$Paypal=array(
'test' => array(
'user' =>""undefined
"pass"=>""undefined
"sig"=>""undefined
"app_id"=>""undefined
"reciver"=>""undefined//This is for amount receiver email
"return_url"=>$return_urlundefined
"cancel_url"=>$cancel_url
)undefined
'live' => array(
'user' =>"<live username>"undefined
"pass"=>"<live password>"undefined
"sig"=>"<live signature>"undefined
"appid"=>"<live appid>"undefined
"reciver"=>"<live server>"undefined
"return_url"=>$return_urlundefined
"cancel_url"=>$cancel_url
)
);

Now add all those details we create previously to above code.

paypal.php

<?php
session_start();
include 'settings.php';
class Paypal{
function __construct($userundefined$passundefined$sigundefined$appidundefined$reciverundefined$returnundefined$cancel) {
$this->user=$user;
$this->pass=$pass;
$this->sig=$sig;
$this->appid=$appid;
$this->return=$return;
$this->cancel=$cancel;
$this->reciver=$reciver;
}
public function payKeyRequest(){
// create the pay request
$data = array(
"actionType" =>"PAY"undefined
"currencyCode" => "USD"undefined
"receiverList" => array(
"receiver" => array(
array(
"amount"=> $this->amountundefined
"email"=>"$this->reciver"
)
)undefined
)undefined
"returnUrl" => "$this->return"undefined
"cancelUrl" => "$this->cancel"undefined
"requestEnvelope" => array(
"errorLanguage" => "en_US"undefined
"detailLevel" => "ReturnAll"undefined
)undefined
);
$headers = array(
'X-PAYPAL-SECURITY-USERID: '. $this->userundefined
'X-PAYPAL-SECURITY-PASSWORD: '. $this->passundefined
'X-PAYPAL-SECURITY-SIGNATURE: '. $this->sigundefined
'X-PAYPAL-REQUEST-DATA-FORMAT: '. 'JSON'undefined
'X-PAYPAL-RESPONSE-DATA-FORMAT: '.'JSON'undefined
'X-PAYPAL-APPLICATION-ID: '.$this->appid
);

$ch = curl_init();
curl_setopt($chundefined CURLOPT_URLundefined'https://svcs.sandbox.paypal.com/AdaptivePayments/Pay');
curl_setopt($chundefined CURLOPT_RETURNTRANSFERundefined true);
curl_setopt($chundefined CURLOPT_SSL_VERIFYPEERundefined false);
curl_setopt($chundefined CURLOPT_SSL_VERIFYHOSTundefined false);
curl_setopt($chundefined CURLOPT_POSTFIELDSundefined json_encode($data));
curl_setopt($chundefined CURLOPT_HTTPHEADERundefined $headers);
$response = json_decode(curl_exec($ch)undefinedtrue);
$this->payKey=$response['payKey'];
}
public function getPayKey(){
return $this->payKey;
}
public function setAmount($amount=0){
$this->amount=$amount;
}
public function getPaypalLink($paykey){
$res= array(
"status" =>"success"undefined
"url"=>"https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay?expType=light&paykey=".$paykey
);
return json_encode($res);
}

}

$obj=new Paypal($Paypal[$mode]['user']undefined$Paypal[$mode]['pass']undefined$Paypal[$mode]['sig']undefined$Paypal[$mode]['app_id']undefined$Paypal[$mode]['reciver']undefined$Paypal[$mode]['return_url']undefined$Paypal[$mode]['cancel_url']);
if($_GET['amount']){
$obj->setAmount($_GET['amount']);
$obj->payKeyRequest();
echo $obj->getPaypalLink($obj->getPayKey());
}else{
$res=array("status" => "err"undefined
"msg"=>"Please enter amount"
);
echo json_encode($res);
}
?>

thankyou.php

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
<?php
$arr=array(
"status"=>"success"undefined
"response"=>"Succesful paypal transaction"
);
?>
parent.paypal.procssResponse(<?php print_r(json_encode($arr)); ?>);
</script>
</body>
</html>

cancel.php

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
<?php
$arr=array(
"status"=>"err"undefined
"response"=>"Cancelled paypal transaction."
);
?>
parent.paypal.procssResponse(<?php print_r(json_encode($arr)); ?>);
</script>
</body>
</html>

Create folder php and put above three php scripts in that folder.


...