[ Index ]
 

Code source de Zen Cart E-Commerce Shopping Cart 1.3.7.1

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/includes/modules/payment/paypal/ -> paypal_functions.php (source)

   1  <?php
   2  /**

   3   * functions used by payment module class for Paypal IPN payment method

   4   *

   5   * @package paymentMethod

   6   * @copyright Copyright 2003-2007 Zen Cart Development Team

   7   * @copyright Portions Copyright 2003 osCommerce

   8   * @copyright Portions Copyright (c) 2004 DevosC.com

   9   * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0

  10   * @version $Id: paypal_functions.php 6528 2007-06-25 23:25:27Z drbyte $

  11   */
  12  
  13  // Functions for paypal processing

  14    function datetime_to_sql_format($paypalDateTime) {
  15      //Copyright (c) 2004 DevosC.com

  16      $months = array('Jan' => '01', 'Feb' => '02', 'Mar' => '03', 'Apr' => '04', 'May' => '05',  'Jun' => '06',  'Jul' => '07', 'Aug' => '08', 'Sep' => '09', 'Oct' => '10', 'Nov' => '11', 'Dec' => '12');
  17      $hour = substr($paypalDateTime, 0, 2);$minute = substr($paypalDateTime, 3, 2);$second = substr($paypalDateTime, 6, 2);
  18      $month = $months[substr($paypalDateTime, 9, 3)];
  19      $day = (strlen($day = preg_replace("/,/" , '' , substr($paypalDateTime, 13, 2))) < 2) ? '0'.$day: $day;
  20      $year = substr($paypalDateTime, -8, 4);
  21      if (strlen($day)<2) $day = '0'.$day;
  22      return ($year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":" . $second);
  23    }
  24  
  25    function ipn_debug_email($message, $email_address = '', $always_send = false, $subjecttext = 'IPN DEBUG message') {
  26      static $paypal_error_counter;
  27      static $paypal_instance_id;
  28      if ($email_address == '') $email_address = (defined('MODULE_PAYMENT_PAYPAL_DEBUG_EMAIL_ADDRESS') ? MODULE_PAYMENT_PAYPAL_DEBUG_EMAIL_ADDRESS : STORE_OWNER_EMAIL_ADDRESS);
  29      if(!isset($paypal_error_counter)) $paypal_error_counter = 0;
  30      if(!isset($paypal_instance_id)) $paypal_instance_id = time() . '_' . zen_create_random_value(4);
  31      if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log and Email' || MODULE_PAYMENT_PAYPAL_IPN_DEBUG == 'Log and Email' || $always_send) {
  32        $paypal_error_counter ++;
  33        zen_mail(STORE_OWNER, $email_address, $subjecttext . ' (' . $paypal_instance_id . ') #' . $paypal_error_counter, $message, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>$message));
  34      }
  35      if (MODULE_PAYMENT_PAYPAL_IPN_DEBUG == 'Log and Email' || MODULE_PAYMENT_PAYPAL_IPN_DEBUG == 'Log File' || MODULE_PAYMENT_PAYPAL_IPN_DEBUG == 'Yes' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log and Email') ipn_add_error_log($message, $paypal_instance_id);
  36    }
  37    function ipn_get_stored_session($session_stuff) {
  38      global $db;
  39      if (!is_array($session_stuff)) {
  40        ipn_debug_email('IPN FATAL ERROR :: Could not find custom variable in POST, cannot re-create session as PayPal IPN transaction.');
  41        return false;
  42      }
  43      $sql = "SELECT *
  44              FROM " . TABLE_PAYPAL_SESSION . "
  45              WHERE session_id = :sessionID";
  46      $sql = $db->bindVars($sql, ':sessionID', $session_stuff[1], 'string');
  47      $stored_session = $db->Execute($sql);
  48      if ($stored_session->recordCount() < 1) {
  49        ipn_debug_email('IPN FATAL ERROR :: Could not find stored session in DB, cannot re-create session as PayPal IPN transaction.');
  50        return false;
  51      }
  52      $_SESSION = unserialize(base64_decode($stored_session->fields['saved_session']));
  53      return true;
  54    }
  55  /**

  56   * look up parent/original transaction record data and return matching order info if found, along with txn_type

  57   */
  58    function ipn_lookup_transaction($postArray) {
  59      global $db;
  60      // find Zen Cart order number from the transactionID in the IPN

  61      $useTable = TABLE_PAYPAL;
  62      if (MODULE_PAYMENT_PAYPAL_TESTING == 'Test') $useTable = TABLE_PAYPAL_TESTING;
  63      $ordersID = 0;
  64      $paypalipnID = 0;
  65      $transType = 'unknown';
  66  
  67      $sql = "SELECT zen_order_id, paypal_ipn_id, payment_status, txn_type, pending_reason
  68                  FROM " . $useTable . "
  69                  WHERE txn_id = :transactionID
  70                  ORDER BY zen_order_id DESC  ";
  71      $sql1 = $db->bindVars($sql, ':transactionID', $postArray['parent_txn_id'], 'string');
  72      $sql2 = $db->bindVars($sql, ':transactionID', $postArray['txn_id'], 'string');
  73      if (isset($postArray['parent_txn_id'])) {
  74        $ipn_id = $db->Execute($sql1);
  75        if($ipn_id->RecordCount() > 0) {
  76          ipn_debug_email('IPN NOTICE :: This transaction HAS a parent record. Thus this is an update of some sort.');
  77          $transType = 'parent';
  78          $ordersID = $ipn_id->fields['zen_order_id'];
  79          $paypalipnID = $ipn_id->fields['paypal_ipn_id'];
  80        }
  81      } else {
  82        $ipn_id = $db->Execute($sql2);
  83        if ($ipn_id->RecordCount() <= 0) {
  84          ipn_debug_email('IPN NOTICE :: Could not find matched txn_id record in DB. Therefore is new to us. ');
  85          $transType = 'unique';
  86        } else {
  87          while(!$ipn_id->EOF) {
  88            switch ($ipn_id->fields['pending_reason']) {
  89              case 'address':
  90                ipn_debug_email('IPN NOTICE :: Found pending-address record in database');
  91                if ($postArray['payment_status'] == 'Completed') $transType = 'cleared-address';
  92                if ($postArray['payment_status'] == 'Denied')    $transType = 'denied-address';
  93                if ($postArray['payment_status'] == 'Pending')   $transType = 'pending-address';
  94              break;
  95              case 'multi_currency':
  96                ipn_debug_email('IPN NOTICE :: Found pending-multicurrency record in database');
  97                if ($postArray['payment_status'] == 'Completed') $transType = 'cleared-multicurrency';
  98                if ($postArray['payment_status'] == 'Denied')    $transType = 'denied-multicurrency';
  99                if ($postArray['payment_status'] == 'Pending')   $transType = 'pending-multicurrency';
 100              break;
 101              case 'echeck':
 102                ipn_debug_email('IPN NOTICE :: Found pending-echeck record in database');
 103                if ($postArray['payment_status'] == 'Completed') $transType = 'cleared-echeck';
 104                if ($postArray['payment_status'] == 'Denied')    $transType = 'denied-echeck';
 105                if ($postArray['payment_status'] == 'Failed')    $transType = 'failed-echeck';
 106                if ($postArray['payment_status'] == 'Pending')   $transType = 'pending-echeck';
 107              break;
 108              case 'authorization':
 109                ipn_debug_email('IPN NOTICE :: Found pending-authorization record in database');
 110                $transType = 'cleared-authorization';
 111              break;
 112              case 'verify':
 113                ipn_debug_email('IPN NOTICE :: Found pending-verify record in database');
 114                $transType = 'cleared-verify';
 115              break;
 116              case 'intl':
 117                ipn_debug_email('IPN NOTICE :: Found pending-intl record in database');
 118                if ($postArray['payment_status'] == 'Completed') $transType = 'cleared-intl';
 119                if ($postArray['payment_status'] == 'Denied')    $transType = 'denied-intl';
 120                if ($postArray['payment_status'] == 'Pending')   $transType = 'pending-intl';
 121              break;
 122              case 'unilateral':
 123                ipn_debug_email('IPN NOTICE :: Found record in database.' . "\n" . '*** NOTE: TRANSACTION IS IN *unilateral* STATUS pending creation of a PayPal account for this receiver_email address.' . "\n" . 'Please create the account, or make sure the account is *Verified*.');
 124                $transType = 'pending-unilateral';
 125              break;
 126            }
 127            if ($transType != 'unknown') {
 128              $ordersID = $ipn_id->fields['zen_order_id'];
 129              $paypalipnID = $ipn_id->fields['paypal_ipn_id'];
 130            }
 131            $ipn_id->MoveNext();
 132          }
 133        }
 134      }
 135      return array('zen_order_id' => $ordersID, 'paypal_ipn_id' => $paypalipnID, 'txn_type' => $transType);
 136    }
 137  /**

 138   * IPN Validation

 139   * - match email addresses 

 140   * - ensure that "VERIFIED" has been returned (otherwise somebody is trying to spoof)

 141   */
 142    function ipn_validate_transaction($info, $postArray, $mode='IPN') {
 143      if ($mode == 'IPN' && !eregi("VERIFIED",$info)) {
 144        ipn_debug_email('IPN WARNING :: Transaction was not marked as VERIFIED. Keep this report for potential use in fraud investigations.' . "\n" . 'IPN Info = ' . "\n" . $info);
 145        return false;
 146      } elseif ($mode == 'PDT' && (!eregi("SUCCESS", $info) || eregi("FAIL", $info))) {
 147        ipn_debug_email('IPN WARNING :: PDT Transaction was not marked as SUCCESS. Keep this report for potential use in fraud investigations.' . "\n" . 'IPN Info = ' . "\n" . $info);
 148        return false;
 149      }
 150      $ppBusEmail = false;
 151      $ppRecEmail = false;
 152      if (defined('MODULE_PAYMENT_PAYPAL_BUSINESS_ID')) {
 153        if (strtolower(trim($postArray['business'])) == strtolower(trim(MODULE_PAYMENT_PAYPAL_BUSINESS_ID))) $ppBusEmail = true;
 154        if (strtolower(trim($postArray['receiver_email'])) == strtolower(trim(MODULE_PAYMENT_PAYPAL_BUSINESS_ID))) $ppRecEmail = true;
 155        if (!$ppBusEmail && !$ppRecEmail) {
 156          ipn_debug_email('IPN WARNING :: Transaction email address NOT matched.' . "\n" . 'From IPN = ' . $postArray['business'] . ' | ' . $postArray['receiver_email'] . "\n" . 'From CONFIG = ' .  MODULE_PAYMENT_PAYPAL_BUSINESS_ID);
 157          return false;
 158        }
 159        ipn_debug_email('IPN INFO :: Transaction email details.' . "\n" . 'From IPN = ' . $postArray['business'] . ' | ' . $postArray['receiver_email'] . "\n" . 'From CONFIG = ' .  MODULE_PAYMENT_PAYPAL_BUSINESS_ID);
 160      }
 161      return true;
 162    }
 163  
 164    // determine acceptable currencies

 165    function select_pp_currency() {
 166      if (MODULE_PAYMENT_PAYPAL_CURRENCY == 'Selected Currency') {
 167        $my_currency = $_SESSION['currency'];
 168      } else {
 169        $my_currency = substr(MODULE_PAYMENT_PAYPAL_CURRENCY, 5);
 170      }
 171      $pp_currencies = array('CAD', 'EUR', 'GBP', 'JPY', 'USD', 'AUD', 'CHF', 'CZK', 'DKK', 'HKD', 'HUF', 'NOK', 'NZD', 'PLN', 'SEK', 'SGD', 'THB');
 172      if (!in_array($my_currency, $pp_currencies)) {
 173        $my_currency = 'USD';
 174      }
 175      return $my_currency;
 176    }
 177  
 178    function valid_payment($amount, $currency, $mode = 'IPN') {
 179      global $currencies;
 180      $my_currency = select_pp_currency();
 181      $exchanged_amount = ($mode == 'IPN' ? ($amount * $currencies->get_value($my_currency)) : $amount);
 182      $transaction_amount = preg_replace('/[^0-9.]/', '', number_format($exchanged_amount, $currencies->get_decimal_places($my_currency), '.', ''));
 183      if ( ($_POST['mc_currency'] != $my_currency) || ($_POST['mc_gross'] != $transaction_amount && $_POST['mc_gross'] != -0.01) && MODULE_PAYMENT_PAYPAL_TESTING != 'Test' ) {
 184        ipn_debug_email('IPN WARNING :: Currency/Amount Mismatch.  Details: ' . "\n" . 'PayPal email address = ' . $_POST['business'] . "\n" . ' | mc_currency = ' . $_POST['mc_currency'] . "\n" . ' | submitted_currency = ' . $my_currency . "\n" . ' | order_currency = ' . $currency . "\n" . ' | mc_gross = ' . $_POST['mc_gross'] . "\n" . ' | converted_amount = ' . $transaction_amount . "\n" . ' | order_amount = ' . $amount );
 185        return false;
 186      }
 187      ipn_debug_email('IPN INFO :: Currency/Amount Details: ' . "\n" . 'PayPal email address = ' . $_POST['business'] . "\n" . ' | mc_currency = ' . $_POST['mc_currency'] . "\n" . ' | submitted_currency = ' . $my_currency . "\n" . ' | order_currency = ' . $currency . "\n" . ' | mc_gross = ' . $_POST['mc_gross'] . "\n" . ' | converted_amount = ' . $transaction_amount . "\n" . ' | order_amount = ' . $amount );
 188      return true;
 189    }
 190  
 191  /**

 192   *  is this an existing transaction?

 193   *    (1) we find a matching record in the "paypal" table

 194   *    (2) we check for valid txn_types or payment_status such as Denied, Refunded, Partially-Refunded, Reversed, Voided, Expired

 195   * @TODO -- this section is not complete yet

 196   */
 197    function ipn_determine_txn_type($postArray, $txn_type = 'unknown') {
 198      global $db;
 199      if (substr($txn_type,0,8) == 'cleared-') return $txn_type;
 200      if ($postArray['txn_type'] == 'send_money') return $postArray['txn_type'];
 201      if ($postArray['txn_type'] == 'express_checkout' || $postArray['txn_type'] == 'cart') $txn_type = $postArray['txn_type'];
 202  // if it's not unique or linked to a parent, then:

 203  // 1. could be an e-check denied / cleared

 204  // 2. could be an express-checkout "pending" transaction which has been Accepted in the merchant's PayPal console and needs activation in Zen Cart

 205      if ($postArray['payment_status']=='Completed' && txn_type=='express_checkout' && $postArray['payment_type']=='echeck') {
 206        $txn_type = 'express-checkout-cleared';
 207        return $txn_type;
 208      }
 209      if ($postArray['payment_status']=='Completed' && $postArray['payment_type']=='echeck') {
 210        $txn_type = 'echeck-cleared';
 211        return $txn_type;
 212      }
 213      if (($postArray['payment_status']=='Denied' || $postArray['payment_status']=='Failed') && $postArray['payment_type']=='echeck') {
 214        $txn_type = 'echeck-denied';
 215        return $txn_type;
 216      }
 217      if ($postArray['payment_status']=='Denied') {
 218        $txn_type = 'denied';
 219        return $txn_type;
 220      }
 221      if (($postArray['payment_status']=='Pending') && $postArray['pending_reason']=='echeck') {
 222        $txn_type = 'pending-echeck';
 223        return $txn_type;
 224      }
 225      if (($postArray['payment_status']=='Pending') && $postArray['pending_reason']=='address') {
 226        $txn_type = 'pending-address';
 227        return $txn_type;
 228      }
 229      if (($postArray['payment_status']=='Pending') && $postArray['pending_reason']=='intl') {
 230        $txn_type = 'pending-intl';
 231        return $txn_type;
 232      }
 233      if (($postArray['payment_status']=='Pending') && $postArray['pending_reason']=='multi_currency') {
 234        $txn_type = 'pending-multicurrency';
 235        return $txn_type;
 236      }
 237      if (($postArray['payment_status']=='Pending') && $postArray['pending_reason']=='verify') {
 238        $txn_type = 'pending-verify';
 239        return $txn_type;
 240      }
 241      return $txn_type;
 242    }
 243  /**

 244   * Create order record from IPN data

 245   */
 246    function ipn_create_order_array($new_order_id, $txn_type) {
 247      $paypal_order = array('zen_order_id' => $new_order_id,
 248                            'txn_type' => $txn_type,
 249                            'reason_code' => $_POST['reason_code'],
 250                            'payment_type' => $_POST['payment_type'],
 251                            'payment_status' => $_POST['payment_status'],
 252                            'pending_reason' => $_POST['pending_reason'],
 253                            'invoice' => $_POST['invoice'],
 254                            'mc_currency' => $_POST['mc_currency'],
 255                            'first_name' => $_POST['first_name'],
 256                            'last_name' => $_POST['last_name'],
 257                            'payer_business_name' => $_POST['payer_business_name'],
 258                            'address_name' => $_POST['address_name'],
 259                            'address_street' => $_POST['address_street'],
 260                            'address_city' => $_POST['address_city'],
 261                            'address_state' => $_POST['address_state'],
 262                            'address_zip' => $_POST['address_zip'],
 263                            'address_country' => $_POST['address_country'],
 264                            'address_status' => $_POST['address_status'],
 265                            'payer_email' => $_POST['payer_email'],
 266                            'payer_id' => $_POST['payer_id'],
 267                            'payer_status' => $_POST['payer_status'],
 268                            'payment_date' => datetime_to_sql_format($_POST['payment_date']),
 269                            'business' => $_POST['business'],
 270                            'receiver_email' => $_POST['receiver_email'],
 271                            'receiver_id' => $_POST['receiver_id'],
 272                            'txn_id' => $_POST['txn_id'],
 273                            'parent_txn_id' => $_POST['parent_txn_id'],
 274                            'num_cart_items' => $_POST['num_cart_items'],
 275                            'mc_gross' => $_POST['mc_gross'],
 276                            'mc_fee' => $_POST['mc_fee'],
 277                            'settle_amount' => $_POST['settle_amount'],
 278                            'settle_currency' => $_POST['settle_currency'],
 279                            'exchange_rate' => $_POST['exchange_rate'],
 280                            'notify_version' => $_POST['notify_version'],
 281                            'verify_sign' => $_POST['verify_sign'],
 282                            'date_added' => 'now()',
 283                            'memo' => $_POST['memo']
 284                           );
 285      return $paypal_order;
 286    }
 287  /**

 288   * Create order-history record from IPN data

 289   */
 290    function ipn_create_order_history_array($insert_id) {
 291      $paypal_order_history = array ('paypal_ipn_id' => $insert_id,
 292                                     'txn_id' => $_POST['txn_id'],
 293                                     'parent_txn_id' => $_POST['parent_txn_id'],
 294                                     'payment_status' => $_POST['payment_status'],
 295                                     'pending_reason' => $_POST['pending_reason'],
 296                                     'date_added' => 'now()'
 297                                    );
 298      return $paypal_order_history;
 299    }
 300  /**

 301   * Create order-update from IPN data

 302   */
 303    function ipn_create_order_update_array($txn_type) {
 304      $paypal_order = array('reason_code' => $_POST['reason_code'],
 305                            'payment_type' => $_POST['payment_type'],
 306                            'txn_type' => $txn_type,
 307                            'parent_txn_id' => $_POST['parent_txn_id'],
 308                            'payment_status' => $_POST['payment_status'],
 309                            'pending_reason' => $_POST['pending_reason'],
 310                            'invoice' => $_POST['invoice'],
 311                            'mc_currency' => $_POST['mc_currency'],
 312                            'first_name' => $_POST['first_name'],
 313                            'last_name' => $_POST['last_name'],
 314                            'payer_business_name' => $_POST['payer_business_name'],
 315                            'address_name' => $_POST['address_name'],
 316                            'address_street' => $_POST['addrss_street'],
 317                            'address_city' => $_POST['address_city'],
 318                            'address_state' => $_POST['address_state'],
 319                            'address_zip' => $_POST['address_zip'],
 320                            'address_country' => $_POST['address_country'],
 321                            'payer_email' => $_POST['payer_email'],
 322                            'payer_id' => $_POST['payer_id'],
 323                            'business' => $_POST['business'],
 324                            'receiver_email' => $_POST['receiver_email'],
 325                            'receiver_id' => $_POST['receiver_id'],
 326                            'num_cart_items' => $_POST['num_cart_items'],
 327                            'mc_gross' => $_POST['mc_gross'],
 328                            'mc_fee' => $_POST['mc_fee'],
 329                            'settle_amount' => $_POST['settle_amount'],
 330                            'settle_currency' => $_POST['settle_currency'],
 331                            'exchange_rate' => $_POST['exchange_rate'],
 332                            'notify_version' => $_POST['notify_version'],
 333                            'verify_sign' => $_POST['verify_sign'],
 334                            'last_modified' => 'now()'
 335                           );
 336      return $paypal_order;
 337    }
 338  /**

 339   * simulator

 340   */
 341    function ipn_simulate_ipn_handler($count) {
 342      global $db;
 343      $sql = "select * from " . TABLE_PAYPAL_TESTING . " order by paypal_ipn_id desc limit " . (int)$count;
 344      $paypal_testing = $db->execute($sql);
 345      while (!$paypal_testing->EOF) {
 346        $paypal_fields[] = $paypal_testing->fields;
 347        $paypal_testing->moveNext();
 348      }
 349      $paypal_fields = array_reverse($paypal_fields);
 350      foreach ($paypal_fields as $value) {
 351        foreach($value as $i=>$v) {
 352          $postdata .= $i . "=" . urlencode(stripslashes($v)) . "&";
 353        }
 354        $address = HTTP_SERVER . DIR_WS_CATALOG . 'ipn_main_handler.php?' . $postdata;
 355        $response = ipn_fopen($address);
 356        echo $response;
 357      }
 358    }
 359  /**

 360   * Debug logging

 361   */
 362    function ipn_add_error_log($message, $paypal_instance_id = '') {
 363      if ($paypal_instance_id == '') $paypal_instance_id = date('mdYGi');
 364      $fp = @fopen('includes/modules/payment/paypal/logs/ipn_' . $paypal_instance_id . '.log', 'a');
 365      @fwrite($fp, date('M d Y G:i') . ' -- ' . $message . "\n\n");
 366      @fclose($fp);
 367      // if (MODULE_PAYMENT_PAYPAL_TESTING == 'Test') echo date('d M Y G:i') . ' -- ' . $message . "\n";

 368    }
 369  /**

 370   * Debug to file

 371   */
 372    function ipn_fopen($filename) {
 373      $response = '';
 374      $fp = fopen($filename,'rb');
 375      if ($fp) {
 376        $response = getRequestBodyContents($fp);
 377        @fclose($fp);
 378      }
 379      return $response;
 380    }
 381    function getRequestBodyContents(&$handle) {
 382      if ($handle) {
 383        while(!feof($handle)) {
 384          $line .= @fgets($handle, 1024);
 385        }
 386        return $line;
 387      }
 388      return false;
 389    }
 390  /**

 391   * Verify IPN by sending it back to PayPal for confirmation

 392   */
 393    function ipn_postback($mode = 'IPN') {
 394      $info = '';
 395      $header = '';
 396      $scheme = 'http://';
 397      //if (ENABLE_SSL == 'true') $scheme = 'https://';

 398      //Parse url

 399      $web = parse_url($scheme . (defined('MODULE_PAYMENT_PAYPAL_HANDLER') ? MODULE_PAYMENT_PAYPAL_HANDLER : 'www.paypal.com/cgi-bin/webscr'));
 400      if (isset($_POST['test_ipn']) && $_POST['test_ipn'] == 1) {
 401        $web = parse_url($scheme . 'www.sandbox.paypal.com/cgi-bin/webscr');
 402      }
 403      //build post string

 404      $postdata = '';
 405      $postback = '';
 406      $postback_array = array();
 407      foreach($_POST as $key=>$value) {
 408        $postdata .= $key . "=" . urlencode(stripslashes($value)) . "&";
 409        $postback .= $key . "=" . urlencode(stripslashes($value)) . "&";
 410        $postback_array[$key] = $value;
 411      }
 412      if ($mode == 'PDT') {
 413        $postback .= "cmd=_notify-synch";
 414        $postback .= "&tx=" . $_GET['tx'];
 415        $postback .= "&at=" . MODULE_PAYMENT_PAYPAL_PDTTOKEN;
 416        $postback_array['cmd'] = "_notify-sync";
 417        $postback_array['tx'] = $_GET['tx'];
 418        $postback_array['at'] = substr(MODULE_PAYMENT_PAYPAL_PDTTOKEN, 0, 5) . '**********' . substr(MODULE_PAYMENT_PAYPAL_PDTTOKEN,-5);
 419      } elseif ($mode == 'IPN') {
 420        $postback .= "cmd=_notify-validate";
 421        $postback_array['cmd'] = "_notify-validate";
 422      }
 423      if ($postdata == '=&') {
 424        ipn_debug_email('IPN FATAL ERROR :: No POST data to process -- Bad IPN data');
 425        return array('info' => $info, 'postdata' => $postdata );
 426      }
 427      $postdata_array = $_POST;
 428      ksort($postdata_array);
 429  
 430      if ($mode == 'IPN') {
 431        ipn_debug_email('IPN INFO - POST VARS received (sorted):' . "\n" . stripslashes(urldecode(print_r($postdata_array, true))));
 432        if (sizeof($postdata_array) == 0) die('Nothing to process. Please return to home page.');
 433      }
 434      if (MODULE_PAYMENT_PAYPAL_TESTING == 'Test') {
 435        $info = "VERIFIED";
 436        ipn_debug_email('IPN INFO - POST VARS sent back for validation: ' . "\n" . 'TEST MODE.' . "\n" . stripslashes(print_r($postback_array, true)));
 437      } else {
 438        //Set the port number

 439        if($web['scheme'] == "https") {
 440          $web['port']="443";  $ssl = "ssl://";
 441        } else {
 442          $web['port']="80";   $ssl = "";
 443        }
 444        $proxy = $web;
 445        if (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '') {
 446          $proxy = parse_url($scheme . CURL_PROXY_SERVER_DETAILS);
 447          $ssl = ($ssl == '') ? 'http://' : $ssl;
 448        }
 449  
 450        //Post Data

 451        if (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '') {
 452          $header  = "POST " . $ssl . $web[host] . $web[path] . " HTTP/1.1\r\n";
 453          $header .= "Host: $proxy[host]\r\n";
 454        } else {
 455          $header  = "POST $web[path] HTTP/1.1\r\n";
 456          $header .= "Host: $web[host]\r\n";
 457        }
 458        $header .= "Content-type: application/x-www-form-urlencoded\r\n";
 459        $header .= "Content-length: " . strlen($postback) . "\r\n";
 460        $header .= "Connection: close\r\n\r\n";
 461  
 462        ipn_debug_email('IPN INFO - POST VARS to be sent back for validation: ' . "\n" . 'To: ' . $ssl . $proxy['host'] . ':' . $proxy['port'] . "\n" . $header . stripslashes(print_r($postback_array, true)));
 463  
 464        //Create paypal connection

 465        if (MODULE_PAYMENT_PAYPAL_IPN_DEBUG == 'Yes') {
 466          $fp=fsockopen($ssl . $proxy['host'], $proxy['port'], $errnum, $errstr, 30);
 467        } else {
 468          $fp=@fsockopen($ssl . $proxy['host'], $proxy['port'], $errnum, $errstr, 30);
 469        }
 470        if(!$fp) {
 471          ipn_debug_email('IPN FATAL ERROR :: Could not establish fsockopen. ' . "\n" . 'Host Details = ' . $ssl . $proxy['host'] . ':' . $proxy['port'] . ' (' . $errnum . ') ' . $errstr . "\n" . (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '' ? "\n" . $ssl . $web[host] . $web[path] : '') . "\n Trying again without SSL ...");
 472          $ssl = 'http://';
 473          $proxy['port'] = '80';
 474          $fp=@fsockopen($ssl . $proxy['host'], $proxy['port'], $errnum, $errstr, 30);
 475        }
 476        if(!$fp) {
 477          ipn_debug_email('IPN FATAL ERROR :: Could not establish fsockopen. ' . "\n" . 'Host Details = ' . $ssl . $proxy['host'] . ':' . $proxy['port'] . ' (' . $errnum . ') ' . $errstr . "\n" . (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '' ? "\n" . $ssl . $web[host] . $web[path] : '') . "\n Trying again without specified protocol ...");
 478          $ssl = '';
 479          $fp=@fsockopen($ssl . $proxy['host'], $proxy['port'], $errnum, $errstr, 30);
 480        }
 481        if(!$fp) {
 482          ipn_debug_email('IPN FATAL ERROR :: Could not establish fsockopen. ' . "\n" . 'Host Details = ' . $ssl . $proxy['host'] . ':' . $proxy['port'] . ' (' . $errnum . ') ' . $errstr . "\n" . (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '' ? "\n" . $ssl . $web[host] . $web[path] : ''));
 483          die();
 484        }
 485  
 486        fputs($fp, $header . $postback . "\r\n\r\n");
 487        $header_data = '';
 488        //loop through the response from the server

 489        while(!feof($fp)) {
 490          $line = @fgets($fp, 1024);
 491          if (strcmp($line, "\r\n") == 0) {
 492            // this is a header row

 493            $headerdone = true;
 494            $header_data .= $line;
 495          } else if ($headerdone) { 
 496            // header has been read. now read the contents

 497            $info[] = $line;
 498          }
 499        }
 500        //close fp - we are done with it

 501        fclose($fp);
 502        //break up results into a string

 503        $info = implode("", $info);
 504      }
 505      $status = (strstr($info,'VERIFIED')) ? 'VERIFIED' : (strstr($info,'SUCCESS')) ? 'SUCCESS' : '';
 506  
 507      ipn_debug_email('IPN INFO - Confirmation/Validation response ' . "\n" . ($status != '' ? $status : $header_data . $info));
 508  
 509      return array('info' => $info, 'postdata' => $postdata );
 510    }
 511  
 512  /**

 513   * Write order-history update to ZC tables denoting the update supplied by the IPN

 514   */
 515    function ipn_update_orders_status_and_history($ordersID, $new_status = 1, $txn_type) {
 516      global $db;
 517      ipn_debug_email('IPN NOTICE :: Updating order #' . (int)$ordersID . ' to status: ' . (int)$new_status . ' (txn_type: ' . $txn_type . ')');
 518      $db->Execute("update " . TABLE_ORDERS  . "
 519                      set orders_status = '" . (int)$new_status . "'
 520                      where orders_id = '" . (int)$ordersID . "'");
 521  
 522      $sql_data_array = array('orders_id' => (int)$ordersID,
 523                              'orders_status_id' => (int)$new_status,
 524                              'date_added' => 'now()',
 525                              'comments' => 'PayPal status: ' . $_POST['payment_status'] . ' ' . ' @ ' . $_POST['payment_date'] . (($_POST['parent_txn_id'] !='') ? "\n" . ' Parent Trans ID:' . $_POST['parent_txn_id'] : '') . "\n" . ' Trans ID:' . $_POST['txn_id'] . "\n" . ' Amount: ' . $_POST['mc_gross'] . ' ' . $_POST['mc_currency'],
 526                              'customer_notified' => false
 527                             );
 528      zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
 529      ipn_debug_email('IPN NOTICE :: Update complete.');
 530  
 531  /** 

 532   * Activate any downloads associated with an order which has now been cleared

 533   */
 534      if ($txn_type=='echeck-cleared' || $txn_type == 'express-checkout-cleared' || substr($txn_type,0,8) == 'cleared-') {
 535        $check_status = $db->Execute("select date_purchased from " . TABLE_ORDERS . " where orders_id = '" . (int)$ordersID . "'");
 536        $zc_max_days = date_diff($check_status->fields['date_purchased'], date('Y-m-d H:i:s', time())) + (int)DOWNLOAD_MAX_DAYS;
 537        ipn_debug_email('IPN NOTICE :: Updating order #' . (int)$ordersID . ' downloads.  New max days: ' . (int)$zc_max_days . ', New count: ' . (int)DOWNLOAD_MAX_COUNT);
 538        $update_downloads_query = "update " . TABLE_ORDERS_PRODUCTS_DOWNLOAD . " set download_maxdays='" . (int)$zc_max_days . "', download_count='" . (int)DOWNLOAD_MAX_COUNT . "' where orders_id='" . (int)$ordersID . "'";
 539        $db->Execute($update_downloads_query);
 540      }
 541    }
 542  
 543  if (!function_exists('replace_accents')) {
 544  /**

 545   * strip out accented characters to reasonable approximations of english equivalents

 546   */
 547    function replace_accents($s) {
 548      $s = htmlentities($s);
 549      $s = preg_replace ('/&([a-zA-Z])(uml|acute|elig|grave|circ|tilde|cedil|ring|quest|slash|caron);/', '$1', $s);
 550      $s = html_entity_decode($s);
 551      return $s;
 552    }
 553  }
 554  ?>


Généré le : Mon Nov 26 16:45:43 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics