How can PHP developers ensure the security and authenticity of payment confirmation from PayPal?

To ensure the security and authenticity of payment confirmation from PayPal, PHP developers can use PayPal IPN (Instant Payment Notification) to receive real-time notifications of payment transactions. By verifying the IPN message with PayPal, developers can ensure that the payment confirmation is legitimate and secure.

// Verify PayPal IPN
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
    $keyval = explode('=', $keyval);
    if (count($keyval) == 2) {
        $myPost[$keyval[0]] = urldecode($keyval[1]);
    }
}
$req = 'cmd=_notify-validate';
foreach ($myPost as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
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'));

if (!($res = curl_exec($ch))) {
    curl_close($ch);
    exit;
}
curl_close($ch);

if (strcmp($res, "VERIFIED") == 0) {
    // Payment verification successful
} else if (strcmp($res, "INVALID") == 0) {
    // Payment verification failed
}