php paypal Integration

Here is the code that would help you to implement paypal in your php website.It is a simple code that you could use in your site and make a paypal run shopping cart easily.

Create an account in sandbox.paypal.com and create a buyer and seller account in it then do as follows:

1. Creating paypal form

<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr" target="paypal">
    <input type="hidden" name="cmd" value="_cart"> <!-- if paypal cart -->
    <input type="hidden" name="cmd" value="_xclick"> <!-- if paypal buy now -->
    <input type="hidden" name="cmd" value="_xclick-subscriptions"> <!-- if paypal subscription -->
    <input type="hidden" name="add" value="1">
    <input type="hidden" name="business" value="seller_1350878263_biz@gmail.com"> <!-- seller email --> 
    <input type="hidden" name="custom" value="package"/> <!-- custom field -->
    <input type="hidden" name="item_name" value='item name'> <!-- item name -->
    <input type="hidden" name="item_number" value='32'> <!-- item number -->
    <input type="hidden" name="amount" value="30.00"> <!-- price -->
    <input type="hidden" name="shipping" value="0.00"> <!-- shipping price  -->
    <input type="hidden" name="handling" value="0.00"> <!-- handling price  -->
    <input type="hidden" name="currency_code" value="USD"> <!-- currency -->
    <input type="hidden" name="notify_url" value="paypal_process.php"> <!-- database entry,co,putation after payment is done by this page -->
    <input name="return" value="payment_success.php" type="hidden"> <!-- user redirected to this page after payment -->
    <input name="cancel_return" value="cancel.php" type="hidden"> <!-- user redirected to this page if cancelled payment  -->
    <input type="hidden" name="undefined_quantity" value="1"> <!-- With Buy Now buttons, you can require buyers to specify the desired quantity of the item by using the undefined_quantity HTML variable: -->
    <input type="image" src="http://www.paypalobjects.com/en_US/i/btn/x-click-but22.gif" border="0" name="submit" width="87" height="23" alt="Make payments with PayPal - it's fast, free and secure!">
    </form> 



 2 . Download IPN Listener

Download the files from here and place it in your webdirectory, we need to include ipnlistener.php in one of our file. (Courtesy:  Micah Carrick)




3. paypal.class.php to validate the ipn and data

<?php
include('ipnlistener.php'); // ipnlisteneris the file which we downloaded in previous step
class paypal_auth
{
      private $listener;
      private $admin_mail;
      private $primarymail;
      function __construct()
      {
             $this->admin_mail="adminmail@domain.com"; // the email where you wish to receive the status report
             $this->primarymail="seller_1350878263_biz@gmail.com"; // ur paypal seller mail
             $this->listener = new IpnListener(); // creating an object of IpnListener
             $this->listener->use_sandbox = true; // 'true' if using sandbox, 'false' otherwise
      }

      /* function to validate ipn */
      function validate_ipn()
      {
             try
             {
                  $this->listener->requirePostMethod();
                  $verified = $this->listener->processIpn();
             } 
             catch (Exception $e)
             {
                error_log($e->getMessage());
                exit(0);
             }
             return $verified; // 'false'if not valid 'true' if valid 
      }
      function check_ipn($data)
      {
    
        if(!($this->validate_ipn()))
                {
                        return "invalid ipn";
                        exit;
                }
                $errmsg = '';   // stores errors from fraud checks
        
        // 1. Make sure the payment status is "Completed" 
        if ($data['payment_status'] != 'Completed')
                { 
            // simply ignore any IPN that is not completed
            exit(0); 
        }
        
        // 2. Make sure seller email matches your primary account email.
        if ($data['receiver_email'] != $this->primarymail)
                {
            $errmsg .= "'receiver_email' does not match: ";
            $errmsg .= $data['receiver_email']."\n";
        }
        
        // 3. Make sure the amount(s) paid match
        if(!(check_price($data['item_number'],$data['mc_gross'],$data['quantity']))) //check_price()is a function to check the price of the commodity from database) 
                {
            $errmsg .= "'mc_gross' does not match: ";
            $errmsg .= $data['mc_gross']."\n";
        }
        
        // 4. Make sure the currency code matches
        if ($data['mc_currency'] != 'USD') {
            $errmsg .= "'mc_currency' does not match: ";
            $errmsg .= $data['mc_currency']."\n";
        }
                else
                { 
                        $errmsg=$errmsg."noerror";
                }
                $status=array();
                $status['error']=$errmsg;
                $status['report']=$this->listener->getTextReport();
                $status['txn_id']=$data['txn_id'];
                return $status;
        // TODO: Check for duplicate txn_id
        
        
        } 
      
}

4. Finally paypal_process.php to do all the computation when payment is made.


<?php
session_start();
include('paypal.class.php');// checks for fraud in ipn
$paypal=new paypal_auth();//object of paypal.class


//IF PAYPAL CART
//-----------------------------------------------------------------------
if($_POST['txn_type']=="cart")
{
   
        for($i=1;$i<($_POST['num_cart_items']+1);$i++) // cart there would be more than one items so loop through
    {
        /* paypal informations */
        $data=$_POST;  // We store all the post variables in an arraynamed $data
        $status=$paypal->check_ipn($data); // checking ipn
        if($status['error']!="noerror") // in case of fraud ipn not validated
        {
           
            $errorstatus['error']=$status['error'];
            $errorstatus['report']=$status['report'];
            $errorstatus['ip']=$_SERVER['REMOTE_ADDR']; 
            mail("youremail@domain.com", 'IPN Fraud Warning', $status['error']); 
            mail("youremail@domain.com", 'IPN Fraud Warning', $status['report']); 
        }
        else
        {
            // things to be done after successful payment   
        }
    }
} 


//IF PAYPAL SUBSCRIBE
//----------------------------------------------------------------------------
else if($_POST['txn_type']=='subscr_payment')
{
        $data=$_POST;  // We store all the post variables in an arraynamed $data
    $status=$paypal->check_ipn($data); //checking IPN
    if($status['error']!="noerror") // in case of fraud ipn not validated
    {
        $errorstatus['error']=$status['error'];
            $errorstatus['report']=$status['report'];
            $errorstatus['ip']=$_SERVER['REMOTE_ADDR']; 
            mail("youremail@domain.com", 'IPN Fraud Warning', $status['error']); 
        mail("youremail@domain.com", 'IPN Fraud Warning', $status['report']); 
    }
    else
    {
        // things to be done after successful payment       
    }
         
          
}

//IF PAYPAL BUY NOW
//------------------------------------------------------------------------------------
else if($_POST['txn_type']=='express_checkout')
{
  
    $data=$_POST;  // We store all the post variables in an arraynamed $data
    $status=$paypal->check_ipn($data); //checking IPN,all the pos
    if($status['error']!="noerror") // in case of fraud ipn not validated
    {
        $errorstatus['error']=$status['error'];
            $errorstatus['report']=$status['report'];
            $errorstatus['ip']=$_SERVER['REMOTE_ADDR']; 
            mail("youremail@domain.com", 'IPN Fraud Warning', $status['error']); 
        mail("youremail@domain.com", 'IPN Fraud Warning', $status['report']); 
    }
    else
    {
        // things to be done after successful payment       
    }
   
}

?>


Paypal list of postitems

payment_status                 -              'completed when payment complete'
first_name                     -              'firstname of the buyer'
last_name                      -              'lastname of the buyer'
payer_email                    -              'email of the buyer'
receiver_email                 -              'seller email'
item_number                    -              'item number'
mc_gross                       -              'total price payed'
mc_currency                    -              'currency'
custom                         -              'custom field value'
ipn_track_id                   -              'unique track id'
receiver_id                    -              'receiver id'
txn_id                         -              'unique transaction id usually stored by the buyer in db'
subscr_id                      -              'unique subscriber id in case of subscription (stored in db)' 
verify_sign                    -              'unique id'
payer_id                       -              'id of the payer'
quantity                       -              'no of items bought' 



6 comments:

  1. what a fantastic and bomblastic explanation, hats off to the cooling glass fellow in browser tab.

    ReplyDelete
  2. sir, I serched a more time in the day to find how to do the paypal sir . u very very good explanation sir. thank you very much sir. u r very brillant sir

    ReplyDelete
  3. @Anoop This sir seems to be the king of PHP. He is gret , Respect with Salutes.

    ReplyDelete
  4. I have never seen such an easy and informative tutorial on paypal integration. Thank you so much sir. Keep posting amazing tutorials like this! I salute you Sir.

    ReplyDelete
  5. This is my second comment for this awesome tutorial just for thanking you sir... You are great sir.. Can you embed your picture in your tutorials? We are planning to start a fan page for you in facebook sir.. Please sir...

    ReplyDelete
  6. Very useful tutorial. Thanks buddy. :)

    ReplyDelete