Location: PHPKode > projects > Musichearts > musichearts-0.2.2/php/payment/api_impl_paypal.php
<?php 
  
  ////////////////////////
  // UNDER CONSTRUCTION //
  ////////////////////////


  // CLASS musichearts_payment_paypal implements payment api using paypal
  // 
  class musichearts_payment_paypal extends musichearts_payment
  {

    //////////////////
    // METHOD SECTION
    public static final function get_description()
    {
      return musichearts_text::get( 'paypal' );
    }
    
    public static final function get_hidden_form()
    {
      global $musichearts_paypal_username;
      global $musichearts_song_currency;
      global $musichearts_development_mode;
      global $basket;
 
      //return URL for PDT should be set in paypal profile as paypal states
      //$return_url = 'http';
      //if ($_SERVER["HTTPS"] == "on") 
        //$return_url .= "s";
      //$return_url .= "://";
      //if ($_SERVER["SERVER_PORT"] != "80")
        //$return_url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
      //else 
        //$return_url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
      //$return_url = preg_replace( '/\?.*$/', '', $return_url);

      $return_url = musichearts_url_tools::get_current_url();
      
      if( $musichearts_development_mode == false )
        $paypal_url = 'www.paypal.com';
      else
        $paypal_url = 'www.sandbox.paypal.com';


      $form[]='<form id="musichearts_payment_paypal" action="https://'. $paypal_url .'/cgi-bin/webscr" method="post">';
      $form[]='  <p>';

      $form[]='    <input type="hidden" name="return" value="'.$return_url.'" />';
      //$form[]='    <input type="hidden" name="rm" value="2" />';
        
      $form[]='    <input type="hidden" name="cmd" value="_cart" />';
        
      $form[]='    <input type="hidden" name="upload" value="1" />';
      

      $form[]='    <input type="hidden" name="business"'.
                   ' value="'. $musichearts_paypal_username.'"'.
                 ' />';

      $form[]='    <input type="hidden" name="currency_code"'.
                  ' value="'.$musichearts_song_currency.'"'.
                 ' />';
      
      $songs = $basket->get_song_objects();
      $index = 0;
      if( is_array( $songs ) )
      {
        foreach( $songs as $song ) 
        { 
          $index++;
          $form[]='    <input type="hidden" name="item_name_'.$index.'"'.
                       ' value="'.$song->filename.'"'.
                     ' />';
          $form[]='    <input type="hidden" name="amount_'.$index.'"'.
                       ' value="'.$song->price.'"'.
                     ' />';
        }
      }
        
      //$form[]='<input type="submit" value="PayPal" />';
      
      $form[]='  </p>';
      $form[]='</form>';

      return $form;
    }


    public static final function get_hidden_form_id()
    {
      return 'musichearts_payment_paypal';
    }


    public static function check_payment( $data, $basket )
    {
      global $musichearts_paypal_auth_token;
      global $musichearts_development_mode;
      global $musichearts_band_email;
      global $musichearts_paypal_ssl_mode;
      global $musichearts_development_mode_local;
      global $musichearts_band_name;

      $download_links    = null;
      $email_content     = null;
      $payment_succeeded = false;
      $header            = '';
      $songs             = null;
      
      //if( empty( $basket ) )
        //return;


      if( !$musichearts_development_mode_local )
      {

        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-synch';
   
        $tx_token = $data;
        $auth_token = $musichearts_paypal_auth_token;
  
        $req .= "&tx=$tx_token&at=$auth_token";
       
        // post back to PayPal system to validate
        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
       
        if( $musichearts_development_mode == false )
          $paypal_url = 'www.paypal.com';
        else
          $paypal_url = 'www.sandbox.paypal.com';
  
        if( $musichearts_paypal_ssl_mode == true )
        {
          // Your PHP server will need to be SSL enabled
          $paypal_url_prefix = 'ssl://';
          $paypal_port = 443;
        }
        else
        {
          $paypal_url_prefix = '';
          $paypal_port = 80;
        }
  
        $fp = fsockopen( $paypal_url_prefix.$paypal_url, $paypal_port, $errno, $errstr, 30 );
        // If possible, securely post back to paypal using HTTPS
        // $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
       
        if( !$fp )
        {
          // TODO
          // HTTP ERROR in index file
          // echo 'HTTP ERROR CONNECTING TO PAYPAL FOR VALIDATION';
          throw new musichearts_exception( 1, 'HTTP ERROR: '.$errno.' '.$errstr );
        }
        else
        {
          fputs( $fp, $header . $req );
          // read the body data
          $res = '';
          $headerdone = false;
          while( !feof($fp) )
          {
            $line = fgets( $fp, 1024 );
            if( strcmp( $line, "\r\n" ) == 0 )
            {
              // read the header
              $headerdone = true;
            }
            else if( $headerdone )
            {
              // header has been read. now read the contents
              $res .= $line;
            }
          }
      
          // parse the data
          $lines = explode("\n", $res);
          $keyarray = array();
      
          
          if( strcmp( $lines[0], "SUCCESS" ) == 0 )
          {
            for( $i = 1; $i < count( $lines) ; $i++ )
            {
              list( $key, $val ) = explode( "=", $lines[$i] );
              $keyarray[ urldecode( $key ) ] = urldecode( $val );
            }
            // 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
            $firstname = $keyarray[ 'first_name' ];
            $lastname  = $keyarray[ 'last_name' ];
            $itemname  = $keyarray[ 'item_name' ];
            $amount    = $keyarray[ 'payment_gross' ];
      
            $payment_succeeded = True;
      
          }
          else if( strcmp( $lines[0], "FAIL" ) == 0 )
          {
            // TODO: log for manual investigation
            //       and move to index file
            //echo 'RECEIVED NEGATIVE ANSWER FROM PAYPAL';
            fclose ($fp);
            throw new musichearts_exception( 2, 'RECEIVED NEGATIVE ANSWER FROM PAYPAL' );
          }
      
        }
  
        //var_dump( $keyarray );
      
        fclose ($fp);
            
            
        if( $payment_succeeded != true )
          throw new musichearts_exception( 3, 'PAYMENT COULD NOT BE CONFIRMED' );
  

        // set payment status in song objects
        foreach( $keyarray as $answer_key => $answer_value )
        {
          if( !preg_match( '/item_name[0-9]*/', $answer_key ) )
            continue;
          $song = musichearts_central_plugin::get_song_from_plugin( 
            musichearts_converter::string2hex(
              $answer_value
            )
          );
          if( $song->check_payment() )
            continue;
            // song is already paid
            
          $songs[] = $song;    
        }
      
      }
      else
      {
        if( !array_key_exists( 'HTTP_CACHE_CONTROL', $_SERVER ) )
          $songs = $basket->get_song_objects();
      }
     

      // TODO: better check more outside
      if( is_array( $songs ) )
      {
        foreach( $songs as $song )
        {
          if( isset( $_SESSION[ 'musichearts_customer_email_address' ] ) )
            $download_links[] = $song->confirm_payment();
          else
            $song->confirm_payment( false );

          $basket->remove_song( musichearts_converter::string2hex( $song->filename ) );
        }

        if( isset( $_SESSION[ 'musichearts_customer_email_address' ] ) )
        {
          $email_content = null;

          
          //TODO: MAIL WITH DOWNLOAD LINKS IN SUBFUNCTION
          $email = new musichearts_email();

          $email_content = musichearts_text::get( 'email_content1' );
          foreach( $download_links as $download_link )
            $email_content .= "\r\n\r\n" . $download_link;
          $email_content .= " \r\n\r\n";
          $email_content .= musichearts_text::get( 'email_content2' );
          $email_content .= $musichearts_band_name.


          $email->add_recipient( $_SESSION[ 'musichearts_customer_email_address' ] );

          $email->set_subject(
            musichearts_text::get( 'email_subject' ) .
            $musichearts_band_name
          );
          
          $email->set_content( $email_content );
  
          $result = $email->send();
        }
      }

    }

  }

?>
Return current item: Musichearts