Integrate Paypal IPN in Php

paypal ipn

To integrate PayPal IPN (Instant Payment Notification) in PHP, you can follow these steps:

1. Create a PayPal Sandbox account:
– Go to the PayPal Developer website  and create a developer account if you don’t have one.
– Once logged in, go to the Dashboard and click on “Sandbox” in the top navigation menu.
– Click on “Accounts” in the left sidebar and create a new Business account. This will be your test seller account.

2. Set up your PHP script to handle IPN:
– Create a new PHP file, e.g., “ipn.php”, where you will handle the IPN requests from PayPal.
– Include the following code at the beginning of the file to enable error reporting and logging:


error_reporting(E_ALL);
ini_set('log_errors', true);
ini_set('error_log', 'ipn_errors.log');

3. Verify the IPN request:
– Add the following code to your “ipn.php” file to verify the IPN request:

// Read the IPN notification from PayPal and add ‘cmd’ parameter

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

// Set up the PayPal Sandbox URL for IPN verification
$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
// Open a connection to PayPal
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

// Send the IPN verification request to PayPal
if (!($res = curl_exec($ch))) {
error_log("Failed to connect to PayPal IPN");
exit;
}

// Check the response from PayPal
if (strcmp($res, "VERIFIED") !== 0) {
error_log("Invalid IPN notification");
exit;
}

4. Process the IPN data:
– After verifying the IPN request, you can process the IPN data and perform any necessary actions, such as updating your database or sending email notifications.
– You can access the IPN variables sent by PayPal using the `$_POST` superglobal array. For example, to get the payment status, use `$_POST[‘payment_status’]`.
5. Send a response back to PayPal:
– Finally, you need to send a response back to PayPal to acknowledge the IPN notification. Add the following code at the end of your “ipn.php” file:


header('HTTP/1.1 200 OK');

Let's talk

If you want to get a free consultation without any obligations, fill in the form below and we'll get in touch with you.