Community Pick: Many members of our community have endorsed this article.

How To Implement a PayPal Buy Now button and live happy

Marco GasiFreelancer
Freelance, I like to share what I know. Find out my articles in my learner-to-learners blog
Surfing the Internet, I noticed that many programmers and web developers have problems with implementing a PayPal "Buy Now" button. Let me say that I'm not a PayPal developer, nor a guru of informatic science or a genius of programming art... But I needed to insert a Buy Now button in a my site and I found a simple way to do it.

So I decided to write a simple, little article to share this little piece of knowledge. Before to start, I have to say that this is not an exhaustive tutorial about implementing PayPal functions and options in a Web site. I only describe a step-by-step procedure to:

1. use in a web page a PayPal Buy Now button (from here BNB) in order to send our customer to PayPal site (other payment options will not be considered);
2. let our customer use PayPal site to pay our product even if he has not a PayPal account;
3. make our customer to return to our site automatically;
4. receive from PayPal the confirmation that transaction has been succsfully completed using PDT and a PHP script included in our site (IPN will not be treated);
5. test all procedure using PayPal Sandbox.  
Of course, I'll assume you have a PayPal account: if you don't have it, I suggest you to create a new one before to proceed.

1. Creating a PayPal Buy Now button.

Make Login your PayPal. In the horizontal tabbed menu click 'PayPal Merchant Services', then click 'Sell single items' and then follow these steps:

      - Fill in Item name box and provide (optionally) an unique ID for it
      - Choose price and currency values
      - Set the postage cost, if needed
      - choose the email address to receive payement notifications

      - Check 'Save button at Paypal'
      - Leave unchecked other options (only because I've not tested yet: feel free to
        use them if you need them)
      Set following options accordingly to your needs
        - Do you want to let your customer change order quantities?
        - Can your customer add special instructions in a message to you?
        - Need your customer's postal address?
        - Take customers to this URL when they cancel their checkout

Set following option with the exact url of the page of your Web site wich contains the script that will process the order and will update database, will allow a download and so on... For our examples we'll call this page ''. Be sure to check the box
        - Take customers to this URL when they finish checkout

Well, all done. Now you have to click 'Create button' and you'll get the code to insert in your page: select the code copy it and paste it where you wish your button will appear.

Now, you have to set up all preferences for Website Payment Preferences. Go back to the PayPal home page, the one that appears after you logged in. There, under the horizontal tabbed menu, with My Account tab selected, you'll see the menu item 'Profile'. Moving your mouse over it, a second v ertical menu will appear but this is not interesting for us: click 'Profile'.

In this way you'll be redirected to My Profile page. Here there are three columns: 'Account Information', 'Financial Information', 'Selling Preferences'. In the last one column look for 'Website Payment Preferences' and click it. In the new page you'll see there are several options to set. First af all, to answer to your question, scroll the page and look for 'Payment Data Transfer (optional)' section (is near the top of the page): be sure to turn On this option and get your Identity Token.

About the other options, be sure its are set as following instructions:

- Auto Return for Website Payments:
    - On
    - Return URL: the page you wish your customer will be redirected to. we call this page

- Encrypted Website Payments
  - I don't use it so I have set it to Off

- PayPal Account Optional
  - On

- Contact Telephone Number
  - I don't use it so I have set it to Off (reccomended by Paypal)

- PayPal Express Checkout Settings
  -  Set to No

Well, that's all. Remember that the page you use in Return URL option must be the same set in BNB configuration.

2. The script

BNB has to be placed in the page where is your product description. The script you find in the box code below has to be placed in the page your customer will be redirected to by PayPal system when he will complete transaction (or when he will decide not to buy, sigh!). In our example, this page is ''.

Obviously, this script has to be included or inserted in a web page in the exact point where you wish messages appear.

3. PayPal Sandbox

Now, all is ready to make us reach and happy but... it will work fine? PayPal give us a chance to test our code quite easily, the PayPal Sandbox. Direct your browser to and you'll see a page very similar to the PayPal login page. You are requested to signup to PayPal Sandbox so to create an account. Once you have your Sandbox account and you are logged in, you have to create two test user: the first one will be the ghost-buyer the second one the ghost-seller. Look for 'Test accounts' just in front of you. Click 'Create a preconfigured buyer or seller account.' and follow easy steps to create a new buyer account. When you have created the first account you are redirected to the Test accounts page. Here click 'Home' in the left menu and repeat all steps to create a new seller account.

When you are creating these two test user, be sure to take note of usernames and passwords: you'll need them soon. The ghost-seller will simulate your real seller account. How? Go in the test user page, select the ghost-seller account and click the 'Test this account' button below. A popup window will appear and you'll be prompted to login: use username and password of your ghost-seller account. Once you are logged in, repeat all steps you have done in the real world of PayPal site. Click 'PayPal Merchant Services', then click on 'Sell single items' and so on.

During this process copy the code to insert the button in your site and take note of your sandbox token.

Now you can close the ghost-seller account window.

Once you have created your sandbox BNB and you have setup Website Payment Preferences, you have to make some changes in your site. First, you have to replace the original BNB code with the one you have taken in Sandbox. Second, in the script in ppreturn.php go to line where you found your token:

$auth_token = "your_paypal_token";

and add this line immediately below:

$auth_token = "your_sandbox_token";

Then comment the line with the PayPal token and leave uncommented the line with sandbox token. When you'll have tested your selling system you'll have to invert comment (commenting sandbox token and uncommenting PayPal token).

Finally, open in your browser the page of your website where is the (sandbox) Buy Now button and click it. You'll be redirected to the sandbox site and you'll have to login using your ghost-buyer account username and password. Complete this simulated transaction and if it's all right you'll be redirected to your ppreturn.php page where you'll see transaction data and your own-written message.

Well, as Warners said, that's all, folks! Good coding.
                      $req = 'cmd=_notify-synch';
                      $tx_token = $_GET['tx'];
                      $auth_token = "your_paypal_token";
                      $req .= "&tx=$tx_token&at=$auth_token";
                      $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
                      $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
                      $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
                      $fp = fsockopen ('', 80, $errno, $errstr, 30);
                      if (!$fp) {
                          exit ("You don't come from Paypal site. Please, complete transaction in Paypal.");
                      } else {
                        //verifies if token is correct and retrieves transaction data from PayPal
                          fputs ($fp, $header . $req);
                          $res = '';
                          $headerdone = false;
                          while (!feof($fp)) {
                              $line = fgets ($fp, 1024);
                              if (strcmp($line, "\r\n") == 0){
                                  $headerdone = true;
                              } else if ($headerdone){
                                  $res .= $line;
                          $lines = explode("\n", $res);
                          $keyarray = array();
                          if (strcmp ($lines[0], "SUCCESS") == 0) {
                      	  //if transaction was successfull insert data in a database (optional), print a message
                      	  //to inform customer about transaction data (recomended) and optionally redirect to another page
                      	  //i.e. to allow to download a file
                              for ($i=1; $i<count($lines);$i++){
                                  list($key,$val) = explode("=", $lines[$i]);
                                  $keyarray[urldecode($key)] = urldecode($val);
                              $firstname = $keyarray['first_name'];
                              $lastname = $keyarray['last_name'];
                              $itemname = $keyarray['item_name'];
                              $email = $keyarray['payer_email'];
                              $amount = $keyarray['mc_gross'];
                              $country = $keyarray['residence_country'];
                              $payerid = $keyarray['payer_id'];
                              $txn_id = $keyarray['txn_id'];
                              $status = $keyarray['payment_status'];
                              $query = "INSERT INTO your_customers_table (firstname, lastname, email)
                                  VALUES('$firstname', '$lastname', '$email')";
                              $result = @mysql_query($query);
                              if (!$result){mysql_error();}
                              echo ("<center><h3>Thank you for your purchase!</h3></center>");
                              echo ("<p>Your transaction has been completed, and a receipt for your purchase has
                                                     been emailed to you.<br>You may log into your account at <a href=''>
                                           </a> to view details of this transaction.<br><br /></p>");
                              echo ("<p><b>Payment Details</b></p>");
                              echo ("<ul><li>First name: $firstname</li>");
                              echo ("<li>Item: $itemname</li>");
                              echo ("<li>Amount: $amount</li>");
                              echo ("<li>Last name: $lastname</li>");
                              echo "<li>Residence Country: $country</li>";
                              echo "<li>Buyer email: $email</li>";
                              echo "<li>Buyer id: $payerid</li>";
                              echo "<li>Transaction id: $txn_id</li>";
                              echo "<li>Transaction status: $status</li>";
                              echo ("</ul>");
                              echo ("");
                      		//otherwise print a message to inform customer that something has gone wrong, ofering support and so on
                      		echo "Your transaction has not been successfully completed. Please contact the Administrator.";
                          fclose ($fp);

Open in new window

Marco GasiFreelancer
Freelance, I like to share what I know. Find out my articles in my learner-to-learners blog

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.