How to setup Paypal IPN using PHP

Instant Payment Notification allows you to integrate your PayPal payments with your website's backend operations, so you get immediate notification and authentication of the PayPal payments you receive. Its easy to do this.

Requirement:
  • Paypal seller account (Live or Sandbox). How to  create sandbox account. Click Here
  • Basic Knowledge of PHP and Mysql
  • A running website for example (www.s2ptech.com)
  •  Make a folder on web server, for example paypal.(www.s2ptech.com/paypal)
  • Free Time: 10 Minutes
Lets Start. Follow these steps:

Front End Page:

This is a page where you can do any payment.
Index.php
<title>Paypal IPN Payment Gateway</title>

<form action="paypalverified.php" method="post" name="frmfunds">
<select class="ns_quarter-1" name="currency_id" id="currency_id">
    <option selected="selected" value="USD">USD</option>
</select>

<input type="text" id="fund_ammount" name="fund_ammount" class="ns_quarter-1"/>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="item_name" value="Item Name">
<input type="hidden" name="item_number" value="123">
<input type="hidden" name="currency_code" value="USD"/>
<input type="submit" name="DepositMoney" class="submit3" value="Deposit Money" />
</form>
 Copy this script in any text editor and save as "index.php". Where "index" can be any word.
 Paste this page in paypal folder. Your page url will be www.s2ptech.com/paypal/index.php. Copy this url in address box of any browser and run.

Oh! this page is redirecting to www.s2ptech.com/paypal/paypalverified.php. No page Found error comes. Actually you have not created paypalverified.php page.

Next Create a paypalverified.php  page and save to paypal folder.

paypalverified.php

<?php
session_start();
    if($_POST['DepositMoney'])
    {
        $paypal_email = 'Enter Your Paypal Email ID';
        $paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr';
       $return_url = 'YOUR URL/paypal/payment-successful.php';             
        $cancel_url = 'YOUR URL/paypal/payment-cancel.php';
        $notify_url = 'YOUR URL/paypal/notify_url.php';
        $item_name = $_POST['item_name'];
        $item_amount = $_SESSION['fund_amt'];
        $querystring .= "?business=".urlencode($paypal_email)."&";   
        $querystring .= "USER=".urlencode("")."&";
        $querystring .= "PWD=".urlencode("")."&";
        $querystring .= "SIGNATURE=".urlencode("")."&";
        $querystring .= "identity_token=".urlencode("")."&";
        $querystring .= "item_name=".urlencode($item_name)."&";
        $querystring .= "amount=".urlencode($_POST['fund_ammount'])."&";
        foreach($_POST as $key => $value)
        {
            $value = urlencode(stripslashes($value));
            $querystring .= "$key=$value&";
        }
        $querystring .= "return=".urlencode(stripslashes($return_url))."&";
        $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
        $querystring .= "notify_url=".urlencode($notify_url);
        @header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);                       
    }
?>

Replace colored text with your live or Sandbox email Id

Replace colored text with "https://www.paypal.com/cgi-bin/webscr" If  you use Live Paypal id 

Replace colored "YOUR URL" with "http://www.s2ptech.com" for return_url, cancel_url and notify_url.

There is a question for you.

Q. What is Return url, Cancel url and Notify url?

Don't go anywhere to search.

Return Url: When a payment is complete from paypal sandbox successfully. You will redirect to your website automatically. You can select that page by return url.

Cancel Url: When a payment failed due to any reason. You will redirect to your website on cancel url page.

Notify Url: When a customer makes a payment to you or a payment is reversed or refunded, PayPal will post a notification to your server at the URL you specified. Included in this notification will be all your customer’s payment information (e.g. customer name, payment amount) as well as a piece of encrypted code. When your server receives a notification, it will then post the information, including the encrypted code, back to a secure PayPal URL. PayPal will authenticate the transaction and send confirmation of its validity back to your server.



notify_url.php

<?php
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value)
{
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

// post back to PayPal system to validate

$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";

// If testing on Sandbox use:
$header .= "Host: www.sandbox.paypal.com:443\r\n";
//$header .= "Host: www.paypal.com:443\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

// If testing on Sandbox use:

$fp =fsockopen('ssl://www.sandbox.paypal.com',443,$err_num,$err_str,30);
          //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
echo('<br>'.$req);
// assign posted variables to local variables



$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];



if (!$fp)
{
    echo(' HTTP ERROR');
}
else
{
    fputs ($fp, $header . $req);
    while (!feof($fp))
    {
        $res = fgets ($fp, 1024);
        echo('<br> res is '.$res);
    if (strcmp ($res, "VERIFIED") == 0)
    {
        // check the payment_status is Completed
        // check that txn_id has not been previously processed
        // check that receiver_email is your Primary PayPal email
        // check that payment_amount/payment_currency are correct
        // process payment
                 /*Above data transfer to this page. When a payment complete successfully.
                    VERIFIED means payment completed successfully.
                    You can do anything with this data. For example,Store data into database, Email to Clients.

*/
         $mail_From = "From: YOUR EMAIL ID";
        $mail_To = $_POST['payer_email'];
        $mail_Subject = "VERIFIED IPN";
        $mail_Body = $req;
        foreach ($_SESSION as $key => $value)
        {
            $emailtext .= $key . " = " .$value ."\n\n";
        }
        mail($mail_To, $mail_Subject, $emailtext . "\n\n" . $mail_Body, $mail_From);
      
      
        mysql_connect('HOST NAME', 'USER NAME', 'PASSWORD') or exit(0);
        mysql_select_db('DATABASE NAME') or exit(0);
        $payer_email = mysql_real_escape_string($_POST['payer_email']);
        $mc_gross = mysql_real_escape_string($_POST['mc_gross']);
        $sql = "INSERT INTO orders VALUES (NULL, '$txn_id', '$payer_email', $mc_gross)";
      
        if (!mysql_query($sql)) {
        error_log(mysql_error());
        exit(0);
        }
      
      
        $fh = fopen('result.txt', 'w');
        fwrite($fh, $mail_Subject.' -- '.$req);
        fclose($fh);
            }
    else if (strcmp ($res, "INVALID") == 0)
    {
        // log for manual investigation
        $mail_From = "From: mubarik.galaxyweb@gmail.com";
        $mail_To = "mukeshdas1985@gmail.com";
        $mail_Subject = "INVALID IPN";
        $mail_Body = $req;
        foreach ($_SESSION as $key => $value)
        {
            $emailtext .= $key . " = " .$value ."\n\n";
        }
        mail($mail_To, $mail_Subject, $emailtext . "\n\n" . $mail_Body, $mail_From);
        $fh = fopen('result.txt', 'w');
        fwrite($fh, $mail_Subject.' -- '.$req);
        fclose($fh);
    }
}
fclose ($fp);
}

?>

payment-successful.php


<div id="signup">
<div><h2 style="color:#144D98;">Congratulation ! Fund Transfered Into Your  Account.</h2></div>
<div><h3>Your have successfully Addedd Fund into Your  Acount.</h3></div>
<div>Your Deposited Funds <strong>:</strong> $<?php echo $_GET['amt'];?></div>
<div class="clear"></div>
</div>
payment-cancel.php
<div id="signup">
<div><h2 style="color:#144D98;">Sorry ! You canceled the Payment.</h2></div>
<div class="clear"></div>
</div>

Scripting section completd. But some major things remains. Click Here To go into next section.

0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment