browser lang:en
There are two different ways to use the PayPal API. The first, is the PayPal Direct Payment. PayPal Direct Payment will allow the customer to simply type in their information including their credit card number and process it invisibly through PayPal on your website. If you use this method, it appears that all orders are being processed without PayPal. The second method is the PayPal Express Checkout. Express Checkout allows the customer to purchase something on a website, pay for it on the PayPal website and then return to initial website to complete the transaction. PayPal Express Checkout is definitely ideal for international customers.
I have included sample code based off of PayPal’s code. PayPal jumbled all of it’s ExpressCheckout and DirectPayment code together so I have separated it. If you want to download PayPal’s code, you can do so in the Merchant area of your PayPal account. In this tutorial I will explain the code included in my sample code. Go ahead and download my code which is attached at the bottom of this post before you start.
Ok so here we go…
The attached zip file should include 8 different files. I will explain the purpose of each file.
index.php
This is the file that initiates the PayPal transaction. session_unset() unsets all the variables stored in the session. Sessions work just like normal PHP variables except instead of storing the variable information on the server, it is stored on the viewers PC. Sessions work especially nicely for PayPal because it allows you to collect customer information on your website, then exit to the PayPal website to authorize payment, and then return your website to confirm payment and submit the customer information collected on the first page. So the first two lines of code start the session. The first deletes information from previous orders processed the customers computer and then a new session is started. The HTML form on this page collects the customers First Name, Last Name, Email and Phone Number. There are a few hidden fields that identify the product price, the currency type (which is USD or United States Dollars) and the payment type. You can find more information about Payment Type in the PayPal documentation but basically there are three options to choose from. Sale is the option set in this example and is ideal for the order of a single item. The other options allow you to use the PayPal shopping cart or identify multiple items in a single order. When the form is submitted, the information is sent to ReviewOrder.php.
session_unset();
session_start();
ReviewOrder.php
This is the most complicated page and it is executed twice. When the order information (customer information and PayPal information) is sent from the index.php page, the customer is redirected to the PayPal website where the transaction is authorized, but not processed. The customer returns to the ReviewOrder.php page where the transaction is completed. On completion, GetExpressCheckoutDetails.php is displayed.
The first part of the code starts the sessions and includes two files. The CallerService.php won’t ever need to be modified. The constants.php file includes user specific details. When your finished testing you will need to edit a few things in the constants.php to take the script out of testing mode. After the files have been included, a few variables are set. If the user just submitted information on the index page (see the “if statement”) than their first name, last name and email address is stored in the Session variables so we can use it later. Then the customer is sent to the PayPal page where they login and authorize the transaction. Once the transaction is authorized, PayPal sends the customer back to the ReviewOrder.php page. The page code is run again, but this time the Session variables aren’t set because the customer didn’t from the index.php page. PayPal sends $token back, so the $token variable is set which means the “else statement” runs which is about half way through the script. If the transaction is authorized by PayPal, then the GetExpressCheckoutDetails.php page is displayed.
session_start();
require_once 'CallerService.php';
require_once 'constants.php';
$submitted = $_POST['submitted'];
if( isset($submitted) ) {
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['customerEmail'] = $_POST['customerEmail'];
}
$token = $_REQUEST['token'];
if(! isset($token)) {
$serverName = $_SERVER['SERVER_NAME'];
$url=dirname('http://'.$serverName.$_SERVER['REQUEST_URI']);
$paymentAmount=$_REQUEST['paymentAmount'];
$currencyCodeType=$_REQUEST['currencyCodeType'];
$paymentType=$_REQUEST['paymentType'];
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType.'&paymentAmount='.$paymentAmount);
$cancelURL =urlencode("$url/index.php?paymentType=$paymentType" );
$nvpstr="&Amt=".$paymentAmount."&PAYMENTACTION=".$paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType;
/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
$resArray=hash_call("SetExpressCheckout",$nvpstr);
$_SESSION['reshash']=$resArray;
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS"){
// Redirect to paypal.com here
$token = urldecode($resArray["TOKEN"]);
$payPalURL = PAYPAL_URL.$token;
header("Location: ".$payPalURL);
} else {
//Redirecting to APIError.php to display errors.
$location = "APIError.php";
header("Location: $location");
}
} else {
/* At this point, the buyer has completed in authorizing payment
at PayPal. The script will now call PayPal with the details
of the authorization, incuding any shipping information of the
buyer. Remember, the authorization is not a completed transaction
at this state - the buyer still needs an additional step to finalize
the transaction
*/
$token =urlencode( $_REQUEST['token']);
/* Build a second API request to PayPal, using the token as the
ID to get the details on the payment authorization
*/
$nvpstr="&TOKEN=".$token;
/* Make the API call and store the results in an array. If the
call was a success, show the authorization details, and provide
an action to complete the payment. If failed, show the error
*/
$resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
$_SESSION['reshash']=$resArray;
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS"){
require_once "GetExpressCheckoutDetails.php";
} else {
//Redirect to APIError.php to display errors.
$location = "APIError.php";
header("Location: $location");
}
}
GetExpressCheckoutDetails.php
This is basically the confirmation page. After customer has agreed to pay for the product, the details of the order are displayed and the customer confirms the order on this page. At the top of this page the session is again started and then session variables are set. PayPal sends a bunch of information back with the customer and all this information is stored in the Session variables. Then a form is displayed with all the PayPal and customer information. If the customer approves the order then the PayPal transaction will be processed by DoExpressCheckoutPayment.php.
session_start();
/* Collect the necessary information to complete the
authorization for the PayPal payment
*/
$_SESSION['token']=$_REQUEST['token'];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount']=$_REQUEST['paymentAmount'];
$_SESSION['currCodeType']=$_REQUEST['currencyCodeType'];
$_SESSION['paymentType']=$_REQUEST['paymentType'];
$resArray=$_SESSION['reshash'];
/* Display the API response back to the browser .
If the response from PayPal was a success, display the response parameters
*/
DoExpressCheckoutPayment.php
This page finalizes the PayPal order and displays the results to the customer. An email is then sent to the store owner with some basic information.
require_once 'CallerService.php';
session_start();
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
$token =urlencode( $_SESSION['token']);
$paymentAmount =urlencode ($_SESSION['paymentAmount']);
$paymentType = urlencode($_SESSION['paymentType']);
$currCodeType = urlencode($_SESSION['currCodeType']);
$payerID = urlencode($_SESSION['payer_id']);
$serverName = urlencode($_SERVER['SERVER_NAME']);
$nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'& IPADDRESS='.$serverName ;
/* Make the call to PayPal to finalize payment
If an error occured, show the resulting errors
*/
$resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
$ack = strtoupper($resArray["ACK"]);
if($ack!="SUCCESS"){
$_SESSION['reshash']=$resArray;
$location = "APIError.php";
header("Location: $location");
}
//Send an HTML email to the store owner.
$message = "A PayPal order has been processed. Check PayPal for shipping directions.";
$headers = "From: Name \r\n”;
$headers .= “Content-Type: text/html;\r\n charset=”iso-8859-1″\r\n”;
mail(”YOUR EMAIL HERE!”,”Website: PayPal Order Processed”,”$message”, $headers);
| Transaction ID: | |
| Amount: |
Security Notes
This is tutorial is intended to be an educational tool. I’m not responsible for any problems you have. The code is optimized for learning purposes and not security. Please understand this.
If you would like to increase your security, do not include the pricing information in hidden inputs on the index page. It would be best to include them predefined on the ReviewOrder.php page at the top where the initial session variables are defined.
Attached Files
Selective Tweets is an application that allows you to control what tweets are added to your Facebook…
in:Social Networking (0 comments)In a FBML Facebook App, your quick jump menu will require a little tweak to work in FBJS…
in:Scripts and tutorials (0 comments)Every single day, someone, somewhere is discussing something important to your business; your brand, your executives, your…
in:Scripts and tutorials (0 comments)Although some IT managers are coming around to the idea of supporting iPhones, most aren’t convinced…
in:Free Software (0 comments)When you want to run your own mail server, and it does not matter what version and…
in:Apache - .htaccess (0 comments)Have you ever had to develop something yourself only to find out that there had already been…
in:JQuery (0 comments)The situation begins with your blog or website and you need to post some code on a particular…
in:The Holy Faq's (0 comments)So. Google just recently announced Google Buzz. I’m not sure about you, but I…
in:Blog (0 comments)
