PHP PayPal ExpressCheckout Tutorial
![]()
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.
<?php session_unset(); session_start(); ?> <html> <head> <title>Test PayPal Transaction</title> <link href="main.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrap"> <h1>International PayPal PRRT™ Home Study Course Order Page</h1> <form action="ReviewOrder.php" method="POST"> First Name <input type="text" name="firstName" /> Last Name <input type="text" name="lastName" /> Email <input type="text" name="customerEmail" /> Phone <input type="text" name="customerPhone" /> <input type="hidden" name="paymentType" value="sale" > <input type="hidden" name="paymentAmount" value="217.00" /> <input type="hidden" name="currencyCodeType" value="USD" /> <input type="submit" value="Pay $217 with PayPal" name="submitted" /> </form> </div> </body> </html>
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.
<?php 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.
<?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 */ ?> <html> <head> <title>Test PayPal Transaction</title> <link href="main.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrap"> <form action="DoExpressCheckoutPayment.php"> <table width="450" border="0" cellspacing="0" cellpadding="5"> <tr> <td>Order Total</td> <td><?php echo $_REQUEST['paymentAmount'];?>   <?php echo $_REQUEST['currencyCodeType'];?></td> </tr> <tr> <td>Shipping Address</td> <td><?php echo $resArray['SHIPTOSTREET']; ?><br /><?php echo $resArray['SHIPTOSTREET2']; ?></td> </tr> <tr> <td>City</td> <td><?php echo $resArray['SHIPTOCITY']; ?></td> </tr> <tr> <td>State</td> <td><?php echo $resArray['SHIPTOSTATE']; ?></td> </tr> <tr> <td>Postal ZIP Code</td> <td><?php echo $resArray['SHIPTOZIP']; ?></td> </tr> <tr> <td>Country</td> <td><?php echo $resArray['SHIPTOCOUNTRYNAME']; ?></td> </tr> </table> <input type="submit" value=" Submit Order" /> </form> </div> </body> </html>
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.
<?php 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 <website@brendenwilson.com>\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); ?> <html> <head> <title>SuperSpine, Inc.</title> <link href="sdk.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrap"> <strong> Your payment has been processed. Thank you. </strong> <table width="400"> <tr> <td >Transaction ID:</td> <td><?php echo $resArray['TRANSACTIONID']; ?></td> </tr> <tr> <td>Amount:</td> <td><?php echo $resArray['AMT']; ?><?php echo $currCodeType?> </td> </tr> </table> </div> </body> </html>
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
Offical PayPal PHP Samples
Brenden Wilson Samples
Screenshots
This ones
must not be there you can add them into the php code $paymentType = “sale” … because the value and other things can be changed very easy
Pretty good, tutorial. PayPal API is quite complicated!
cigraphics, he knows that, and says it’s not secure that way at the end of the tutorial
Good tutorial though, helped me out a lot.
Has anybody used my code successfully?
Hi Brenden,
I was unable to understand paypal API as it was mixed. But your pages worked great for sandbox account as they was. I had to update constants only (not a big deal). I do appreciate your effors! Thank you very much….. cheers!!!
hello guys.. im new to programming and I wanted to try these scripts that you made. but I always have an error on CallerService.php on line 45..
Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\paypal-expresscheckout\CallerService.php on line 45
how do I get rid of these? thanks ^_^
Do you have cURL setup?
hi xenoz,
just open php.ini file and search curl word then remove ; from that line which is first character.
hi xenoz,
just open php.ini file and search curl word then remove ; from that line which is first character .
Brenden: Hello! Thank you for putting together this tutorial. I am in the finishing stages of putting together a commercial website-my first one. Since my coding skills are fair at best, your tutorial has been VERY helpful. Actally it is the best one I have yet found on the Internet. Thank you again. ~Robert
αγαπη με kaKh00b2j2eVI αγαπη για
pharmacy medications canadian pharmacy with canadian
Good One for starters. Excellent work. Thanks