How to use PayPal Instant Payment Notification for e-commerce Website?

In this part, we are going to learn about PayPal Instant Payment Notification (IPN).

IPN is a message service that notifies you of events related to PayPal transactions. You can use IPN to automate back-office and administrative functions. As the name says Instant Payment Notification, it really is instant. The moment a customer buys a product from your website using PayPal, IPN reaches your server within few seconds.

The process is shown in the following image (Copied from PayPal)

When a customer buys your product, PayPal sends the transaction detail to the IPN URL provided by you.

Lets write a code to handle IPN

        $req = 'cmd=_notify-validate';
        //Collect the variables sent by PayPal
        foreach ($_POST as $key => $value) {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";

        //Send them back to PayPal to verify whether they are authentic or not
        $paypal_action = '';
        //For PayPal Sandbox: $paypal_action = '';
        $ch = curl_init($paypal_action);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
        $result = curl_exec($ch);

        //If PayPal verified the posted data
        if (strcmp ($result, "VERIFIED") == 0) {
            $transaction_id = $_POST['txn_id'];
            $payment_status = $_POST['payment_status'];
            $item_name = $_POST['item_name'];
            $amount = $_POST['mc_gross'];
            $quantity = $_POST['quantity'];
            $fee_deducted = $_POST['mc_fee'];
            $payer_email = $_POST['payer_email'];
            $payment_date = $_POST['payment_date'];

            //Check the payment status
            switch($payment_status) {
                case 'Processed':
                    //Processed and Completed are almost same. Perform the action for successful payment.

                case 'Completed':
                    //Perform the action for successful payment.

                case 'Pending':
                     //Perform the action for pending payment status.


        else {
            //Perform the action for invalid IPN.

Lets see what we have done so far.

PayPal sends the transaction details to our server. To check whether, PayPal sent this data, we need to send the data back to PayPal. If the data was sent by PayPal, it will display “VERIFIED”.

By using IPN, you can maintain inventory, transaction logs and automate so many other things.

For more information on PayPal IPN, you can refer the following link:

About Author

Parshwa Nemi Jain