Tuesday, March 22, 2016

Create component to validate IPN (Instant Payment Notification) with Cakephp


It's seem to be for senior programmer, but I just want to let somebody know the benefit or how to implement the IPN of PayPal using PHP or Cakephp, before you can understand what to do with IPN you have take a look this website.

If you don't know at all about Paypal please read the previous article : Paypal
class IpnComponent extends Component
{
   public function validate_ipn_data($data_ipn)
   {
     //Change these with your information
     //Sandbox for testing or empty ''
     $site = @$_SERVER['SERVER_NAME'];
     $paypalmode = $site === 'your_site' ? '' : 'sandbox';

    if ($data_ipn) {
       if ($paypalmode=='sandbox') {
          $paypalmode     =   '.sandbox';
       }
       $req = 'cmd=' . urlencode('_notify-validate');
       foreach ($data_ipn as $key => $value) {
           $value = urlencode(stripslashes($value));
           $req .= "&$key=$value";
        }
    $ch = curl_init();
    $url_ = 'https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr';
    $host_ = 'Host: www'.$paypalmode.'.sandbox.paypal.com';
    curl_setopt($ch, CURLOPT_URL, $url_);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    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_HTTPHEADER, array($host_));
    $res = curl_exec($ch);
    curl_close($ch);

    if (strcmp ($res, "VERIFIED") == 0) {
         $item_number = $data_ipn['item_number'];
         $model      = ClassRegistry::init('Reservation');
                $model->id = $item_number;
                $model->save(array('is_paid' => 1));
    }
  }
 }  
}
1- Please create file in Component and pass the code above, then save.
2- You have to load the component in your controller
3- Create a function and call the  validate_ipn_data from IPN component
Note : Make sure that your URL pointed to Paypal.

0 comments:

Post a Comment