PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/modules/payment/paypalwpp.php

https://github.com/happyxlq/zencart_svn
PHP | 2848 lines | 2011 code | 254 blank | 583 comment | 774 complexity | ac449f49cbcd135a624063dd2c7e4221 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * paypalwpp.php payment module class for PayPal Express Checkout payment method
  4. *
  5. * @package paymentMethod
  6. * @copyright Copyright 2003-2010 Zen Cart Development Team
  7. * @copyright Portions Copyright 2003 osCommerce
  8. * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
  9. * @version $Id: paypalwpp.php 16878 2010-07-08 17:03:31Z drbyte $
  10. */
  11. /**
  12. * load the communications layer code
  13. */
  14. require_once(DIR_FS_CATALOG . DIR_WS_MODULES . 'payment/paypal/paypal_curl.php');
  15. /**
  16. * the PayPal payment module with Express Checkout
  17. */
  18. class paypalwpp extends base {
  19. /**
  20. * name of this module
  21. *
  22. * @var string
  23. */
  24. var $code;
  25. /**
  26. * displayed module title
  27. *
  28. * @var string
  29. */
  30. var $title;
  31. /**
  32. * displayed module description
  33. *
  34. * @var string
  35. */
  36. var $description;
  37. /**
  38. * module status - set based on various config and zone criteria
  39. *
  40. * @var string
  41. */
  42. var $enabled;
  43. /**
  44. * the zone to which this module is restricted for use
  45. *
  46. * @var string
  47. */
  48. var $zone;
  49. /**
  50. * debugging flag
  51. *
  52. * @var boolean
  53. */
  54. var $enableDebugging = false;
  55. /**
  56. * Determines whether payment page is displayed or not
  57. *
  58. * @var boolean
  59. */
  60. var $showPaymentPage = false;
  61. var $flagDisablePaymentAddressChange = false;
  62. /**
  63. * sort order of display
  64. *
  65. * @var int
  66. */
  67. var $sort_order = 0;
  68. /**
  69. * Button Source / BN code -- enables the module to work for Zen Cart
  70. *
  71. * @var string
  72. */
  73. var $buttonSourceEC = 'zhongtuo_cart_ec_c2';
  74. /**
  75. * order status setting for pending orders
  76. *
  77. * @var int
  78. */
  79. var $order_pending_status = 1;
  80. /**
  81. * order status setting for completed orders
  82. *
  83. * @var int
  84. */
  85. var $order_status = DEFAULT_ORDERS_STATUS_ID;
  86. /**
  87. * Debug tools
  88. */
  89. var $_logDir = 'includes/modules/payment/paypal/logs/';
  90. var $_logLevel = 0;
  91. /**
  92. * FMF
  93. */
  94. var $fmfResponse = '';
  95. var $fmfErrors = array();
  96. /**
  97. * class constructor
  98. */
  99. function paypalwpp() {
  100. include_once(zen_get_file_directory(DIR_FS_CATALOG . DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/payment/', 'paypalwpp.php', 'false'));
  101. global $order;
  102. $this->code = 'paypalwpp';
  103. $this->codeTitle = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
  104. $this->codeVersion = '1.3.9e';
  105. $this->enableDirectPayment = FALSE;
  106. $this->enabled = (MODULE_PAYMENT_PAYPALWPP_STATUS == 'True');
  107. // Set the title & description text based on the mode we're in ... EC vs US/UK vs admin
  108. if (IS_ADMIN_FLAG === true) {
  109. $this->description = sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_DESCRIPTION, ' (rev' . $this->codeVersion . ')');
  110. switch (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE) {
  111. case ('PayPal'):
  112. $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
  113. break;
  114. case ('Payflow-UK'):
  115. $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PRO20;
  116. break;
  117. case ('Payflow-US'):
  118. if (defined('MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC') && MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC == 'Yes') {
  119. $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PF_EC;
  120. } else {
  121. $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PF_GATEWAY;
  122. }
  123. break;
  124. default:
  125. $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
  126. }
  127. if ($this->enabled) {
  128. if ( (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'PayPal' && (MODULE_PAYMENT_PAYPALWPP_APISIGNATURE == '' || MODULE_PAYMENT_PAYPALWPP_APIUSERNAME == '' || MODULE_PAYMENT_PAYPALWPP_APIPASSWORD == ''))
  129. || (substr(MODULE_PAYMENT_PAYPALWPP_MODULE_MODE,0,7) == 'Payflow' && (MODULE_PAYMENT_PAYPALWPP_PFPARTNER == '' || MODULE_PAYMENT_PAYPALWPP_PFVENDOR == '' || MODULE_PAYMENT_PAYPALWPP_PFUSER == '' || MODULE_PAYMENT_PAYPALWPP_PFPASSWORD == ''))
  130. ) $this->title .= '<span class="alert"><strong> NOT CONFIGURED YET</strong></span>';
  131. if (MODULE_PAYMENT_PAYPALWPP_SERVER =='sandbox') $this->title .= '<strong><span class="alert"> (sandbox active)</span></strong>';
  132. if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email') $this->title .= '<strong> (Debug)</strong>';
  133. if (!function_exists('curl_init')) $this->title .= '<strong><span class="alert"> CURL NOT FOUND. Cannot Use.</span></strong>';
  134. }
  135. } else {
  136. $this->description = MODULE_PAYMENT_PAYPALWPP_TEXT_DESCRIPTION;
  137. $this->title = MODULE_PAYMENT_PAYPALWPP_EC_TEXT_TITLE; //pp
  138. }
  139. if ((!defined('PAYPAL_OVERRIDE_CURL_WARNING') || (defined('PAYPAL_OVERRIDE_CURL_WARNING') && PAYPAL_OVERRIDE_CURL_WARNING != 'True')) && !function_exists('curl_init')) $this->enabled = false;
  140. $this->enableDebugging = (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email');
  141. $this->emailAlerts = (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Alerts Only');
  142. $this->doDPonly = (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE =='Payflow-US' && !(defined('MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC') && MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC == 'Yes'));
  143. $this->showPaymentPage = (MODULE_PAYMENT_PAYPALWPP_SKIP_PAYMENT_PAGE == 'No') ? true : false;
  144. $this->sort_order = MODULE_PAYMENT_PAYPALWPP_SORT_ORDER;
  145. $this->buttonSourceEC = 'ZenCart-EC_us';
  146. $this->buttonSourceDP = 'ZenCart-DP_us';
  147. if (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-UK') {
  148. $this->buttonSourceEC = 'ZenCart-EC_uk';
  149. $this->buttonSourceDP = 'ZenCart-DP_uk';
  150. }
  151. if (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-US') {
  152. $this->buttonSourceEC = 'ZenCart-ECGW_us';
  153. $this->buttonSourceDP = 'ZenCart-GW_us';
  154. }
  155. $this->order_pending_status = MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID;
  156. if ((int)MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID > 0) {
  157. $this->order_status = MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID;
  158. }
  159. $this->new_acct_notify = MODULE_PAYMENT_PAYPALWPP_NEW_ACCT_NOTIFY;
  160. $this->zone = (int)MODULE_PAYMENT_PAYPALWPP_ZONE;
  161. if (is_object($order)) $this->update_status();
  162. if (PROJECT_VERSION_MAJOR != '1' && substr(PROJECT_VERSION_MINOR, 0, 3) != '3.9') $this->enabled = false;
  163. $this->cards = array();
  164. // if operating in markflow mode, start EC process when submitting order
  165. if (!$this->in_special_checkout()) {
  166. $this->form_action_url = zen_href_link('ipn_main_handler.php', 'type=ec&markflow=1&clearSess=1&stage=final', 'SSL', true, true, true);
  167. }
  168. // debug setup
  169. if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_CATALOG . $this->_logDir;
  170. if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_SQL_CACHE;
  171. // Regular mode:
  172. if ($this->enableDebugging) $this->_logLevel = PEAR_LOG_INFO;
  173. // DEV MODE:
  174. if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $this->_logLevel = PEAR_LOG_DEBUG;
  175. if (IS_ADMIN_FLAG === true) $this->tableCheckup();
  176. }
  177. /**
  178. * Sets payment module status based on zone restrictions etc
  179. */
  180. function update_status() {
  181. global $order, $db;
  182. if ($this->enabled && (int)$this->zone > 0) {
  183. $check_flag = false;
  184. $sql = "SELECT zone_id
  185. FROM " . TABLE_ZONES_TO_GEO_ZONES . "
  186. WHERE geo_zone_id = :zoneId
  187. AND zone_country_id = :countryId
  188. ORDER BY zone_id";
  189. $sql = $db->bindVars($sql, ':zoneId', $this->zone, 'integer');
  190. $sql = $db->bindVars($sql, ':countryId', $order->billing['country']['id'], 'integer');
  191. $check = $db->Execute($sql);
  192. while (!$check->EOF) {
  193. if ($check->fields['zone_id'] < 1) {
  194. $check_flag = true;
  195. break;
  196. } elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
  197. $check_flag = true;
  198. break;
  199. }
  200. $check->MoveNext();
  201. }
  202. if (!$check_flag) {
  203. $this->enabled = false;
  204. }
  205. // module cannot be used for purchase > $10,000 USD
  206. $order_amount = $this->calc_order_amount($order->info['total'], 'USD');
  207. if ($order_amount > 10000) $this->enabled = false;
  208. if ($order->info['total'] == 0) $this->enabled = false;
  209. }
  210. }
  211. /**
  212. * Validate the credit card information via javascript (Number, Owner, and CVV Lengths)
  213. */
  214. function javascript_validation() {
  215. return false;
  216. }
  217. /**
  218. * Display Credit Card Information Submission Fields on the Checkout Payment Page
  219. */
  220. function selection() {
  221. $this->cc_type_check = '';
  222. /**
  223. * since we are NOT processing via the gateway, we will only display MarkFlow payment option, and no CC fields
  224. */
  225. return array('id' => $this->code,
  226. 'module' => '<img src="' . MODULE_PAYMENT_PAYPALEC_MARK_BUTTON_IMG . '" alt="' . MODULE_PAYMENT_PAYPALWPP_TEXT_BUTTON_ALTTEXT . '" /><span style="font-size:11px; font-family: Arial, Verdana;"> ' . MODULE_PAYMENT_PAYPALWPP_MARK_BUTTON_TXT . '</span>');
  227. }
  228. function pre_confirmation_check() {
  229. // Since this is an EC checkout, do nothing.
  230. return false;
  231. }
  232. /**
  233. * Display Payment Information for review on the Checkout Confirmation Page
  234. */
  235. function confirmation() {
  236. $confirmation = array('title' => '', 'fields' => array());
  237. return $confirmation;
  238. }
  239. /**
  240. * Prepare the hidden fields comprising the parameters for the Submit button on the checkout confirmation page
  241. */
  242. function process_button() {
  243. $_SESSION['paypal_ec_markflow'] = 1;
  244. return '';
  245. }
  246. /**
  247. * Prepare and submit the final authorization to PayPal via the appropriate means as configured
  248. */
  249. function before_process() {
  250. global $order, $doPayPal, $messageStack;
  251. $options = array();
  252. $optionsShip = array();
  253. $optionsNVP = array();
  254. $options = $this->getLineItemDetails($this->selectCurrency($order->info['currency']));
  255. //$this->zcLog('before_process - 1', 'Have line-item details:' . "\n" . print_r($options, true));
  256. // Initializing DESC field: using for comments related to tax-included pricing, populated by getLineItemDetails()
  257. $options['DESC'] = '';
  258. $doPayPal = $this->paypal_init();
  259. $this->zcLog('before_process - EC-1', 'Beginning EC mode');
  260. /****************************************
  261. * Do EC checkout
  262. ****************************************/
  263. // do not allow blank address to be sent to PayPal
  264. if ($_SESSION['paypal_ec_payer_info']['ship_street_1'] != '' && strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE') {
  265. $options = array_merge($options,
  266. array('SHIPTONAME' => $_SESSION['paypal_ec_payer_info']['ship_name'],
  267. 'SHIPTOSTREET' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
  268. 'SHIPTOSTREET2'=> $_SESSION['paypal_ec_payer_info']['ship_street_2'],
  269. 'SHIPTOCITY' => $_SESSION['paypal_ec_payer_info']['ship_city'],
  270. 'SHIPTOSTATE' => $_SESSION['paypal_ec_payer_info']['ship_state'],
  271. 'SHIPTOZIP' => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
  272. 'SHIPTOCOUNTRYCODE'=> $_SESSION['paypal_ec_payer_info']['ship_country_code'],
  273. ));
  274. $this->zcLog('before_process - EC-2', 'address overrides added:' . "\n" . print_r($options, true));
  275. }
  276. $this->zcLog('before_process - EC-3', 'address info added:' . "\n" . print_r($options, true));
  277. $options['BUTTONSOURCE'] = $this->buttonSourceEC;
  278. // If the customer has changed their shipping address,
  279. // override the shipping address in PayPal with the shipping
  280. // address that is selected in Zen Cart.
  281. if ($order->delivery['street_address'] != $_SESSION['paypal_ec_payer_info']['ship_street_1'] && $_SESSION['paypal_ec_payer_info']['ship_street_1'] != '') {
  282. $_GET['markflow'] = 2;
  283. if (($address_arr = $this->getOverrideAddress()) !== false) {
  284. // set the override var
  285. $options['ADDROVERRIDE'] = 1;
  286. // set the address info
  287. $options['SHIPTONAME'] = $address_arr['entry_firstname'] . ' ' . $address_arr['entry_lastname'];
  288. $options['SHIPTOSTREET'] = $address_arr['entry_street_address'];
  289. if ($address_arr['entry_suburb'] != '') $options['SHIPTOSTREET2'] = $address_arr['entry_suburb'];
  290. $options['SHIPTOCITY'] = $address_arr['entry_city'];
  291. $options['SHIPTOZIP'] = $address_arr['entry_postcode'];
  292. $options['SHIPTOSTATE'] = $address_arr['zone_code'];
  293. $options['SHIPTOCOUNTRYCODE'] = $address_arr['countries_iso_code_2'];
  294. }
  295. }
  296. // if these optional parameters are blank, remove them from transaction
  297. if (isset($options['SHIPTOSTREET2']) && trim($options['SHIPTOSTREET2']) == '') unset($options['SHIPTOSTREET2']);
  298. if (isset($options['SHIPTOPHONE']) && trim($options['SHIPTOPHONE']) == '') unset($options['SHIPTOPHONE']);
  299. // if State is not supplied, repeat the city so that it's not blank, otherwise PayPal croaks
  300. if ((!isset($options['SHIPTOSTATE']) || trim($options['SHIPTOSTATE']) == '') && $options['SHIPTOCITY'] != '') $options['SHIPTOSTATE'] = $options['SHIPTOCITY'];
  301. // FMF support
  302. $options['RETURNFMFDETAILS'] = (MODULE_PAYMENT_PAYPALWPP_EC_RETURN_FMF_DETAILS == 'Yes') ? 1 : 0;
  303. // Add note to track that this was an EC transaction (used in properly handling update IPNs related to EC transactions):
  304. $options['CUSTOM'] = 'EC-' . (int)$_SESSION['customer_id'] . '-' . time();
  305. // send the store name as transaction identifier, to help distinguish payments between multiple stores:
  306. $options['INVNUM'] = (int)$_SESSION['customer_id'] . '-' . time() . '-[' . substr(preg_replace('/[^a-zA-Z0-9_]/', '', STORE_NAME), 0, 30) . ']'; // (cannot send actual invoice number because it's not assigned until after payment is completed)
  307. $options['CURRENCY'] = $this->selectCurrency($order->info['currency']);
  308. $order_amount = $this->calc_order_amount($order->info['total'], $options['CURRENCY'], FALSE);
  309. // debug output
  310. $this->zcLog('before_process - EC-4', 'info being submitted:' . "\n" . $_SESSION['paypal_ec_token'] . ' ' . $_SESSION['paypal_ec_payer_id'] . ' ' . number_format($order_amount, 2) . "\n" . print_r($options, true));
  311. if (isset($options['DESC']) && $options['DESC'] == '') unset($options['DESC']);
  312. if (!isset($options['AMT'])) $options['AMT'] = number_format($order_amount, 2, '.', '');
  313. $response = $doPayPal->DoExpressCheckoutPayment($_SESSION['paypal_ec_token'],
  314. $_SESSION['paypal_ec_payer_id'],
  315. $options);
  316. $this->zcLog('before_process - EC-5', 'resultset:' . "\n" . urldecode(print_r($response, true)));
  317. // CHECK RESPONSE -- if error, actions are taken in the errorHandler
  318. $errorHandlerMessage = $this->_errorHandler($response, 'DoExpressCheckoutPayment');
  319. if ($this->fmfResponse != '') {
  320. $this->order_status = $this->order_pending_status;
  321. }
  322. // SUCCESS
  323. $this->payment_type = MODULE_PAYMENT_PAYPALWPP_EC_TEXT_TYPE;
  324. $this->responsedata = $response;
  325. if ($response['PAYMENTTYPE'] != '') $this->payment_type .= ' (' . urldecode($response['PAYMENTTYPE']) . ')';
  326. $this->transaction_id = trim($response['PNREF'] . ' ' . $response['TRANSACTIONID']);
  327. if (empty($response['PENDINGREASON']) ||
  328. $response['PENDINGREASON'] == 'none' ||
  329. $response['PENDINGREASON'] == 'completed' ||
  330. $response['PAYMENTSTATUS'] == 'Completed') {
  331. $this->payment_status = 'Completed';
  332. if ($this->order_status > 0) $order->info['order_status'] = $this->order_status;
  333. } else {
  334. if ($response['PAYMENTSTATUS'] == 'Pending')
  335. {
  336. if ($response['L_ERRORCODE0'] == 11610 && $response['PENDINGREASON'] == '') $response['PENDINGREASON'] = 'Pending FMF Review by Storeowner';
  337. }
  338. $this->payment_status = 'Pending (' . $response['PENDINGREASON'] . ')';
  339. $order->info['order_status'] = $this->order_pending_status;
  340. }
  341. $this->avs = 'N/A';
  342. $this->cvv2 = 'N/A';
  343. $this->correlationid = $response['CORRELATIONID'];
  344. $this->transactiontype = $response['TRANSACTIONTYPE'];
  345. $this->payment_time = urldecode($response['ORDERTIME']);
  346. $this->feeamt = urldecode($response['FEEAMT']);
  347. $this->taxamt = urldecode($response['TAXAMT']);
  348. $this->pendingreason = $response['PENDINGREASON'];
  349. $this->reasoncode = $response['REASONCODE'];
  350. $this->numitems = sizeof($order->products);
  351. $this->amt = urldecode($response['AMT'] . ' ' . $response['CURRENCYCODE']);
  352. $this->auth_code = (isset($this->response['AUTHCODE'])) ? $this->response['AUTHCODE'] : $this->response['TOKEN'];
  353. }
  354. /**
  355. * When the order returns from the processor, this stores the results in order-status-history and logs data for subsequent use
  356. */
  357. function after_process() {
  358. global $insert_id, $db, $order;
  359. // FMF
  360. if ($this->fmfResponse != '') {
  361. $detailedMessage = $insert_id . "\n" . $this->fmfResponse . "\n" . MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_INTRO . "\n" . print_r($this->fmfErrors, TRUE);
  362. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_SUBJECT . ' (' . $insert_id . ')', $detailedMessage, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($detailedMessage)), 'paymentalert');
  363. }
  364. // add a new OSH record for this order's PP details
  365. $commentString = "Transaction ID: :transID: " .
  366. (isset($this->responsedata['PPREF']) ? "\nPPRef: " . $this->responsedata['PPREF'] : "") .
  367. (isset($this->responsedata['AUTHCODE'])? "\nAuthCode: " . $this->responsedata['AUTHCODE'] : "") .
  368. "\nPayment Type: :pmtType: " .
  369. ($this->payment_time != '' ? "\nTimestamp: :pmtTime: " : "") .
  370. "\nPayment Status: :pmtStatus: " .
  371. (isset($this->responsedata['auth_exp']) ? "\nAuth-Exp: " . $this->responsedata['auth_exp'] : "") .
  372. ($this->avs != 'N/A' ? "\nAVS Code: ".$this->avs."\nCVV2 Code: ".$this->cvv2 : '') .
  373. (trim($this->amt) != '' ? "\nAmount: :orderAmt: " : "");
  374. $commentString = $db->bindVars($commentString, ':transID:', $this->transaction_id, 'noquotestring');
  375. $commentString = $db->bindVars($commentString, ':pmtType:', $this->payment_type, 'noquotestring');
  376. $commentString = $db->bindVars($commentString, ':pmtTime:', $this->payment_time, 'noquotestring');
  377. $commentString = $db->bindVars($commentString, ':pmtStatus:', $this->payment_status, 'noquotestring');
  378. $commentString = $db->bindVars($commentString, ':orderAmt:', $this->amt, 'noquotestring');
  379. $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=>$insert_id, 'type'=>'integer'),
  380. array('fieldName'=>'orders_status_id', 'value'=>$order->info['order_status'], 'type'=>'integer'),
  381. array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
  382. array('fieldName'=>'customer_notified', 'value'=>0, 'type'=>'integer'),
  383. array('fieldName'=>'comments', 'value'=>$commentString, 'type'=>'string'));
  384. $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  385. // store the PayPal order meta data -- used for later matching and back-end processing activities
  386. $paypal_order = array('order_id' => $insert_id,
  387. 'txn_type' => $this->transactiontype,
  388. 'module_name' => $this->code,
  389. 'module_mode' => MODULE_PAYMENT_PAYPALWPP_MODULE_MODE,
  390. 'reason_code' => $this->reasoncode,
  391. 'payment_type' => $this->payment_type,
  392. 'payment_status' => $this->payment_status,
  393. 'pending_reason' => $this->pendingreason,
  394. 'invoice' => urldecode($_SESSION['paypal_ec_token'] . $this->responsedata['PPREF']),
  395. 'first_name' => $_SESSION['paypal_ec_payer_info']['payer_firstname'],
  396. 'last_name' => $_SESSION['paypal_ec_payer_info']['payer_lastname'],
  397. 'payer_business_name' => $_SESSION['paypal_ec_payer_info']['payer_business'],
  398. 'address_name' => $_SESSION['paypal_ec_payer_info']['ship_name'],
  399. 'address_street' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
  400. 'address_city' => $_SESSION['paypal_ec_payer_info']['ship_city'],
  401. 'address_state' => $_SESSION['paypal_ec_payer_info']['ship_state'],
  402. 'address_zip' => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
  403. 'address_country' => $_SESSION['paypal_ec_payer_info']['ship_country'],
  404. 'address_status' => $_SESSION['paypal_ec_payer_info']['ship_address_status'],
  405. 'payer_email' => $_SESSION['paypal_ec_payer_info']['payer_email'],
  406. 'payer_id' => $_SESSION['paypal_ec_payer_id'],
  407. 'payer_status' => $_SESSION['paypal_ec_payer_info']['payer_status'],
  408. 'payment_date' => trim(preg_replace('/[^0-9-:]/', ' ', $this->payment_time)),
  409. 'business' => '',
  410. 'receiver_email' => (substr(MODULE_PAYMENT_PAYPALWPP_MODULE_MODE,0,7) == 'Payflow' ? MODULE_PAYMENT_PAYPALWPP_PFVENDOR : str_replace('_api1', '', MODULE_PAYMENT_PAYPALWPP_APIUSERNAME)),
  411. 'receiver_id' => '',
  412. 'txn_id' => $this->transaction_id,
  413. 'parent_txn_id' => '',
  414. 'num_cart_items' => (float)$this->numitems,
  415. 'mc_gross' => (float)$this->amt,
  416. 'mc_fee' => (float)urldecode($this->feeamt),
  417. 'mc_currency' => $this->responsedata['CURRENCYCODE'],
  418. 'settle_amount' => (float)urldecode($this->responsedata['SETTLEAMT']),
  419. 'settle_currency' => $this->responsedata['CURRENCYCODE'],
  420. 'exchange_rate' => (urldecode($this->responsedata['EXCHANGERATE']) > 0 ? urldecode($this->responsedata['EXCHANGERATE']) : 1.0),
  421. 'notify_version' => '0',
  422. 'verify_sign' =>'',
  423. 'date_added' => 'now()',
  424. 'memo' => (sizeof($this->fmfErrors) > 0 ? 'FMF Details ' . print_r($this->fmfErrors, TRUE) : '{Record generated by payment module}'),
  425. );
  426. zen_db_perform(TABLE_PAYPAL, $paypal_order);
  427. // Unregister the paypal session variables, making it necessary to start again for another purchase
  428. unset($_SESSION['paypal_ec_temp']);
  429. unset($_SESSION['paypal_ec_token']);
  430. unset($_SESSION['paypal_ec_payer_id']);
  431. unset($_SESSION['paypal_ec_payer_info']);
  432. unset($_SESSION['paypal_ec_final']);
  433. unset($_SESSION['paypal_ec_markflow']);
  434. }
  435. /**
  436. * Build admin-page components
  437. *
  438. * @param int $zf_order_id
  439. * @return string
  440. */
  441. function admin_notification($zf_order_id) {
  442. if (!defined('MODULE_PAYMENT_PAYPALWPP_STATUS')) return '';
  443. global $db;
  444. $module = $this->code;
  445. $output = '';
  446. $response = $this->_GetTransactionDetails($zf_order_id);
  447. //$response = $this->_TransactionSearch('2006-12-01T00:00:00Z', $zf_order_id);
  448. $sql = "SELECT * from " . TABLE_PAYPAL . " WHERE order_id = :orderID
  449. AND parent_txn_id = '' AND order_id > 0
  450. ORDER BY paypal_ipn_id DESC LIMIT 1";
  451. $sql = $db->bindVars($sql, ':orderID', $zf_order_id, 'integer');
  452. $ipn = $db->Execute($sql);
  453. if ($ipn->RecordCount() == 0) $ipn->fields = array();
  454. if (file_exists(DIR_FS_CATALOG . DIR_WS_MODULES . 'payment/paypal/paypalwpp_admin_notification.php')) require(DIR_FS_CATALOG . DIR_WS_MODULES . 'payment/paypal/paypalwpp_admin_notification.php');
  455. return $output;
  456. }
  457. /**
  458. * Used to read details of an existing transaction. FOR FUTURE USE.
  459. */
  460. function _GetTransactionDetails($oID) {
  461. global $db, $messageStack, $doPayPal;
  462. $doPayPal = $this->paypal_init();
  463. // look up history on this order from PayPal table
  464. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID order by last_modified DESC, date_added DESC, parent_txn_id DESC, paypal_ipn_id DESC ";
  465. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  466. $zc_ppHist = $db->Execute($sql);
  467. if ($zc_ppHist->RecordCount() == 0) return false;
  468. $txnID = $zc_ppHist->fields['txn_id'];
  469. /**
  470. * Read data from PayPal
  471. */
  472. $response = $doPayPal->GetTransactionDetails($txnID);
  473. $error = $this->_errorHandler($response, 'GetTransactionDetails', 10007);
  474. if ($error === false) {
  475. return false;
  476. } else {
  477. return $response;
  478. }
  479. }
  480. /**
  481. * Used to read details of existing transactions. FOR FUTURE USE.
  482. */
  483. function _TransactionSearch($startDate = '', $oID = '', $criteria = '') {
  484. global $db, $messageStack, $doPayPal;
  485. $doPayPal = $this->paypal_init();
  486. // look up history on this order from PayPal table
  487. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  488. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  489. $zc_ppHist = $db->Execute($sql);
  490. if ($zc_ppHist->RecordCount() == 0) return false;
  491. $txnID = $zc_ppHist->fields['txn_id'];
  492. $startDate = $zc_ppHist->fields['payment_date'];
  493. $timeval = time();
  494. if ($startDate == '') $startDate = date('Y-m-d', $timeval) . 'T' . date('h:i:s', $timeval) . 'Z';
  495. /**
  496. * Read data from PayPal
  497. */
  498. $response = $doPayPal->TransactionSearch($startDate, $txnID, $email, $criteria);
  499. $error = $this->_errorHandler($response, 'TransactionSearch');
  500. if ($error === false) {
  501. return false;
  502. } else {
  503. return $response;
  504. }
  505. }
  506. /**
  507. * Evaluate installation status of this module. Returns true if the status key is found.
  508. */
  509. function check() {
  510. global $db;
  511. if (!isset($this->_check)) {
  512. $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PAYPALWPP_STATUS'");
  513. $this->_check = !$check_query->EOF;
  514. }
  515. return $this->_check;
  516. }
  517. /**
  518. * Installs all the configuration keys for this module
  519. */
  520. function install() {
  521. global $db, $messageStack;
  522. if (defined('MODULE_PAYMENT_PAYPALWPP_STATUS')) {
  523. $messageStack->add_session('Express Checkout module already installed.', 'error');
  524. zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypalwpp', 'NONSSL'));
  525. return 'failed';
  526. }
  527. if (defined('MODULE_PAYMENT_PAYPAL_STATUS')) {
  528. $messageStack->add_session('NOTE: You already have the PayPal Website Payments Standard module installed. You should REMOVE it if you want to install Express Checkout.', 'error');
  529. zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypal', 'NONSSL'));
  530. return 'failed';
  531. }
  532. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable this Payment Module', 'MODULE_PAYMENT_PAYPALWPP_STATUS', 'True', 'Do you want to enable this payment module?', '6', '25', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
  533. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Live or Sandbox', 'MODULE_PAYMENT_PAYPALWPP_SERVER', 'live', '<strong>Live: </strong> Used to process Live transactions<br><strong>Sandbox: </strong>For developers and testing', '6', '25', 'zen_cfg_select_option(array(\'live\', \'sandbox\'), ', now())");
  534. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Require Confirmed Address', 'MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS', 'No', 'Do you want to require that your (not-logged-in) customers use a *confirmed* address when choosing their shipping address in PayPal?<br />(this is ignored for logged-in customers)', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
  535. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Select Cheapest Shipping Automatically', 'MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING', 'Yes', 'When customer returns from PayPal, do we want to automatically select the Cheapest shipping method and skip the shipping page? (making it more *express*)<br />Note: enabling this means the customer does *not* have easy access to select an alternate shipping method (without going back to the Checkout-Step-1 page)', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
  536. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Skip Payment Page', 'MODULE_PAYMENT_PAYPALWPP_SKIP_PAYMENT_PAGE', 'Yes', 'If the customer is checking out with Express Checkout, do you want to skip the checkout payment page, making things more *express*? <br /><strong>(NOTE: The Payment Page will auto-display regardless of this setting if you have Coupons or Gift Certificates enabled in your store.)</strong>', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
  537. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Automatic Account Creation', 'MODULE_PAYMENT_PAYPALWPP_NEW_ACCT_NOTIFY', 'Yes', 'If a visitor is not an existing customer, a Zen Cart account is created for them. Would you like make it a permanent account and send them an email containing their login information?<br />NOTE: Permanent accounts are auto-created if the customer purchases downloads or gift certificates, regardless of this setting.', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
  538. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_PAYPALWPP_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '25', now())");
  539. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PAYPALWPP_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '25', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
  540. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID', '2', 'Set the status of orders paid with this payment module to this value. <br /><strong>Recommended: Processing[2]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
  541. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Unpaid Order Status', 'MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID', '1', 'Set the status of unpaid orders made with this payment module to this value. <br /><strong>Recommended: Pending[1]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
  542. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Refund Order Status', 'MODULE_PAYMENT_PAYPALWPP_REFUNDED_STATUS_ID', '1', 'Set the status of refunded orders to this value. <br /><strong>Recommended: Pending[1]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
  543. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PayPal Page Style', 'MODULE_PAYMENT_PAYPALWPP_PAGE_STYLE', 'Primary', 'The page-layout style you want customers to see when they visit the PayPal site. You can configure your <strong>Custom Page Styles</strong> in your PayPal Profile settings. This value is case-sensitive.', '6', '25', now())");
  544. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Payment Action', 'MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE', 'Final Sale', 'How do you want to obtain payment?<br /><strong>Default: Final Sale</strong>', '6', '25', 'zen_cfg_select_option(array(\'Auth Only\', \'Final Sale\'), ', now())");
  545. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Currency', 'MODULE_PAYMENT_PAYPALWPP_CURRENCY', 'Selected Currency', 'Which currency should the order be sent to PayPal as? <br />NOTE: if an unsupported currency is sent to PayPal, it will be auto-converted to USD (or GBP if using UK account)<br /><strong>Default: Selected Currency</strong>', '6', '25', 'zen_cfg_select_option(array(\'Selected Currency\', \'Only USD\', \'Only AUD\', \'Only CAD\', \'Only EUR\', \'Only GBP\', \'Only CHF\', \'Only CZK\', \'Only DKK\', \'Only HKD\', \'Only HUF\', \'Only JPY\', \'Only NOK\', \'Only NZD\', \'Only PLN\', \'Only SEK\', \'Only SGD\', \'Only THB\', \'Only MXN\', \'Only ILS\', \'Only PHP\', \'Only TWD\', \'Only BRL\', \'Only MYR\'), ', now())");
  546. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Fraud Mgmt Filters - FMF', 'MODULE_PAYMENT_PAYPALWPP_EC_RETURN_FMF_DETAILS', 'No', 'If you have enabled FMF support in your PayPal account and wish to utilize it in your transactions, set this to yes. Otherwise, leave it at No.', '6', '25','zen_cfg_select_option(array(\'No\', \'Yes\'), ', now())");
  547. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Signature -- Username', 'MODULE_PAYMENT_PAYPALWPP_APIUSERNAME', '', 'The API Username from your PayPal API Signature settings under *API Access*. This value typically looks like an email address and is case-sensitive.', '6', '25', now())");
  548. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('API Signature -- Password', 'MODULE_PAYMENT_PAYPALWPP_APIPASSWORD', '', 'The API Password from your PayPal API Signature settings under *API Access*. This value is a 16-character code and is case-sensitive.', '6', '25', now(), 'zen_cfg_password_input(', 'zen_cfg_password_display')");
  549. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('API Signature -- Signature Code', 'MODULE_PAYMENT_PAYPALWPP_APISIGNATURE', '', 'The API Signature from your PayPal API Signature settings under *API Access*. This value is a 56-character code, and is case-sensitive.', '6', '25', now(), '', 'zen_cfg_password_display')");
  550. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PAYFLOW: User', 'MODULE_PAYMENT_PAYPALWPP_PFUSER', '', 'If you set up one or more additional users on the account, this value is the ID of the user authorized to process transactions. Otherwise it should be the same value as VENDOR. This value is case-sensitive.', '6', '25', now())");
  551. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PAYFLOW: Partner', 'MODULE_PAYMENT_PAYPALWPP_PFPARTNER', 'ZenCart', 'Your Payflow Partner name linked to your Payflow account. This value is case-sensitive.<br />Typical values: <strong>PayPal</strong> or <strong>ZenCart</strong>', '6', '25', now())");
  552. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PAYFLOW: Vendor', 'MODULE_PAYMENT_PAYPALWPP_PFVENDOR', '', 'Your merchant login ID that you created when you registered for the Payflow Pro account. This value is case-sensitive.', '6', '25', now())");
  553. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('PAYFLOW: Password', 'MODULE_PAYMENT_PAYPALWPP_PFPASSWORD', '', 'The 6- to 32-character password that you defined while registering for the account. This value is case-sensitive.', '6', '25', now(), 'zen_cfg_password_input(', 'zen_cfg_password_display')");
  554. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('PayPal Mode', 'MODULE_PAYMENT_PAYPALWPP_MODULE_MODE', 'PayPal', 'Which PayPal API system should be used for processing? <br /><u>Choices:</u><br /><font color=green>For choice #1, you need to supply <strong>API Settings</strong> above.</font><br /><strong>1. PayPal</strong> = Express Checkout with a regular PayPal account<br />or<br /><font color=green>for choices 2 &amp; 3 you need to supply <strong>PAYFLOW settings</strong>, below (and have a Payflow account)</font><br /><strong>2. Payflow-UK</strong> = Website Payments Pro UK Payflow Edition<br /><strong>3. Payflow-US</strong> = Payflow Pro Gateway only<!--<br /><strong>4. PayflowUS+EC</strong> = Payflow Pro with Express Checkout-->', '6', '25', 'zen_cfg_select_option(array(\'PayPal\', \'Payflow-UK\', \'Payflow-US\'), ', now())");
  555. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Debug Mode', 'MODULE_PAYMENT_PAYPALWPP_DEBUGGING', 'Off', 'Would you like to enable debug mode? A complete detailed log of failed transactions will be emailed to the store owner.', '6', '25', 'zen_cfg_select_option(array(\'Off\', \'Alerts Only\', \'Log File\', \'Log and Email\'), ', now())");
  556. $this->notify('NOTIFY_PAYMENT_PAYPALWPP_INSTALLED');
  557. }
  558. function keys() {
  559. $keys_list = array('MODULE_PAYMENT_PAYPALWPP_STATUS', 'MODULE_PAYMENT_PAYPALWPP_SORT_ORDER', 'MODULE_PAYMENT_PAYPALWPP_ZONE', 'MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID', 'MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID', 'MODULE_PAYMENT_PAYPALWPP_REFUNDED_STATUS_ID', 'MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS', 'MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING', 'MODULE_PAYMENT_PAYPALWPP_SKIP_PAYMENT_PAGE', 'MODULE_PAYMENT_PAYPALWPP_NEW_ACCT_NOTIFY', 'MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE', 'MODULE_PAYMENT_PAYPALWPP_CURRENCY', 'MODULE_PAYMENT_PAYPALWPP_PAGE_STYLE', 'MODULE_PAYMENT_PAYPALWPP_APIUSERNAME', 'MODULE_PAYMENT_PAYPALWPP_APIPASSWORD', 'MODULE_PAYMENT_PAYPALWPP_APISIGNATURE', 'MODULE_PAYMENT_PAYPALWPP_MODULE_MODE', /*'MODULE_PAYMENT_PAYPALWPP_PFPARTNER', 'MODULE_PAYMENT_PAYPALWPP_PFVENDOR', 'MODULE_PAYMENT_PAYPALWPP_PFUSER', 'MODULE_PAYMENT_PAYPALWPP_PFPASSWORD', */'MODULE_PAYMENT_PAYPALWPP_SERVER', 'MODULE_PAYMENT_PAYPALWPP_DEBUGGING');
  560. if (IS_ADMIN_FLAG === true && (PAYPAL_DEV_MODE == 'true' || strstr(MODULE_PAYMENT_PAYPALWPP_MODULE_MODE, 'Payflow'))) {
  561. $keys_list = array_merge($keys_list, array('MODULE_PAYMENT_PAYPALWPP_PFPARTNER', 'MODULE_PAYMENT_PAYPALWPP_PFVENDOR', 'MODULE_PAYMENT_PAYPALWPP_PFUSER', 'MODULE_PAYMENT_PAYPALWPP_PFPASSWORD'));
  562. }
  563. return $keys_list;
  564. }
  565. /**
  566. * De-install this module
  567. */
  568. function remove() {
  569. global $messageStack;
  570. // cannot remove EC if DP installed:
  571. if (defined('MODULE_PAYMENT_PAYPALDP_STATUS')) {
  572. // this language text is hard-coded in english since Website Payments Pro is not yet available in any countries that speak any other language at this time.
  573. $messageStack->add_session('<strong>Sorry, you must remove Website Payments Pro (paypaldp) first.</strong> Website Payments Pro requires that you offer Express Checkout to your customers.<br /><a href="' . zen_href_link('modules.php?set=payment&module=paypaldp', '', 'NONSSL') . '">Click here to edit or remove your Website Payments Pro module.</a>' , 'error');
  574. zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypalwpp', 'NONSSL'));
  575. return 'failed';
  576. }
  577. global $db;
  578. $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key LIKE 'MODULE\_PAYMENT\_PAYPALWPP\_%'");
  579. $this->notify('NOTIFY_PAYMENT_PAYPALWPP_UNINSTALLED');
  580. }
  581. /**
  582. * Check settings and conditions to determine whether we are in an Express Checkout phase or not
  583. */
  584. function in_special_checkout() {
  585. if ((defined('MODULE_PAYMENT_PAYPALWPP_STATUS') && MODULE_PAYMENT_PAYPALWPP_STATUS == 'True') &&
  586. !empty($_SESSION['paypal_ec_token']) &&
  587. !empty($_SESSION['paypal_ec_payer_id']) &&
  588. !empty($_SESSION['paypal_ec_payer_info'])) {
  589. $this->flagDisablePaymentAddressChange = true;
  590. return true;
  591. }
  592. }
  593. /**
  594. * Determine whether the shipping-edit button should be displayed or not
  595. */
  596. function alterShippingEditButton() {
  597. return false;
  598. if ($this->in_special_checkout() && empty($_SESSION['paypal_ec_markflow'])) {
  599. return zen_href_link('ipn_main_handler.php', 'type=ec&clearSess=1', 'SSL', true,true, true);
  600. }
  601. }
  602. /**
  603. * Debug Logging support
  604. */
  605. function zcLog($stage, $message) {
  606. static $tokenHash;
  607. if ($tokenHash == '') $tokenHash = '_' . zen_create_random_value(4);
  608. if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log and Email' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File') {
  609. $token = (isset($_SESSION['paypal_ec_token'])) ? $_SESSION['paypal_ec_token'] : preg_replace('/[^0-9.A-Z\-]/', '', $_GET['token']);
  610. $token = ($token == '') ? date('m-d-Y-H-i') : $token; // or time()
  611. $token .= $tokenHash;
  612. $file = $this->_logDir . '/' . $this->code . '_Paypal_Action_' . $token . '.log';
  613. if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $file = $this->_logDir . '/' . $this->code . '_Paypal_Debug_' . $token . '.log';
  614. $fp = @fopen($file, 'a');
  615. @fwrite($fp, date('M-d-Y H:i:s') . ' (' . time() . ')' . "\n" . $stage . "\n" . $message . "\n=================================\n\n");
  616. @fclose($fp);
  617. }
  618. $this->_doDebug($stage, $message, false);
  619. }
  620. /**
  621. * Debug Emailing support
  622. */
  623. function _doDebug($subject = 'PayPal debug data', $data, $useSession = true) {
  624. if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log and Email') {
  625. $data = urldecode($data) . "\n\n";
  626. if ($useSession) $data .= "\nSession data: " . print_r($_SESSION, true);
  627. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, $subject, $this->code . "\n" . $data, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($this->code . "\n" . $data)), 'debug');
  628. }
  629. }
  630. /**
  631. * Initialize the PayPal/PayflowPro object for communication to the processing gateways
  632. */
  633. function paypal_init() {
  634. if (!defined('MODULE_PAYMENT_PAYPALWPP_STATUS') || !defined('MODULE_PAYMENT_PAYPALWPP_SERVER')) {
  635. $doPayPal = new paypal_curl(array('mode' => 'NOTCONFIGURED'));
  636. return $doPayPal;
  637. }
  638. $ec_uses_gateway = (defined('MODULE_PAYMENT_PAYPALWPP_PRO20_EC_METHOD') && MODULE_PAYMENT_PAYPALWPP_PRO20_EC_METHOD == 'Payflow') ? true : false;
  639. if (substr(MODULE_PAYMENT_PAYPALWPP_MODULE_MODE,0,7) == 'Payflow') {
  640. $doPayPal = new paypal_curl(array('mode' => 'payflow',
  641. 'user' => trim(MODULE_PAYMENT_PAYPALWPP_PFUSER),
  642. 'vendor' => trim(MODULE_PAYMENT_PAYPALWPP_PFVENDOR),
  643. 'partner'=> trim(MODULE_PAYMENT_PAYPALWPP_PFPARTNER),
  644. 'pwd' => trim(MODULE_PAYMENT_PAYPALWPP_PFPASSWORD),
  645. 'server' => MODULE_PAYMENT_PAYPALWPP_SERVER));
  646. $doPayPal->_endpoints = array('live' => 'https://payflowpro.paypal.com/transaction',
  647. 'sandbox' => 'https://pilot-payflowpro.paypal.com/transaction');
  648. } else {
  649. $doPayPal = new paypal_curl(array('mode' => 'nvp',
  650. 'user' => trim(MODULE_PAYMENT_PAYPALWPP_APIUSERNAME),
  651. 'pwd' => trim(MODULE_PAYMENT_PAYPALWPP_APIPASSWORD),
  652. 'signature' => trim(MODULE_PAYMENT_PAYPALWPP_APISIGNATURE),
  653. 'version' => '60.0',
  654. 'server' => MODULE_PAYMENT_PAYPALWPP_SERVER));
  655. $doPayPal->_endpoints = array('live' => 'https://api-3t.paypal.com/nvp',
  656. 'sandbox' => 'https://api.sandbox.paypal.com/nvp');
  657. }
  658. // set logging options
  659. $doPayPal->_logDir = $this->_logDir;
  660. // $doPayPal->_logLevel = $this->_logLevel;
  661. // set proxy options if configured
  662. if (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '') {
  663. $proxy_tunnel_flag = (defined('CURL_PROXY_TUNNEL_FLAG') && strtoupper(CURL_PROXY_TUNNEL_FLAG) == 'FALSE') ? false : true;
  664. $doPayPal->setCurlOption(CURLOPT_HTTPPROXYTUNNEL, $proxy_tunnel_flag);
  665. $doPayPal->setCurlOption(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  666. $doPayPal->setCurlOption(CURLOPT_PROXY, CURL_PROXY_SERVER_DETAILS);
  667. }
  668. // transaction processing mode
  669. $doPayPal->_trxtype = (in_array(MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE, array('Auth Only', 'Order'))) ? 'A' : 'S';
  670. return $doPayPal;
  671. }
  672. /**
  673. * Determine which PayPal URL to direct the customer's browser to when needed
  674. */
  675. function getPayPalLoginServer() {
  676. if (MODULE_PAYMENT_PAYPALWPP_SERVER == 'live') {
  677. // live url
  678. $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
  679. } else {
  680. // sandbox url
  681. $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
  682. }
  683. return $paypal_url;
  684. }
  685. /**
  686. * Used to submit a refund for a given transaction. FOR FUTURE USE.
  687. */
  688. function _doRefund($oID, $amount = 'Full', $note = '') {
  689. global $db, $doPayPal, $messageStack;
  690. $new_order_status = (int)MODULE_PAYMENT_PAYPALWPP_REFUNDED_STATUS_ID;
  691. $orig_order_amount = 0;
  692. $doPayPal = $this->paypal_init();
  693. $proceedToRefund = false;
  694. $refundNote = strip_tags(zen_db_input($_POST['refnote']));
  695. if (isset($_POST['fullrefund']) && $_POST['fullrefund'] == MODULE_PAYMENT_PAYPAL_ENTRY_REFUND_BUTTON_TEXT_FULL) {
  696. $refundAmt = 'Full';
  697. if (isset($_POST['reffullconfirm']) && $_POST['reffullconfirm'] == 'on') {
  698. $proceedToRefund = true;
  699. } else {
  700. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_REFUND_FULL_CONFIRM_ERROR, 'error');
  701. }
  702. }
  703. if (isset($_POST['partialrefund']) && $_POST['partialrefund'] == MODULE_PAYMENT_PAYPAL_ENTRY_REFUND_BUTTON_TEXT_PARTIAL) {
  704. $refundAmt = (float)$_POST['refamt'];
  705. $proceedToRefund = true;
  706. if ($refundAmt == 0) {
  707. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_REFUND_AMOUNT, 'error');
  708. $proceedToRefund = false;
  709. }
  710. }
  711. // look up history on this order from PayPal table
  712. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  713. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  714. $zc_ppHist = $db->Execute($sql);
  715. if ($zc_ppHist->RecordCount() == 0) return false;
  716. $txnID = $zc_ppHist->fields['txn_id'];
  717. $PFamt = $zc_ppHist->fields['mc_gross'];
  718. if ($doPayPal->_mode == 'payflow' && $refundAmt == 'Full') $refundAmt = $PFamt;
  719. /**
  720. * Submit refund request to PayPal
  721. */
  722. if ($proceedToRefund) {
  723. $response = $doPayPal->RefundTransaction($oID, $txnID, $refundAmt, $refundNote);
  724. $error = $this->_errorHandler($response, 'DoRefund');
  725. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  726. if (!$error) {
  727. if (!isset($response['GROSSREFUNDAMT'])) $response['GROSSREFUNDAMT'] = $refundAmt;
  728. // Success, so save the results
  729. $sql_data_array = array('orders_id' => $oID,
  730. 'orders_status_id' => (int)$new_order_status,
  731. 'date_added' => 'now()',
  732. 'comments' => 'REFUND INITIATED. Trans ID:' . $response['REFUNDTRANSACTIONID'] . $response['PNREF']. "\n" . /*' Net Refund Amt:' . urldecode($response['NETREFUNDAMT']) . "\n" . ' Fee Refund Amt: ' . urldecode($response['FEEREFUNDAMT']) . "\n" . */' Gross Refund Amt: ' . urldecode($response['GROSSREFUNDAMT']) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $refundNote,
  733. 'customer_notified' => 0
  734. );
  735. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  736. $db->Execute("update " . TABLE_ORDERS . "
  737. set orders_status = '" . (int)$new_order_status . "'
  738. where orders_id = '" . (int)$oID . "'");
  739. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_REFUND_INITIATED, urldecode($response['GROSSREFUNDAMT']), urldecode($response['REFUNDTRANSACTIONID']). $response['PNREF']), 'success');
  740. return true;
  741. }
  742. }
  743. }
  744. /**
  745. * Used to authorize part of a given previously-initiated transaction. FOR FUTURE USE.
  746. */
  747. function _doAuth($oID, $amt, $currency = 'USD') {
  748. global $db, $doPayPal, $messageStack;
  749. $doPayPal = $this->paypal_init();
  750. $authAmt = $amt;
  751. $new_order_status = (int)MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID;
  752. if (isset($_POST['orderauth']) && $_POST['orderauth'] == MODULE_PAYMENT_PAYPAL_ENTRY_AUTH_BUTTON_TEXT_PARTIAL) {
  753. $authAmt = (float)$_POST['authamt'];
  754. $new_order_status = MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID;
  755. if (isset($_POST['authconfirm']) && $_POST['authconfirm'] == 'on') {
  756. $proceedToAuth = true;
  757. } else {
  758. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_AUTH_CONFIRM_ERROR, 'error');
  759. $proceedToAuth = false;
  760. }
  761. if ($authAmt == 0) {
  762. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_AUTH_AMOUNT, 'error');
  763. $proceedToAuth = false;
  764. }
  765. }
  766. // look up history on this order from PayPal table
  767. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  768. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  769. $zc_ppHist = $db->Execute($sql);
  770. if ($zc_ppHist->RecordCount() == 0) return false;
  771. $txnID = $zc_ppHist->fields['txn_id'];
  772. /**
  773. * Submit auth request to PayPal
  774. */
  775. if ($proceedToAuth) {
  776. $response = $doPayPal->DoAuthorization($txnID, $authAmt, $currency);
  777. $error = $this->_errorHandler($response, 'DoAuthorization');
  778. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  779. if (!$error) {
  780. // Success, so save the results
  781. $sql_data_array = array('orders_id' => (int)$oID,
  782. 'orders_status_id' => (int)$new_order_status,
  783. 'date_added' => 'now()',
  784. 'comments' => 'AUTHORIZATION ADDED. Trans ID: ' . urldecode($response['TRANSACTIONID']) . "\n" . ' Amount:' . urldecode($response['AMT']) . ' ' . $currency,
  785. 'customer_notified' => -1
  786. );
  787. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  788. $db->Execute("update " . TABLE_ORDERS . "
  789. set orders_status = '" . (int)$new_order_status . "'
  790. where orders_id = '" . (int)$oID . "'");
  791. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_AUTH_INITIATED, urldecode($response['AMT'])), 'success');
  792. return true;
  793. }
  794. }
  795. }
  796. /**
  797. * Used to capture part or all of a given previously-authorized transaction. FOR FUTURE USE.
  798. * (alt value for $captureType = 'NotComplete')
  799. */
  800. function _doCapt($oID, $captureType = 'Complete', $amt = 0, $currency = 'USD', $note = '') {
  801. global $db, $doPayPal, $messageStack;
  802. $doPayPal = $this->paypal_init();
  803. //@TODO: Read current order status and determine best status to set this to
  804. $new_order_status = (int)MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID;
  805. $orig_order_amount = 0;
  806. $doPayPal = $this->paypal_init();
  807. $proceedToCapture = false;
  808. $captureNote = strip_tags(zen_db_input($_POST['captnote']));
  809. if (isset($_POST['captfullconfirm']) && $_POST['captfullconfirm'] == 'on') {
  810. $proceedToCapture = true;
  811. } else {
  812. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_CAPTURE_FULL_CONFIRM_ERROR, 'error');
  813. }
  814. if (isset($_POST['captfinal']) && $_POST['captfinal'] == 'on') {
  815. $captureType = 'Complete';
  816. } else {
  817. $captureType = 'NotComplete';
  818. }
  819. if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_PAYPAL_ENTRY_CAPTURE_BUTTON_TEXT_FULL) {
  820. $captureAmt = (float)$_POST['captamt'];
  821. if ($captureAmt == 0) {
  822. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
  823. $proceedToCapture = false;
  824. }
  825. }
  826. // look up history on this order from PayPal table
  827. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  828. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  829. $zc_ppHist = $db->Execute($sql);
  830. if ($zc_ppHist->RecordCount() == 0) return false;
  831. $txnID = $zc_ppHist->fields['txn_id'];
  832. /**
  833. * Submit capture request to PayPal
  834. */
  835. if ($proceedToCapture) {
  836. $response = $doPayPal->DoCapture($txnID, $captureAmt, $currency, $captureType, '', $captureNote);
  837. $error = $this->_errorHandler($response, 'DoCapture');
  838. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  839. if (!$error) {
  840. if (isset($response['PNREF'])) {
  841. if (!isset($response['AMT'])) $response['AMT'] = $captureAmt;
  842. if (!isset($response['ORDERTIME'])) $response['ORDERTIME'] = date("M-d-Y h:i:s");
  843. }
  844. // Success, so save the results
  845. $sql_data_array = array('orders_id' => (int)$oID,
  846. 'orders_status_id' => (int)$new_order_status,
  847. 'date_added' => 'now()',
  848. 'comments' => 'FUNDS COLLECTED. Trans ID: ' . urldecode($response['TRANSACTIONID']) . $response['PNREF']. "\n" . ' Amount: ' . urldecode($response['AMT']) . ' ' . $currency . "\n" . 'Time: ' . urldecode($response['ORDERTIME']) . "\n" . (isset($response['RECEIPTID']) ? 'Receipt ID: ' . urldecode($response['RECEIPTID']) : 'Auth Code: ' . (isset($response['AUTHCODE']) && $response['AUTHCODE'] != '' ? $response['AUTHCODE'] : $response['CORRELATIONID'])) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $captureNote,
  849. 'customer_notified' => 0
  850. );
  851. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  852. $db->Execute("update " . TABLE_ORDERS . "
  853. set orders_status = '" . (int)$new_order_status . "'
  854. where orders_id = '" . (int)$oID . "'");
  855. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_CAPT_INITIATED, urldecode($response['AMT']), urldecode($response['RECEIPTID'] . (isset($response['AUTHCODE']) && $response['AUTHCODE'] != '' ? $response['AUTHCODE'] : $response['CORRELATIONID']) ). $response['PNREF']), 'success');
  856. return true;
  857. }
  858. }
  859. }
  860. /**
  861. * Used to void a given previously-authorized transaction. FOR FUTURE USE.
  862. */
  863. function _doVoid($oID, $note = '') {
  864. global $db, $doPayPal, $messageStack;
  865. $new_order_status = (int)MODULE_PAYMENT_PAYPALWPP_REFUNDED_STATUS_ID;
  866. $doPayPal = $this->paypal_init();
  867. $voidNote = strip_tags(zen_db_input($_POST['voidnote']));
  868. $voidAuthID = trim(strip_tags(zen_db_input($_POST['voidauthid'])));
  869. if (isset($_POST['ordervoid']) && $_POST['ordervoid'] == MODULE_PAYMENT_PAYPAL_ENTRY_VOID_BUTTON_TEXT_FULL) {
  870. if (isset($_POST['voidconfirm']) && $_POST['voidconfirm'] == 'on') {
  871. $proceedToVoid = true;
  872. } else {
  873. $messageStack->add_session(MODULE_PAYMENT_PAYPALWPP_TEXT_VOID_CONFIRM_ERROR, 'error');
  874. }
  875. }
  876. // look up history on this order from PayPal table
  877. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  878. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  879. $sql = $db->bindVars($sql, ':transID', $voidAuthID, 'string');
  880. $zc_ppHist = $db->Execute($sql);
  881. if ($zc_ppHist->RecordCount() == 0) return false;
  882. $txnID = $zc_ppHist->fields['txn_id'];
  883. /**
  884. * Submit void request to PayPal
  885. */
  886. if ($proceedToVoid) {
  887. $response = $doPayPal->DoVoid($voidAuthID, $voidNote);
  888. $error = $this->_errorHandler($response, 'DoVoid');
  889. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  890. if (!$error) {
  891. // Success, so save the results
  892. $sql_data_array = array('orders_id' => (int)$oID,
  893. 'orders_status_id' => (int)$new_order_status,
  894. 'date_added' => 'now()',
  895. 'comments' => 'VOIDED. Trans ID: ' . urldecode($response['AUTHORIZATIONID']). $response['PNREF'] . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $voidNote,
  896. 'customer_notified' => 0
  897. );
  898. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  899. $db->Execute("update " . TABLE_ORDERS . "
  900. set orders_status = '" . (int)$new_order_status . "'
  901. where orders_id = '" . (int)$oID . "'");
  902. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_VOID_INITIATED, urldecode($response['AUTHORIZATIONID']) . $response['PNREF']), 'success');
  903. return true;
  904. }
  905. }
  906. }
  907. /**
  908. * Determine the language to use when visiting the PayPal site
  909. */
  910. function getLanguageCode() {
  911. global $order;
  912. $lang_code = '';
  913. $orderISO = zen_get_countries($order->customer['country']['id'], true);
  914. $storeISO = zen_get_countries(STORE_COUNTRY, true);
  915. if (in_array(strtoupper($orderISO['countries_iso_code_2']), array('US', 'AU', 'DE', 'FR', 'IT', 'GB', 'ES', 'AT', 'BE', 'CA', 'CH', 'CN', 'NL', 'PL'))) {
  916. $lang_code = strtoupper($orderISO['countries_iso_code_2']);
  917. } elseif (in_array(strtoupper($storeISO['countries_iso_code_2']), array('US', 'AU', 'DE', 'FR', 'IT', 'GB', 'ES', 'AT', 'BE', 'CA', 'CH', 'CN', 'NL', 'PL'))) {
  918. $lang_code = strtoupper($storeISO['countries_iso_code_2']);
  919. } elseif (in_array(strtoupper($_SESSION['languages_code']), array('EN', 'US', 'AU', 'DE', 'FR', 'IT', 'GB', 'ES', 'AT', 'BE', 'CA', 'CH', 'CN', 'NL', 'PL'))) {
  920. $lang_code = $_SESSION['languages_code'];
  921. }
  922. if (strtoupper($lang_code) == 'EN') $lang_code = 'US';
  923. //return $orderISO['countries_iso_code_2'];
  924. return strtoupper($lang_code);
  925. }
  926. /**
  927. * Set the currency code -- use defaults if active currency is not a currency accepted by PayPal
  928. */
  929. function selectCurrency($val = '', $subset = 'EC') {
  930. $ec_currencies = array('CAD', 'EUR', 'GBP', 'JPY', 'USD', 'AUD', 'CHF', 'CZK', 'DKK', 'HKD', 'HUF', 'NOK', 'NZD', 'PLN', 'SEK', 'SGD', 'THB', 'MXN', 'ILS', 'PHP', 'TWD', 'BRL', 'MYR');
  931. $dp_currencies = array('CAD', 'EUR', 'GBP', 'JPY', 'USD', 'AUD');
  932. $paypalSupportedCurrencies = ($subset == 'EC') ? $ec_currencies : $dp_currencies;
  933. // if using Pro 2.0 (UK), only the 6 currencies are supported.
  934. $paypalSupportedCurrencies = (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-UK') ? $dp_currencies : $paypalSupportedCurrencies;
  935. $my_currency = substr(MODULE_PAYMENT_PAYPALWPP_CURRENCY, 5);
  936. if (MODULE_PAYMENT_PAYPALWPP_CURRENCY == 'Selected Currency') {
  937. $my_currency = ($val == '') ? $_SESSION['currency'] : $val;
  938. }
  939. if (!in_array($my_currency, $paypalSupportedCurrencies)) {
  940. $my_currency = (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-UK') ? 'GBP' : 'USD';
  941. }
  942. return $my_currency;
  943. }
  944. /**
  945. * Calculate the amount based on acceptable currencies
  946. */
  947. function calc_order_amount($amount, $paypalCurrency, $applyFormatting = false) {
  948. global $currencies;
  949. $amount = ($amount * $currencies->get_value($paypalCurrency));
  950. if ($paypalCurrency == 'JPY') {
  951. $amount = (int)$amount;
  952. $applyFormatting = FALSE;
  953. }
  954. return ($applyFormatting ? number_format($amount, $currencies->get_decimal_places($paypalCurrency)) : $amount);
  955. }
  956. /**
  957. * Set the state field depending on what PayPal requires for that country.
  958. */
  959. function setStateAndCountry(&$info) {
  960. global $db, $messageStack;
  961. switch ($info['country']['iso_code_2']) {
  962. case 'AU':
  963. case 'US':
  964. case 'CA':
  965. // Paypal only accepts two character state/province codes for some countries.
  966. if (strlen($info['state']) > 2) {
  967. $sql = "SELECT zone_code FROM " . TABLE_ZONES . " WHERE zone_name = :zoneName";
  968. $sql = $db->bindVars($sql, ':zoneName', $info['state'], 'string');
  969. $state = $db->Execute($sql);
  970. if (!$state->EOF) {
  971. $info['state'] = $state->fields['zone_code'];
  972. } else {
  973. $messageStack->add_session('header', MODULE_PAYMENT_PAYPALWPP_TEXT_STATE_ERROR, 'error');
  974. $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_STATE_ERROR);
  975. }
  976. }
  977. break;
  978. case 'AT':
  979. case 'BE':
  980. case 'FR':
  981. case 'DE':
  982. case 'CH':
  983. $info['state'] = '';
  984. break;
  985. case 'GB':
  986. break;
  987. default:
  988. $info['state'] = '';
  989. }
  990. }
  991. /**
  992. * Prepare subtotal and line-item detail content to send to PayPal
  993. */
  994. function getLineItemDetails($restrictedCurrency) {
  995. global $order, $currencies, $order_totals, $order_total_modules;
  996. // if not default currency, do not send subtotals or line-item details
  997. if (DEFAULT_CURRENCY != $order->info['currency'] || $restrictedCurrency != DEFAULT_CURRENCY) {
  998. $this->zcLog('getLineItemDetails 1', 'Not using default currency. Thus, no line-item details can be submitted.');
  999. return array();
  1000. }
  1001. if ($currencies->currencies[$_SESSION['currency']]['value'] != 1 || $currencies->currencies[$order->info['currency']]['value'] != 1) {
  1002. $this->zcLog('getLineItemDetails 2', 'currency val not equal to 1.0000 - cannot proceed without coping with currency conversions. Aborting line-item details.');
  1003. return array();
  1004. }
  1005. $optionsST = array();
  1006. $optionsLI = array();
  1007. $optionsNB = array();
  1008. $numberOfLineItemsProcessed = 0;
  1009. $creditsApplied = 0;
  1010. $surcharges = 0;
  1011. $sumOfLineItems = 0;
  1012. $sumOfLineTax = 0;
  1013. $optionsST['AMT'] = 0;
  1014. $optionsST['ITEMAMT'] = 0;
  1015. $optionsST['TAXAMT'] = 0;
  1016. $optionsST['SHIPPINGAMT'] = 0;
  1017. $optionsST['SHIPDISCAMT'] = 0;
  1018. $optionsST['HANDLINGAMT'] = 0;
  1019. $optionsST['INSURANCEAMT'] = 0;
  1020. $flagSubtotalsUnknownYet = true;
  1021. $subTotalLI = 0;
  1022. $subTotalTax = 0;
  1023. $subTotalShipping = 0;
  1024. $subtotalPRE = array('no data');
  1025. $discountProblemsFlag = FALSE;
  1026. if (sizeof($order_totals)) {
  1027. // prepare subtotals
  1028. for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
  1029. if ($order_totals[$i]['code'] == '') continue;
  1030. if (in_array($order_totals[$i]['code'], array('ot_total','ot_subtotal','ot_tax','ot_shipping')) || strstr($order_totals[$i]['code'], 'insurance')) {
  1031. if ($order_totals[$i]['code'] == 'ot_shipping') $optionsST['SHIPPINGAMT'] = round($order_totals[$i]['value'],2);
  1032. if ($order_totals[$i]['code'] == 'ot_total') $optionsST['AMT'] = round($order_totals[$i]['value'],2);
  1033. if ($order_totals[$i]['code'] == 'ot_tax') $optionsST['TAXAMT'] = round($order_totals[$i]['value'],2);
  1034. if ($order_totals[$i]['code'] == 'ot_subtotal') $optionsST['ITEMAMT'] = round($order_totals[$i]['value'],2);
  1035. if (strstr($order_totals[$i]['code'], 'insurance')) $optionsST['INSURANCEAMT'] += round($order_totals[$i]['value'],2);
  1036. //$optionsST['SHIPDISCAMT'] = ''; // Not applicable
  1037. } else {
  1038. // handle other order totals:
  1039. global $$order_totals[$i]['code'];
  1040. if ((substr($order_totals[$i]['text'], 0, 1) == '-') || (isset($$order_totals[$i]['code']->credit_class) && $$order_totals[$i]['code']->credit_class == true)) {
  1041. // handle credits
  1042. $creditsApplied += round($order_totals[$i]['value'], 2);
  1043. } else {
  1044. // treat all other OT's as if they're related to handling fees or other extra charges to be added/included
  1045. $surcharges += $order_totals[$i]['value'];
  1046. }
  1047. }
  1048. }
  1049. if ($creditsApplied > 0) $optionsST['ITEMAMT'] -= $creditsApplied;
  1050. if ($surcharges > 0) $optionsST['ITEMAMT'] += $surcharges;
  1051. // Handle tax-included scenario
  1052. if (DISPLAY_PRICE_WITH_TAX == 'true') $optionsST['TAXAMT'] = 0;
  1053. $subtotalPRE = $optionsST;
  1054. // Move shipping tax amount from Tax subtotal into Shipping subtotal for submission to PayPal, since PayPal applies tax to each line-item individually
  1055. $module = substr($_SESSION['shipping']['id'], 0, strpos($_SESSION['shipping']['id'], '_'));
  1056. if (zen_not_null($order->info['shipping_method']) && DISPLAY_PRICE_WITH_TAX != 'true') {
  1057. if ($GLOBALS[$module]->tax_class > 0) {
  1058. $shipping_tax_basis = (!isset($GLOBALS[$module]->tax_basis)) ? STORE_SHIPPING_TAX_BASIS : $GLOBALS[$module]->tax_basis;
  1059. $shippingOnBilling = zen_get_tax_rate($GLOBALS[$module]->tax_class, $order->billing['country']['id'], $order->billing['zone_id']);
  1060. $shippingOnDelivery = zen_get_tax_rate($GLOBALS[$module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
  1061. if ($shipping_tax_basis == 'Billing') {
  1062. $shipping_tax = $shippingOnBilling;
  1063. } elseif ($shipping_tax_basis == 'Shipping') {
  1064. $shipping_tax = $shippingOnDelivery;
  1065. } else {
  1066. if (STORE_ZONE == $order->billing['zone_id']) {
  1067. $shipping_tax = $shippingOnBilling;
  1068. } elseif (STORE_ZONE == $order->delivery['zone_id']) {
  1069. $shipping_tax = $shippingOnDelivery;
  1070. } else {
  1071. $shipping_tax = 0;
  1072. }
  1073. }
  1074. $taxAdjustmentForShipping = zen_calculate_tax($order->info['shipping_cost'], $shipping_tax);
  1075. $optionsST['SHIPPINGAMT'] += $taxAdjustmentForShipping;
  1076. $optionsST['TAXAMT'] -= $taxAdjustmentForShipping;
  1077. }
  1078. }
  1079. $flagSubtotalsUnknownYet = (($optionsST['SHIPPINGAMT'] + $optionsST['SHIPDISCAMT'] + $optionsST['AMT'] + $optionsST['TAXAMT'] + $optionsST['ITEMAMT'] + $optionsST['INSURANCEAMT']) == 0);
  1080. } else {
  1081. // if we get here, we don't have any order-total information yet because the customer has clicked Express before starting normal checkout flow
  1082. // thus, we must make a note to manually calculate subtotals, rather than relying on the more robust order-total infrastructure
  1083. $flagSubtotalsUnknownYet = TRUE;
  1084. }
  1085. // loop thru all products to prepare details of quantity and price.
  1086. for ($i=0, $n=sizeof($order->products), $k=0; $i<$n; $i++, $k++) {
  1087. // PayPal won't accept zero-value line-items, so skip this entry if price is zero
  1088. if ($order->products[$i]['final_price'] == 0) continue;
  1089. $optionsLI["L_NUMBER$k"] = $order->products[$i]['model'];
  1090. $optionsLI["L_NAME$k"] = $order->products[$i]['name'];
  1091. // Append *** if out-of-stock.
  1092. $optionsLI["L_NAME$k"] .= ((zen_get_products_stock($order->products[$i]['id']) - $order->products[$i]['qty']) < 0 ? STOCK_MARK_PRODUCT_OUT_OF_STOCK : '');
  1093. // if there are attributes, loop thru them and add to description
  1094. if (isset($order->products[$i]['attributes']) && sizeof($order->products[$i]['attributes']) > 0 ) {
  1095. $optionsLI["L_DESC$k"] = '';
  1096. for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
  1097. $optionsLI["L_DESC$k"] .= "\n " . $order->products[$i]['attributes'][$j]['option'] .
  1098. ': ' . $order->products[$i]['attributes'][$j]['value'];
  1099. } // end loop
  1100. } // endif attribute-info
  1101. // PayPal can't handle partial-quantity values, so fudge it here
  1102. if ($order->products[$i]['qty'] != (int)$order->products[$i]['qty']) {
  1103. $optionsLI["L_NAME$k"] = '('.$order->products[$i]['qty'].' x ) ' . $optionsLI["L_NAME$k"];
  1104. $optionsLI["L_AMT$k"] = ($order->products[$i]['qty'] * $order->products[$i]['final_price']);
  1105. $optionsLI["L_TAXAMT$k"] = zen_calculate_tax($order->products[$i]['qty'] * $order->products[$i]['final_price'], $order->products[$i]['tax']);
  1106. $optionsLI["L_QTY$k"] = 1;
  1107. } else {
  1108. $optionsLI["L_AMT$k"] = $order->products[$i]['final_price'];
  1109. $optionsLI["L_QTY$k"] = $order->products[$i]['qty'];
  1110. $optionsLI["L_TAXAMT$k"] = zen_calculate_tax(1 * $order->products[$i]['final_price'], $order->products[$i]['tax']);
  1111. }
  1112. // For tax-included pricing, combine tax with price instead of treating separately:
  1113. if (DISPLAY_PRICE_WITH_TAX == 'true') {
  1114. $optionsLI["L_AMT$k"] += $optionsLI["L_TAXAMT$k"];
  1115. $optionsLI["L_TAXAMT$k"] = 0;
  1116. }
  1117. $subTotalLI += ($optionsLI["L_QTY$k"] * $optionsLI["L_AMT$k"]);
  1118. $subTotalTax += ($optionsLI["L_QTY$k"] * $optionsLI["L_TAXAMT$k"]);
  1119. // add line-item for one-time charges on this product
  1120. if ($order->products[$i]['onetime_charges'] != 0 ) {
  1121. $k++;
  1122. $optionsLI["L_NAME$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_ONETIME_CHARGES_PREFIX . substr(htmlentities($order->products[$i]['name'], ENT_QUOTES, 'UTF-8'), 0, 120);
  1123. $optionsLI["L_AMT$k"] = $order->products[$i]['onetime_charges'];
  1124. $optionsLI["L_QTY$k"] = 1;
  1125. $optionsLI["L_TAXAMT$k"] = zen_calculate_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']);
  1126. $subTotalLI += $order->products[$i]['onetime_charges'];
  1127. $subTotalTax += $optionsLI["L_TAXAMT$k"];
  1128. }
  1129. $numberOfLineItemsProcessed = $k;
  1130. } // end for loopthru all products
  1131. // add line items for any surcharges added by order-total modules
  1132. if ($surcharges > 0) {
  1133. $numberOfLineItemsProcessed++;
  1134. $k = $numberOfLineItemsProcessed;
  1135. $optionsLI["L_NAME$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_SURCHARGES_SHORT;
  1136. $optionsLI["L_DESC$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_SURCHARGES_LONG;
  1137. $optionsLI["L_AMT$k"] = $surcharges;
  1138. $optionsLI["L_QTY$k"] = 1;
  1139. $subTotalLI += $surcharges;
  1140. }
  1141. // add line items for discounts such as gift certificates and coupons
  1142. if ($creditsApplied > 0) {
  1143. $numberOfLineItemsProcessed++;
  1144. $k = $numberOfLineItemsProcessed;
  1145. $optionsLI["L_NAME$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_DISCOUNTS_SHORT;
  1146. $optionsLI["L_DESC$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_DISCOUNTS_LONG;
  1147. $optionsLI["L_AMT$k"] = (-1 * $creditsApplied);
  1148. $optionsLI["L_QTY$k"] = 1;
  1149. $subTotalLI -= $creditsApplied;
  1150. }
  1151. // Reformat properly
  1152. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1153. // Replace & and = and % with * if found.
  1154. $optionsLI["L_NAME$k"] = str_replace(array('&','=','%'), '*', $optionsLI["L_NAME$k"]);
  1155. if (isset($optionsLI["L_DESC$k"])) $optionsLI["L_DESC$k"] = str_replace(array('&','=','%'), '*', $optionsLI["L_DESC$k"]);
  1156. if (isset($optionsLI["L_NUMBER$k"])) $optionsLI["L_NUMBER$k"] = str_replace(array('&','=','%'), '*', $optionsLI["L_NUMBER$k"]);
  1157. // Remove HTML markup if found
  1158. $optionsLI["L_NAME$k"] = zen_clean_html($optionsLI["L_NAME$k"], 'strong');
  1159. if (isset($optionsLI["L_DESC$k"])) $optionsLI["L_DESC$k"] = zen_clean_html($optionsLI["L_DESC$k"], 'strong');
  1160. // reformat properly according to API specs
  1161. $optionsLI["L_NAME$k"] = substr($optionsLI["L_NAME$k"], 0, 127);
  1162. if (isset($optionsLI["L_NUMBER$k"])) $optionsLI["L_NUMBER$k"] = substr($optionsLI["L_NUMBER$k"], 0, 127);
  1163. if (isset($optionsLI["L_DESC$k"]) && $optionsLI["L_DESC$k"] == '') unset($optionsLI["L_DESC$k"]);
  1164. if (isset($optionsLI["L_DESC$k"])) $optionsLI["L_DESC$k"] = substr($optionsLI["L_DESC$k"], 0, 127);
  1165. if (isset($optionsLI["L_TAXAMT$k"]) && ($optionsLI["L_TAXAMT$k"] != '' || $optionsLI["L_TAXAMT$k"] > 0)) {
  1166. $optionsLI["L_TAXAMT$k"] = round($optionsLI["L_TAXAMT$k"], 2);
  1167. }
  1168. }
  1169. /**
  1170. * PayPal says their math works like this:
  1171. * a) ITEMAMT = L_AMTn * L_QTYn
  1172. * b) TAXAMT = L_QTYn * L_TAXAMTn
  1173. * c) AMT = ITEMAMT + SHIPPINGAMT + HANDLINGAMT + TAXAMT
  1174. */
  1175. // Sanity Check of line-item subtotals
  1176. for ($j=0; $j<$k; $j++) {
  1177. $itemAMT = $optionsLI["L_AMT$j"];
  1178. $itemQTY = $optionsLI["L_QTY$j"];
  1179. $itemTAX = (isset($optionsLI["L_TAXAMT$j"]) ? $optionsLI["L_TAXAMT$j"] : 0);
  1180. $sumOfLineItems += ($itemQTY * $itemAMT);
  1181. $sumOfLineTax += ($itemQTY * $itemTAX);
  1182. }
  1183. $sumOfLineItems = round($sumOfLineItems, 2);
  1184. $sumOfLineTax = round($sumOfLineTax, 2);
  1185. if ($sumOfLineItems == 0) {
  1186. $sumofLineTax = 0;
  1187. $optionsLI = array();
  1188. $discountProblemsFlag = TRUE;
  1189. if ($optionsST['SHIPPINGAMT'] == $optionsST['AMT']) {
  1190. $optionsST['SHIPPINGAMT'] = 0;
  1191. }
  1192. }
  1193. // Sanity check -- if tax-included pricing is causing problems, remove the numbers and put them in a comment instead:
  1194. $stDiffTaxOnly = (strval($sumOfLineItems - $sumOfLineTax - round($optionsST['AMT'], 2)) + 0);
  1195. if (DISPLAY_PRICE_WITH_TAX == 'true' && $stDiffTaxOnly == 0) {
  1196. $optionsNB['DESC'] = 'Tax included in prices: ' . $sumOfLineTax . ' (' . $optionsST['TAXAMT'] . ') ';
  1197. $optionsST['TAXAMT'] = 0;
  1198. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1199. if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1200. }
  1201. }
  1202. // Do sanity check -- if any of the line-item subtotal math doesn't add up properly, skip line-item details,
  1203. // so that the order can go through even though PayPal isn't being flexible to handle Zen Cart's diversity
  1204. if ((strval($subTotalTax) - strval($sumOfLineTax)) > 0.02) {
  1205. $this->zcLog('getLineItemDetails 3', 'Tax Subtotal does not match sum of taxes for line-items. Tax details are being removed from line-item submission data.' . "\n" . $sumOfLineTax . ' ' . $subTotalTax . print_r(array_merge($optionsST, $optionsLI), true));
  1206. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1207. if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1208. }
  1209. $subTotalTax = 0;
  1210. $sumOfLineTax = 0;
  1211. }
  1212. // If coupons exist and there's a calculation problem, then it's likely that taxes are incorrect, so reset L_TAXAMTn values
  1213. if ($creditsApplied > 0 && (strval($optionsST['TAXAMT']) != strval($sumOfLineTax))) {
  1214. $pre = $optionsLI;
  1215. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1216. if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1217. }
  1218. $this->zcLog('getLineItemDetails 4', 'Coupons/Discounts have affected tax calculations, so tax details are being removed from line-item submission data.' . "\n" . $sumOfLineTax . ' ' . $optionsST['TAXAMT'] . "\n" . print_r(array_merge($optionsST, $pre, $optionsNB), true) . "\nAFTER:" . print_r(array_merge($optionsST, $optionsLI, $optionsNB), TRUE));
  1219. $subTotalTax = 0;
  1220. $sumOfLineTax = 0;
  1221. }
  1222. if (TRUE) {
  1223. // disable line-item tax details, leaving only TAXAMT subtotal as tax indicator
  1224. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1225. if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1226. }
  1227. }
  1228. // check subtotals
  1229. if (strval($subTotalLI) - strval($sumOfLineItems) > 0.02) {
  1230. $this->zcLog('getLineItemDetails 5', 'Line-item subtotals do not add up properly. Line-item-details skipped.' . "\n" . (float)$sumOfLineItems . ' ' . (float)$subTotalTax . print_r(array_merge($optionsST, $optionsLI), true));
  1231. $optionsLI = array();
  1232. }
  1233. // check whether discounts are causing a problem
  1234. if (strval($optionsST['ITEMAMT']) < 0) {
  1235. $pre = (array_merge($optionsST, $optionsLI));
  1236. $optionsLI = array();
  1237. $optionsST['ITEMAMT'] = $optionsST['AMT'];
  1238. if ($optionsST['AMT'] < $optionsST['TAXAMT']) $optionsST['TAXAMT'] = 0;
  1239. if ($optionsST['AMT'] < $optionsST['SHIPPINGAMT']) $optionsST['SHIPPINGAMT'] = 0;
  1240. $discountProblemsFlag = TRUE;
  1241. $this->zcLog('getLineItemDetails 6', 'Discounts have caused the subtotal to calculate incorrectly. Line-item-details cannot be submitted.' . "\nBefore:" . print_r($pre, TRUE) . "\nAfter:" . print_r(array_merge($optionsST, $optionsLI), true));
  1242. }
  1243. // if AMT or ITEMAMT values are 0 (ie: certain OT modules disabled) or we've started express checkout without going through normal checkout flow, we have to get subtotals manually
  1244. if ((!isset($optionsST['AMT']) || $optionsST['AMT'] == 0 || $flagSubtotalsUnknownYet == TRUE || $optionsST['ITEMAMT'] == 0) && $discountProblemsFlag != TRUE) {
  1245. $optionsST['ITEMAMT'] = $sumOfLineItems;
  1246. $optionsST['TAXAMT'] = $sumOfLineTax;
  1247. if ($subTotalShipping > 0) $optionsST['SHIPPINGAMT'] = $subTotalShipping;
  1248. $optionsST['AMT'] = $sumOfLineItems + $optionsST['TAXAMT'] + $optionsST['SHIPPINGAMT'];
  1249. }
  1250. $this->zcLog('getLineItemDetails 7 - subtotal comparisons', 'BEFORE line-item calcs: ' . print_r($subtotalPRE, true) . ($flagSubtotalsUnknownYet == TRUE ? 'Subtotals Unknown Yet' : '') . ' - AFTER doing line-item calcs: ' . print_r(array_merge($optionsST, $optionsLI, $optionsNB), true));
  1251. // if subtotals are not adding up correctly, then skip sending any line-item or subtotal details to PayPal
  1252. $stAll = round(strval($optionsST['ITEMAMT'] + $optionsST['TAXAMT'] + $optionsST['SHIPPINGAMT'] + $optionsST['SHIPDISCAMT'] + $optionsST['HANDLINGAMT'] + $optionsST['INSURANCEAMT']), 2);
  1253. $stDiff = strval($optionsST['AMT'] - $stAll);
  1254. $stDiffRounded = (strval($stAll - round($optionsST['AMT'], 2)) + 0);
  1255. // unset any subtotal values that are zero
  1256. if (isset($optionsST['ITEMAMT']) && $optionsST['ITEMAMT'] == 0) unset($optionsST['ITEMAMT']);
  1257. if (isset($optionsST['TAXAMT']) && $optionsST['TAXAMT'] == 0) unset($optionsST['TAXAMT']);
  1258. if (isset($optionsST['SHIPPINGAMT']) && $optionsST['SHIPPINGAMT'] == 0) unset($optionsST['SHIPPINGAMT']);
  1259. if (isset($optionsST['SHIPDISCAMT']) && $optionsST['SHIPDISCAMT'] == 0) unset($optionsST['SHIPDISCAMT']);
  1260. if (isset($optionsST['HANDLINGAMT']) && $optionsST['HANDLINGAMT'] == 0) unset($optionsST['HANDLINGAMT']);
  1261. if (isset($optionsST['INSURANCEAMT']) && $optionsST['INSURANCEAMT'] == 0) unset($optionsST['INSURANCEAMT']);
  1262. // tidy up all values so that they comply with proper format (number_format(xxxx,2) for PayPal US use )
  1263. if (!defined('PAYPALWPP_SKIP_LINE_ITEM_DETAIL_FORMATTING') || PAYPALWPP_SKIP_LINE_ITEM_DETAIL_FORMATTING != 'true' || in_array($order->info['currency'], array('JPY', 'NOK'))) {
  1264. if (is_array($optionsST)) foreach ($optionsST as $key=>$value) {
  1265. $optionsST[$key] = number_format($value, ($order->info['currency'] == 'JPY' ? 0 : 2));
  1266. }
  1267. if (is_array($optionsLI)) foreach ($optionsLI as $key=>$value) {
  1268. if (substr($key, 0, 8) == 'L_TAXAMT' && ($optionsLI[$key] == '' || $optionsLI[$key] == 0)) {
  1269. unset($optionsLI[$key]);
  1270. } else {
  1271. if (strstr($key, 'AMT')) $optionsLI[$key] = number_format($value, ($order->info['currency'] == 'JPY' ? 0 : 2));
  1272. }
  1273. }
  1274. }
  1275. $this->zcLog('getLineItemDetails 8', 'checking subtotals... ' . "\n" . print_r(array_merge(array('calculated total'=>number_format($stAll, ($order->info['currency'] == 'JPY' ? 0 : 2))), $optionsST), true) . "\n-------------------\ndifference: " . ($stDiff + 0) . ' (abs+rounded: ' . ($stDiffRounded + 0) . ')');
  1276. if ( $stDiffRounded != 0) {
  1277. $this->zcLog('getLineItemDetails 9', 'Subtotals Bad. Skipping line-item/subtotal details');
  1278. return array();
  1279. }
  1280. $this->zcLog('getLineItemDetails 10', 'subtotals balance - okay');
  1281. // Send Subtotal and LineItem results back to be submitted to PayPal
  1282. return array_merge($optionsST, $optionsLI, $optionsNB);
  1283. }
  1284. /**
  1285. * This method sends the customer to PayPal's site
  1286. * There, they will log in to their PayPal account, choose a funding source and shipping method
  1287. * and then return to our store site with an EC token
  1288. */
  1289. function ec_step1() {
  1290. global $order, $order_totals, $db, $doPayPal;
  1291. // if cart is empty due to timeout on login or shopping cart page, go to timeout screen
  1292. if ($_SESSION['cart']->count_contents() == 0) {
  1293. $message = 'Logging out due to empty shopping cart. Is session started properly? ... ' . "\nSESSION Details:\n" . print_r($_SESSION, TRUE) . 'GET:' . "\n" . print_r($_GET, TRUE);
  1294. include_once(DIR_WS_MODULES . 'payment/paypal/paypal_functions.php');
  1295. ipn_debug_email($message);
  1296. zen_redirect(zen_href_link(FILENAME_TIME_OUT, '', 'SSL'));
  1297. }
  1298. // init new order object
  1299. require(DIR_WS_CLASSES . 'order.php');
  1300. $order = new order;
  1301. // load the selected shipping module so that shipping taxes can be assessed
  1302. require(DIR_WS_CLASSES . 'shipping.php');
  1303. $shipping_modules = new shipping($_SESSION['shipping']);
  1304. // load OT modules so that discounts and taxes can be assessed
  1305. require(DIR_WS_CLASSES . 'order_total.php');
  1306. $order_total_modules = new order_total;
  1307. $order_totals = $order_total_modules->pre_confirmation_check();
  1308. $order_totals = $order_total_modules->process();
  1309. $doPayPal = $this->paypal_init();
  1310. $options = array();
  1311. $options = $this->getLineItemDetails($this->selectCurrency());
  1312. // Determine the language to use when visiting the PP site
  1313. $lc_code = $this->getLanguageCode();
  1314. if ($lc_code != '') $options['LOCALECODE'] = $lc_code;
  1315. // Set currency and amount
  1316. $options['CURRENCY'] = $this->selectCurrency();
  1317. $order_amount = $this->calc_order_amount($order->info['total'], $options['CURRENCY']);
  1318. // Payment Transaction/Authorization Mode
  1319. $options['PAYMENTACTION'] = (MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Sale';
  1320. // for future:
  1321. if (MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE == 'Order') $options['PAYMENTACTION'] = 'Order';
  1322. $options['ALLOWNOTE'] = 1; // allow customer to enter a note on the PayPal site, which will be copied to order comments upon return to store.
  1323. $options['SOLUTIONTYPE'] = 'Sole'; // Use 'Mark' for normal Express Checkout, 'Sole' for auctions or alternate flow
  1324. $options['LANDINGPAGE'] = 'Billing'; // "Billing" or "Login" selects the style of landing page on PayPal site during checkout
  1325. // Set the return URL if they click "Submit" on PayPal site
  1326. $return_url = str_replace('&amp;', '&', zen_href_link('ipn_main_handler.php', 'type=ec', 'SSL', true, true, true));
  1327. // Select the return URL if they click "cancel" on PayPal site or click to return without making payment or login
  1328. $cancel_url = str_replace('&amp;', '&', zen_href_link(($_SESSION['customer_first_name'] != '' && $_SESSION['customer_id'] != '' ? FILENAME_CHECKOUT_SHIPPING :FILENAME_LOGIN), 'ec_cancel=1', 'SSL'));
  1329. // debug
  1330. $val = $_SESSION; unset($val['navigation']);
  1331. $this->zcLog('ec_step1 - 1', 'Checking to see if we are in markflow' . "\n" . 'cart contents: ' . $_SESSION['cart']->get_content_type() . "\n\nNOTE: " . '$this->showPaymentPage = ' . (int)$this->showPaymentPage . "\nCustomer ID: " . (int)$_SESSION['customer_id'] . "\nSession Data: " . print_r($val, true));
  1332. /**
  1333. * Check whether shipping is required on this order or not.
  1334. * If not, tell PayPal to skip all shipping options
  1335. * ie: don't ask for any shipping info if cart content is strictly virtual and customer is already logged-in
  1336. * (if not logged in, we need address information only to build the customer record)
  1337. */
  1338. if ($_SESSION['cart']->get_content_type() == 'virtual' && isset($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0) {
  1339. $this->zcLog('ec-step1-addr_check', "cart contents is virtual and customer is logged in ... therefore options['NOSHIPPING']=1");
  1340. $options['NOSHIPPING'] = 1;
  1341. } else {
  1342. $this->zcLog('ec-step1-addr_check', "cart content is not all virtual (or customer is not logged in) ... therefore will be submitting address details");
  1343. // If we are in a "mark" flow and the customer has a usable address, set the addressoverride variable to 1. This will
  1344. // override the shipping address in PayPal with the shipping address that is selected in Zen Cart.
  1345. // @TODO: consider using address-validation against Paypal's addresses
  1346. if (($address_arr = $this->getOverrideAddress()) !== false) {
  1347. $address_error = false;
  1348. foreach(array('entry_firstname','entry_lastname','entry_street_address','entry_city','entry_postcode','zone_code','countries_iso_code_2') as $val) {
  1349. if ($address_arr[$val] == '') $address_error = true;
  1350. if ($address_error == true) $this->zcLog('ec-step1-addr_check2', '$address_error = true because ' .$val . ' is blank.');
  1351. }
  1352. if ($address_error == false) {
  1353. // set the override var
  1354. $options['ADDROVERRIDE'] = 1;
  1355. // set the address info
  1356. $options['SHIPTONAME'] = $address_arr['entry_firstname'] . ' ' . $address_arr['entry_lastname'];
  1357. $options['SHIPTOSTREET'] = $address_arr['entry_street_address'];
  1358. if ($address_arr['entry_suburb'] != '') $options['SHIPTOSTREET2'] = $address_arr['entry_suburb'];
  1359. $options['SHIPTOCITY'] = $address_arr['entry_city'];
  1360. $options['SHIPTOZIP'] = $address_arr['entry_postcode'];
  1361. $options['SHIPTOSTATE'] = $address_arr['zone_code'];
  1362. $options['SHIPTOCOUNTRYCODE'] = $address_arr['countries_iso_code_2'];
  1363. }
  1364. }
  1365. $this->zcLog('ec-step1-addr_check3', 'address details from override check:'.($address_arr == FALSE ? ' <NONE FOUND>' : print_r($address_arr, true)));
  1366. // Do we require a "confirmed" shipping address ?
  1367. if (MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS == 'Yes') {
  1368. $options['REQCONFIRMSHIPPING'] = 1;
  1369. }
  1370. }
  1371. // if we know customer's email address, supply it, so as to pre-fill the signup box at PayPal (useful for new PayPal accounts only)
  1372. if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id'])) {
  1373. $sql = "select * from " . TABLE_CUSTOMERS . " where customers_id = :custID ";
  1374. $sql = $db->bindVars($sql, ':custID', $_SESSION['customer_id'], 'integer');
  1375. $zc_getemail = $db->Execute($sql);
  1376. if ($zc_getemail->RecordCount() > 0 && $zc_getemail->fields['customers_email_address'] != '') {
  1377. $options['EMAIL'] = $zc_getemail->fields['customers_email_address'];
  1378. }
  1379. if ($zc_getemail->RecordCount() > 0 && $zc_getemail->fields['customers_telephone'] != '') {
  1380. $options['PHONENUM'] = $zc_getemail->fields['customers_telephone'];
  1381. }
  1382. }
  1383. if (!isset($options['AMT'])) $options['AMT'] = number_format($order_amount, 2);
  1384. $this->zcLog('ec_step1 - 2 -submit', print_r(array_merge($options, array('RETURNURL' => $return_url, 'CANCELURL' => $cancel_url)), true));
  1385. /**
  1386. * Ask PayPal for the token with which to initiate communications
  1387. */
  1388. $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
  1389. $submissionCheckOne = TRUE;
  1390. $submissionCheckTwo = TRUE;
  1391. if ($submissionCheckOne) {
  1392. // If there's an error on line-item details, remove tax values and resubmit, since the most common cause of 10413 is tax mismatches
  1393. if ($response['L_ERRORCODE0'] == '10413') {
  1394. $this->zcLog('ec_step1 - 3 - removing tax portion', 'Tax Subtotal does not match sum of taxes for line-items. Tax details removed from line-item submission data.' . "\n" . print_r($options, true));
  1395. //echo '1st submission REJECTED. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true) . urldecode(print_r($response, true));
  1396. $tsubtotal = 0;
  1397. foreach ($options as $key=>$value) {
  1398. if (substr($key, 0, 8) == 'L_TAXAMT') {
  1399. $tsubtotal += preg_replace('/[^0-9.\-]/', '', $value);
  1400. unset($options[$key]);
  1401. }
  1402. }
  1403. $options['TAXAMT'] = $tsubtotal;
  1404. $amt = preg_replace('/[^0-9.%]/', '', $options['AMT']);
  1405. // echo 'oldAMT:'.$amt;
  1406. // echo ' newTAXAMT:'.$tsubtotal;
  1407. $taxamt = preg_replace('/[^0-9.%]/', '', $options['TAXAMT']);
  1408. $shipamt = preg_replace('/[^0-9.%]/', '', $options['SHIPPINGAMT']);
  1409. $itemamt = preg_replace('/[^0-9.%]/', '', $options['ITEMAMT']);
  1410. $calculatedAmount = $itemamt + $taxamt + $shipamt;
  1411. if ($amt != $calculatedAmount) $amt = $calculatedAmount;
  1412. // echo ' newAMT:'.$amt;
  1413. $options['AMT'] = $amt;
  1414. $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
  1415. //echo '<br>2nd submission. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true);
  1416. }
  1417. if ($submissionCheckTwo) {
  1418. if ($response['L_ERRORCODE0'] == '10413') {
  1419. $this->zcLog('ec_step1 - 4 - removing line-item details', 'PayPal designed their own mathematics rules. Dumbing it down for them.' . "\n" . print_r($options, true));
  1420. //echo '2nd submission REJECTED. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true) . urldecode(print_r($response, true));
  1421. foreach ($options as $key=>$value) {
  1422. if (substr($key, 0, 2) == 'L_') {
  1423. unset($options[$key]);
  1424. }
  1425. }
  1426. $amt = preg_replace('/[^0-9.%]/', '', $options['AMT']);
  1427. $taxamt = preg_replace('/[^0-9.%]/', '', $options['TAXAMT']);
  1428. $shipamt = preg_replace('/[^0-9.%]/', '', $options['SHIPPINGAMT']);
  1429. $itemamt = preg_replace('/[^0-9.%]/', '', $options['ITEMAMT']);
  1430. $calculatedAmount = $itemamt + $taxamt + $shipamt;
  1431. if ($amt != $calculatedAmount) $amt = $calculatedAmount;
  1432. $options['AMT'] = $amt;
  1433. $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
  1434. //echo '<br>3rd submission. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true);
  1435. }
  1436. }
  1437. }
  1438. /**
  1439. * Determine result of request for token -- if error occurred, the errorHandler will redirect accordingly
  1440. */
  1441. $error = $this->_errorHandler($response, 'SetExpressCheckout');
  1442. // Success, so read the EC token
  1443. $_SESSION['paypal_ec_token'] = preg_replace('/[^0-9.A-Z\-]/', '', urldecode($response['TOKEN']));
  1444. // prepare to redirect to PayPal so the customer can log in and make their selections
  1445. $paypal_url = $this->getPayPalLoginServer();
  1446. // Set the name of the displayed "continue" button on the PayPal site.
  1447. // 'commit' = "Pay Now" || 'continue' = "Review Payment"
  1448. $orderReview = true;
  1449. if ($_SESSION['paypal_ec_markflow'] == 1) $orderReview = false;
  1450. $userActionKey = "&useraction=" . ((int)$orderReview == false ? 'commit' : 'continue');
  1451. // This is where we actually redirect the customer's browser to PayPal. Upon return from PayPal, they go to ec_step2
  1452. header("HTTP/1.1 302 Object Moved");
  1453. zen_redirect($paypal_url . "?cmd=_express-checkout&token=" . $_SESSION['paypal_ec_token'] . $userActionKey);
  1454. // this should never be reached:
  1455. return $error;
  1456. }
  1457. /**
  1458. * This method is for step 2 of the express checkout option. This
  1459. * retrieves from PayPal the data set by step one and sets the Zen Cart
  1460. * data accordingly depending on admin settings.
  1461. */
  1462. function ec_step2() {
  1463. // Visitor just came back from PayPal and so we collect all
  1464. // the info returned, create an account if necessary, then log
  1465. // them in, and then send them to the appropriate page.
  1466. if (empty($_SESSION['paypal_ec_token'])) {
  1467. // see if the token is set -- if not, we cannot continue -- ideally the token should match the session token
  1468. if (isset($_GET['token'])) {
  1469. // we have a token, so we will proceed
  1470. $_SESSION['paypal_ec_token'] = $_GET['token'];
  1471. // sanitize this
  1472. $_SESSION['paypal_ec_token'] = preg_replace('/[^0-9.A-Z\-]/', '', $_GET['token']);
  1473. } else {
  1474. // no token -- not ready for this step -- send them back to checkout page with error
  1475. $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_INVALID_RESPONSE, true);
  1476. }
  1477. }
  1478. // debug
  1479. //$this->zcLog('PayPal test Log - ec_step2 $_REQUEST data', "In function: ec_step2()\r\nData in \$_REQUEST = \r\n" . print_r($_REQUEST, true));
  1480. // Initialize the paypal caller object.
  1481. global $doPayPal;
  1482. $doPayPal = $this->paypal_init();
  1483. // with the token we retrieve the data about this user
  1484. $response = $doPayPal->GetExpressCheckoutDetails($_SESSION['paypal_ec_token']);
  1485. //$this->zcLog('ec_step2 - GetExpressCheckout response', print_r($response, true));
  1486. /**
  1487. * Determine result of request for data -- if error occurred, the errorHandler will redirect accordingly
  1488. */
  1489. $error = $this->_errorHandler($response, 'GetExpressCheckoutDetails');
  1490. // Alert customer that they've selected an unconfirmed address at PayPal, and must go back and choose a Confirmed one
  1491. if (MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS == 'Yes' && strtoupper($response['ADDRESSSTATUS']) != 'CONFIRMED') {
  1492. $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_CONFIRMEDADDR_ERROR, true, FILENAME_CHECKOUT_SHIPPING);
  1493. }
  1494. // will we be creating an account for this customer? We must if the cart contents are virtual, so can login to download etc.
  1495. if ($_SESSION['cart']->get_content_type('true') > 0 || in_array($_SESSION['cart']->content_type, array('mixed', 'virtual'))) $this->new_acct_notify = 'Yes';
  1496. // get the payer_id from the customer's info as returned from PayPal
  1497. $_SESSION['paypal_ec_payer_id'] = $response['PAYERID'];
  1498. $this->notify('NOTIFY_PAYPAL_EXPRESS_CHECKOUT_PAYERID_DETERMINED', $response['PAYERID']);
  1499. $gender = '';
  1500. if (urldecode($response['SALUTATION'] == 'Mr')) $gender = 'm';
  1501. if (in_array(urldecode($response['SALUTATION']), array('Ms', 'Mrs'))) $gender = 'f';
  1502. // prepare the information to pass to the ec_step2_finish() function, which does the account creation, address build, etc
  1503. $step2_payerinfo = array('payer_id' => $response['PAYERID'],
  1504. 'payer_email' => urldecode($response['EMAIL']),
  1505. 'payer_salutation'=> urldecode($response['SALUTATION']),
  1506. 'payer_gender' => $gender,
  1507. 'payer_firstname' => urldecode($response['FIRSTNAME']),
  1508. 'payer_lastname' => urldecode($response['LASTNAME']),
  1509. 'payer_business' => urldecode($response['BUSINESS']),
  1510. 'payer_status' => $response['PAYERSTATUS'],
  1511. 'ship_country_code' => urldecode($response['COUNTRYCODE']),
  1512. 'ship_address_status' => urldecode($response['ADDRESSSTATUS']),
  1513. 'ship_phone' => urldecode($response['PHONENUM']),
  1514. 'order_comment' => urldecode($response['NOTE']),
  1515. );
  1516. if (strtoupper($response['ADDRESSSTATUS']) == 'NONE') {
  1517. $step2_shipto = array();
  1518. } else {
  1519. // accomodate PayPal bug which repeats 1st line of address for 2nd line if 2nd line is empty.
  1520. if ($response['SHIPTOSTREET2'] == $response['SHIPTOSTREET1']) $response['SHIPTOSTREET2'] = '';
  1521. // accomodate PayPal bug which incorrectly treats 'Yukon Territory' as YK instead of ISO standard of YT.
  1522. if ($response['SHIPTOSTATE'] == 'YK') $response['SHIPTOSTATE'] = 'YT';
  1523. // same with Newfoundland
  1524. if ($response['SHIPTOSTATE'] == 'NF') $response['SHIPTOSTATE'] = 'NL';
  1525. // process address details supplied
  1526. $step2_shipto = array('ship_name' => urldecode($response['SHIPTONAME']),
  1527. 'ship_street_1' => urldecode($response['SHIPTOSTREET']),
  1528. 'ship_street_2' => urldecode($response['SHIPTOSTREET2']),
  1529. 'ship_city' => urldecode($response['SHIPTOCITY']),
  1530. 'ship_state' => (isset($response['SHIPTOSTATE']) && $response['SHIPTOSTATE'] !='' ? urldecode($response['SHIPTOSTATE']) : urldecode($response['SHIPTOCITY'])),
  1531. 'ship_postal_code' => urldecode($response['SHIPTOZIP']),
  1532. 'ship_country_code' => urldecode($response['SHIPTOCOUNTRYCODE']),
  1533. 'ship_country_name' => (isset($response['SHIPTOCOUNTRY']) ? urldecode($response['SHIPTOCOUNTRY']) : urldecode($response['SHIPTOCOUNTRYNAME'])));
  1534. }
  1535. // reset all previously-selected shipping choices, because cart contents may have been changed
  1536. if (!(isset($_SESSION['paypal_ec_markflow']) && $_SESSION['paypal_ec_markflow'] == 1)) unset($_SESSION['shipping']);
  1537. // set total temporarily based on amount returned from PayPal, so validations continue to work properly
  1538. global $order;
  1539. $order->info['total'] = $response['AMT'];
  1540. //$this->zcLog('ec_step2 - processed info', print_r(array_merge($step2_payerinfo, $step2_shipto), true));
  1541. // send data off to build account, log in, set addresses, place order
  1542. $this->ec_step2_finish(array_merge($step2_payerinfo, $step2_shipto), $this->new_acct_notify);
  1543. }
  1544. /**
  1545. * Complete the step2 phase by creating accounts if needed, linking data, placing order, etc.
  1546. */
  1547. function ec_step2_finish($paypal_ec_payer_info, $new_acct_notify) {
  1548. global $db, $order;
  1549. // register the payer_info in the session
  1550. $_SESSION['paypal_ec_payer_info'] = $paypal_ec_payer_info;
  1551. // debug
  1552. $this->zcLog('ec_step2_finish - 1', 'START: paypal_ec_payer_info= ' . print_r($_SESSION['paypal_ec_payer_info'], true));
  1553. /**
  1554. * Building customer zone/address from returned data
  1555. */
  1556. // set some defaults, which will be updated later:
  1557. $country_id = '223';
  1558. $address_format_id = 2;
  1559. $state_id = 0;
  1560. $acct_exists = false;
  1561. // store default address id for later use/reference
  1562. $original_default_address_id = $_SESSION['customer_default_address_id'];
  1563. // Get the customer's country ID based on name or ISO code
  1564. $sql = "SELECT countries_id, address_format_id, countries_iso_code_2, countries_iso_code_3
  1565. FROM " . TABLE_COUNTRIES . "
  1566. WHERE countries_iso_code_2 = :countryId
  1567. OR countries_name = :countryId
  1568. LIMIT 1";
  1569. $sql1 = $db->bindVars($sql, ':countryId', $paypal_ec_payer_info['ship_country_name'], 'string');
  1570. $country1 = $db->Execute($sql1);
  1571. $sql2 = $db->bindVars($sql, ':countryId', $paypal_ec_payer_info['ship_country_code'], 'string');
  1572. $country2 = $db->Execute($sql2);
  1573. // see if we found a record, if yes, then use it instead of default American format
  1574. if ($country1->RecordCount() > 0) {
  1575. $country_id = $country1->fields['countries_id'];
  1576. if (!isset($paypal_ec_payer_info['ship_country_code']) || $paypal_ec_payer_info['ship_country_code'] == '') $paypal_ec_payer_info['ship_country_code'] = $country1->fields['countries_iso_code_2'];
  1577. $country_code3 = $country1->fields['countries_iso_code_3'];
  1578. $address_format_id = (int)$country1->fields['address_format_id'];
  1579. } elseif ($country2->RecordCount() > 0) {
  1580. // if didn't find it based on name, check using ISO code (ie: in case of no-shipping-address required/supplied)
  1581. $country_id = $country2->fields['countries_id'];
  1582. $country_code3 = $country2->fields['countries_iso_code_3'];
  1583. $address_format_id = (int)$country2->fields['address_format_id'];
  1584. }
  1585. // Need to determine zone, based on zone name first, and then zone code if name fails check. Otherwise uses 0.
  1586. $sql = "SELECT zone_id
  1587. FROM " . TABLE_ZONES . "
  1588. WHERE zone_country_id = :zCountry
  1589. AND zone_code = :zoneCode
  1590. OR zone_name = :zoneCode
  1591. LIMIT 1";
  1592. $sql = $db->bindVars($sql, ':zCountry', $country_id, 'integer');
  1593. $sql = $db->bindVars($sql, ':zoneCode', $paypal_ec_payer_info['ship_state'], 'string');
  1594. $states = $db->Execute($sql);
  1595. if ($states->RecordCount() > 0) {
  1596. $state_id = $states->fields['zone_id'];
  1597. }
  1598. /**
  1599. * Using the supplied data from PayPal, set the data into the order record
  1600. */
  1601. // customer
  1602. $order->customer['name'] = $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname'];
  1603. $order->customer['company'] = $paypal_ec_payer_info['payer_business'];
  1604. $order->customer['street_address'] = $paypal_ec_payer_info['ship_street_1'];
  1605. $order->customer['suburb'] = $paypal_ec_payer_info['ship_street_2'];
  1606. $order->customer['city'] = $paypal_ec_payer_info['ship_city'];
  1607. $order->customer['postcode'] = $paypal_ec_payer_info['ship_postal_code'];
  1608. $order->customer['state'] = $paypal_ec_payer_info['ship_state'];
  1609. $order->customer['country'] = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
  1610. $order->customer['country']['id'] = $country_id;
  1611. $order->customer['country']['iso_code_2'] = $paypal_ec_payer_info['ship_country_code'];
  1612. $order->customer['format_id'] = $address_format_id;
  1613. $order->customer['email_address'] = $paypal_ec_payer_info['payer_email'];
  1614. $order->customer['telephone'] = $paypal_ec_payer_info['ship_phone'];
  1615. $order->customer['zone_id'] = $state_id;
  1616. // billing
  1617. $order->billing['name'] = $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname'];
  1618. $order->billing['company'] = $paypal_ec_payer_info['payer_business'];
  1619. $order->billing['street_address'] = $paypal_ec_payer_info['ship_street_1'];
  1620. $order->billing['suburb'] = $paypal_ec_payer_info['ship_street_2'];
  1621. $order->billing['city'] = $paypal_ec_payer_info['ship_city'];
  1622. $order->billing['postcode'] = $paypal_ec_payer_info['ship_postal_code'];
  1623. $order->billing['state'] = $paypal_ec_payer_info['ship_state'];
  1624. $order->billing['country'] = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
  1625. $order->billing['country']['id'] = $country_id;
  1626. $order->billing['country']['iso_code_2'] = $paypal_ec_payer_info['ship_country_code'];
  1627. $order->billing['format_id'] = $address_format_id;
  1628. $order->billing['zone_id'] = $state_id;
  1629. // delivery
  1630. if (strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE') {
  1631. $order->delivery['name'] = $paypal_ec_payer_info['ship_name'];
  1632. $order->delivery['company'] = trim($paypal_ec_payer_info['ship_name'] . ' ' . $paypal_ec_payer_info['payer_business']);
  1633. $order->delivery['street_address']= $paypal_ec_payer_info['ship_street_1'];
  1634. $order->delivery['suburb'] = $paypal_ec_payer_info['ship_street_2'];
  1635. $order->delivery['city'] = $paypal_ec_payer_info['ship_city'];
  1636. $order->delivery['postcode'] = $paypal_ec_payer_info['ship_postal_code'];
  1637. $order->delivery['state'] = $paypal_ec_payer_info['ship_state'];
  1638. $order->delivery['country'] = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
  1639. $order->delivery['country_id'] = $country_id;
  1640. $order->delivery['format_id'] = $address_format_id;
  1641. $order->delivery['zone_id'] = $state_id;
  1642. }
  1643. // process submitted customer notes
  1644. if (isset($paypal_ec_payer_info['order_comment']) && $paypal_ec_payer_info['order_comment'] != '') {
  1645. $_SESSION['comments'] = (isset($_SESSION['comments']) ? $_SESSION['comments'] : '') . $paypal_ec_payer_info['order_comment'];
  1646. $order->info['comments'] = $_SESSION['comments'];
  1647. }
  1648. // debug
  1649. $this->zcLog('ec_step2_finish - 2', 'country_id = ' . $country_id . ' ' . $paypal_ec_payer_info['ship_country_name'] . ' ' . $paypal_ec_payer_info['ship_country_code'] ."\naddress_format_id = " . $address_format_id . "\nstate_id = " . $state_id . ' (original state tested: ' . $paypal_ec_payer_info['ship_state'] . ')' . "\ncountry1->fields['countries_id'] = " . $country1->fields['countries_id'] . "\ncountry2->fields['countries_id'] = " . $country2->fields['countries_id'] . "\n" . '$order->customer = ' . print_r($order->customer, true));
  1650. // check to see whether PayPal should still be offered to this customer, based on the zone of their address:
  1651. $this->update_status();
  1652. if (!$this->enabled) {
  1653. $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
  1654. }
  1655. // see if the user is logged in
  1656. if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0) {
  1657. // They're logged in, so forward them straight to checkout stages, depending on address needs etc
  1658. $order->customer['id'] = $_SESSION['customer_id'];
  1659. // set the session value for express checkout temp
  1660. $_SESSION['paypal_ec_temp'] = false;
  1661. // if no address required for shipping, leave shipping portion alone
  1662. if (strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE' && $_SESSION['paypal_ec_payer_info']['ship_street_1'] != '') {
  1663. // set the session info for the sendto
  1664. $_SESSION['sendto'] = $_SESSION['customer_default_address_id'];
  1665. // This is the address matching section
  1666. // try to match it first
  1667. // note: this is by no means 100%
  1668. $address_book_id = $this->findMatchingAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing));
  1669. // no match, so add the record
  1670. if (!$address_book_id) {
  1671. $address_book_id = $this->addAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing), false);
  1672. }
  1673. // set the address for use
  1674. $_SESSION['sendto'] = $address_book_id;
  1675. }
  1676. // set the users billto information (default address)
  1677. if (!isset($_SESSION['billto'])) {
  1678. $_SESSION['billto'] = $_SESSION['customer_default_address_id'];
  1679. }
  1680. // debug
  1681. $this->zcLog('ec_step2_finish - 3', 'Exiting ec_step2_finish logged-in mode.' . "\n" . 'Selected address: ' . $address_book_id . "\nOriginal was: " . $original_default_address_id);
  1682. // select a shipping method, based on cheapest available option
  1683. if (MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING == 'Yes') $this->setShippingMethod();
  1684. // send the user on
  1685. if ($_SESSION['paypal_ec_markflow'] == 1) {
  1686. $this->terminateEC('', false, FILENAME_CHECKOUT_PROCESS);
  1687. } else {
  1688. $this->terminateEC('', false, FILENAME_CHECKOUT_CONFIRMATION);
  1689. }
  1690. } else {
  1691. // They're not logged in. Create an account if necessary, and then log them in.
  1692. // First, see if they're an existing customer, and log them in automatically
  1693. // If Paypal didn't supply us an email address, something went wrong
  1694. if (trim($paypal_ec_payer_info['payer_email']) == '') $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_INVALID_RESPONSE, true);
  1695. // attempt to obtain the user information using the payer_email from the info returned from PayPal, via email address
  1696. $sql = "SELECT customers_id, customers_firstname, customers_lastname, customers_paypal_payerid, customers_paypal_ec
  1697. FROM " . TABLE_CUSTOMERS . "
  1698. WHERE customers_email_address = :emailAddress ";
  1699. $sql = $db->bindVars($sql, ':emailAddress', $paypal_ec_payer_info['payer_email'], 'string');
  1700. $check_customer = $db->Execute($sql);
  1701. // debug
  1702. $this->zcLog('ec_step2_finish - 4', 'Not logged in. Looking for account.' . "\n" . (int)$check_customer->RecordCount() . ' matching customer records found.');
  1703. if (!$check_customer->EOF) {
  1704. $acct_exists = true;
  1705. // see if this was only a temp account -- if so, remove it
  1706. if ($check_customer->fields['customers_paypal_ec'] == '1') {
  1707. // Delete the existing temporary account
  1708. $this->ec_delete_user($check_customer->fields['customers_id']);
  1709. $acct_exists = false;
  1710. // debug
  1711. $this->zcLog('ec_step2_finish - 5', 'Found temporary account - deleting it.');
  1712. }
  1713. }
  1714. // Create an account, if the account does not exist
  1715. if (!$acct_exists) {
  1716. // debug
  1717. $this->zcLog('ec_step2_finish - 6', 'No ZC account found for this customer. Creating new account.' . "\n" . '$this->new_acct_notify =' . $this->new_acct_notify);
  1718. // Generate a random 8-char password
  1719. $password = zen_create_random_value(8);
  1720. $sql_data_array = array();
  1721. // set the customer information in the array for the table insertion
  1722. $sql_data_array = array(
  1723. 'customers_firstname' => $paypal_ec_payer_info['payer_firstname'],
  1724. 'customers_lastname' => $paypal_ec_payer_info['payer_lastname'],
  1725. 'customers_email_address' => $paypal_ec_payer_info['payer_email'],
  1726. 'customers_email_format' => (ACCOUNT_EMAIL_PREFERENCE == '1' ? 'HTML' : 'TEXT'),
  1727. 'customers_telephone' => $paypal_ec_payer_info['ship_phone'],
  1728. 'customers_fax' => '',
  1729. 'customers_gender' => $paypal_ec_payer_info['payer_gender'],
  1730. 'customers_newsletter' => '0',
  1731. 'customers_password' => zen_encrypt_password($password),
  1732. 'customers_paypal_payerid' => $_SESSION['paypal_ec_payer_id']);
  1733. // insert the data
  1734. $result = zen_db_perform(TABLE_CUSTOMERS, $sql_data_array);
  1735. // grab the customer_id (last insert id)
  1736. $customer_id = $db->Insert_ID();
  1737. // set the Guest customer ID -- for PWA purposes
  1738. $_SESSION['customer_guest_id'] = $customer_id;
  1739. // set the customer address information in the array for the table insertion
  1740. $sql_data_array = array(
  1741. 'customers_id' => $customer_id,
  1742. 'entry_gender' => $paypal_ec_payer_info['payer_gender'],
  1743. 'entry_firstname' => $paypal_ec_payer_info['payer_firstname'],
  1744. 'entry_lastname' => $paypal_ec_payer_info['payer_lastname'],
  1745. 'entry_street_address' => $paypal_ec_payer_info['ship_street_1'],
  1746. 'entry_suburb' => $paypal_ec_payer_info['ship_street_2'],
  1747. 'entry_city' => $paypal_ec_payer_info['ship_city'],
  1748. 'entry_zone_id' => $state_id,
  1749. 'entry_postcode' => $paypal_ec_payer_info['ship_postal_code'],
  1750. 'entry_country_id' => $country_id);
  1751. if (isset($paypal_ec_payer_info['ship_name']) && $paypal_ec_payer_info['ship_name'] != '' && $paypal_ec_payer_info['ship_name'] != $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname']) {
  1752. $sql_data_array['entry_company'] = $paypal_ec_payer_info['ship_name'];
  1753. }
  1754. if ($state_id > 0) {
  1755. $sql_data_array['entry_zone_id'] = $state_id;
  1756. $sql_data_array['entry_state'] = '';
  1757. } else {
  1758. $sql_data_array['entry_zone_id'] = 0;
  1759. $sql_data_array['entry_state'] = $paypal_ec_payer_info['ship_state'];
  1760. }
  1761. // insert the data
  1762. zen_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);
  1763. // grab the address_id (last insert id)
  1764. $address_id = $db->Insert_ID();
  1765. // set the address id lookup for the customer
  1766. $sql = "UPDATE " . TABLE_CUSTOMERS . "
  1767. SET customers_default_address_id = :addrID
  1768. WHERE customers_id = :custID";
  1769. $sql = $db->bindVars($sql, ':addrID', $address_id, 'integer');
  1770. $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
  1771. $db->Execute($sql);
  1772. // insert the new customer_id into the customers info table for consistency
  1773. $sql = "INSERT INTO " . TABLE_CUSTOMERS_INFO . "
  1774. (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_date_of_last_logon)
  1775. VALUES (:custID, 1, now(), now())";
  1776. $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
  1777. $db->Execute($sql);
  1778. // send Welcome Email if appropriate
  1779. if ($this->new_acct_notify == 'Yes') {
  1780. // require the language file
  1781. global $language_page_directory, $template_dir;
  1782. if (!isset($language_page_directory)) $language_page_directory = DIR_WS_LANGUAGES . $_SESSION['language'] . '/';
  1783. if (file_exists($language_page_directory . $template_dir . '/create_account.php')) {
  1784. $template_dir_select = $template_dir . '/';
  1785. } else {
  1786. $template_dir_select = '';
  1787. }
  1788. require($language_page_directory . $template_dir_select . '/create_account.php');
  1789. // set the mail text
  1790. $email_text = sprintf(EMAIL_GREET_NONE, $paypal_ec_payer_info['payer_firstname']) . EMAIL_WELCOME . "\n\n" . EMAIL_TEXT;
  1791. $email_text .= "\n\n" . EMAIL_EC_ACCOUNT_INFORMATION . "\nUsername: " . $paypal_ec_payer_info['payer_email'] . "\nPassword: " . $password . "\n\n";
  1792. $email_text .= EMAIL_CONTACT;
  1793. // include create-account-specific disclaimer
  1794. $email_text .= "\n\n" . sprintf(EMAIL_DISCLAIMER_NEW_CUSTOMER, STORE_OWNER_EMAIL_ADDRESS). "\n\n";
  1795. $email_html = array();
  1796. $email_html['EMAIL_GREETING'] = sprintf(EMAIL_GREET_NONE, $paypal_ec_payer_info['payer_firstname']) ;
  1797. $email_html['EMAIL_WELCOME'] = EMAIL_WELCOME;
  1798. $email_html['EMAIL_MESSAGE_HTML'] = nl2br(EMAIL_TEXT . "\n\n" . EMAIL_EC_ACCOUNT_INFORMATION . "\nUsername: " . $paypal_ec_payer_info['payer_email'] . "\nPassword: " . $password . "\n\n");
  1799. $email_html['EMAIL_CONTACT_OWNER'] = EMAIL_CONTACT;
  1800. $email_html['EMAIL_CLOSURE'] = nl2br(EMAIL_GV_CLOSURE);
  1801. $email_html['EMAIL_DISCLAIMER'] = sprintf(EMAIL_DISCLAIMER_NEW_CUSTOMER, '<a href="mailto:' . STORE_OWNER_EMAIL_ADDRESS . '">'. STORE_OWNER_EMAIL_ADDRESS .' </a>');
  1802. // send the mail
  1803. if (trim(EMAIL_SUBJECT) != 'n/a') zen_mail($paypal_ec_payer_info['payer_firstname'] . " " . $paypal_ec_payer_info['payer_lastname'], $paypal_ec_payer_info['payer_email'], EMAIL_SUBJECT, $email_text, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, $email_html, 'welcome');
  1804. // set the express checkout temp -- false means the account is no longer "only" for EC ... it'll be permanent
  1805. $_SESSION['paypal_ec_temp'] = false;
  1806. } else {
  1807. // Make it a temporary account that'll be deleted once they've checked out
  1808. $sql = "UPDATE " . TABLE_CUSTOMERS . "
  1809. SET customers_paypal_ec = 1
  1810. WHERE customers_id = :custID ";
  1811. $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
  1812. $db->Execute($sql);
  1813. // set the boolean ec temp value since we created account strictly for EC purposes
  1814. $_SESSION['paypal_ec_temp'] = true;
  1815. }
  1816. // hook notifier class vis a vis account-creation
  1817. $this->notify('NOTIFY_LOGIN_SUCCESS_VIA_CREATE_ACCOUNT');
  1818. } else {
  1819. // set the boolean ec temp value for the account to false, since we didn't have to create one
  1820. $_SESSION['paypal_ec_temp'] = false;
  1821. }
  1822. // log the user in with the email sent back from paypal response
  1823. $this->user_login($_SESSION['paypal_ec_payer_info']['payer_email'], false);
  1824. // debug
  1825. $this->zcLog('ec_step2_finish - 7', 'Auto-Logged customer in. (' . $_SESSION['paypal_ec_payer_info']['payer_email'] . ') (' . $_SESSION['customer_id'] . ')' . "\n" . '$_SESSION[paypal_ec_temp]=' . $_SESSION['paypal_ec_temp']);
  1826. // This is the address matching section
  1827. // try to match it first
  1828. // note: this is by no means 100%
  1829. $address_book_id = $this->findMatchingAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing));
  1830. // no match add the record
  1831. if (!$address_book_id) {
  1832. $address_book_id = $this->addAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing), false);
  1833. if (!$address_book_id) {
  1834. $address_book_id = $_SESSION['customer_default_address_id'];
  1835. }
  1836. }
  1837. // set the sendto to the address
  1838. $_SESSION['sendto'] = $address_book_id;
  1839. // set billto in the session
  1840. $_SESSION['billto'] = $_SESSION['customer_default_address_id'];
  1841. // select a shipping method, based on cheapest available option
  1842. if (MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING == 'Yes') $this->setShippingMethod();
  1843. // debug
  1844. $this->zcLog('ec_step2_finish - 8', 'Exiting via terminateEC (from originally-not-logged-in mode).' . "\n" . 'Selected address: ' . $address_book_id . "\nOriginal was: " . (int)$original_default_address_id . "\nprepared data: " . print_r($order->customer, true));
  1845. // send the user on
  1846. if ($_SESSION['paypal_ec_markflow'] == 1) {
  1847. $this->terminateEC('', false, FILENAME_CHECKOUT_PROCESS);
  1848. } else {
  1849. $this->terminateEC('', false, FILENAME_CHECKOUT_CONFIRMATION);
  1850. }
  1851. }
  1852. }
  1853. /**
  1854. * Determine the appropriate shipping method if applicable
  1855. * By default, selects the lowest-cost quote
  1856. */
  1857. function setShippingMethod() {
  1858. global $total_count, $total_weight;
  1859. // ensure that cart contents is calculated properly for weight and value
  1860. if (!isset($total_weight)) $total_weight = $_SESSION['cart']->show_weight();
  1861. if (!isset($total_count)) $total_count = $_SESSION['cart']->count_contents();
  1862. // set the shipping method if one is not already set
  1863. // defaults to the cheapest shipping method
  1864. if ( !$_SESSION['shipping'] || ( $_SESSION['shipping'] && ($_SESSION['shipping'] == false) && (zen_count_shipping_modules() > 1) ) ) {
  1865. require_once(DIR_WS_CLASSES . 'http_client.php');
  1866. require_once(DIR_WS_CLASSES . 'shipping.php');
  1867. $shipping_Obj = new shipping;
  1868. // generate the quotes
  1869. $shipping_Obj->quote();
  1870. // set the cheapest one
  1871. $_SESSION['shipping'] = $shipping_Obj->cheapest();
  1872. }
  1873. }
  1874. /**
  1875. * Get Override Address (uses sendto if set, otherwise uses customer's primary address)
  1876. */
  1877. function getOverrideAddress() {
  1878. global $db;
  1879. // Only proceed IF *in* markflow mode AND logged-in (have to be logged in to get to markflow mode anyway)
  1880. if (!empty($_GET['markflow']) && isset($_SESSION['customer_id']) && $_SESSION['customer_id']) {
  1881. // From now on for this user we will edit addresses in Zen Cart, not by going to PayPal.
  1882. $_SESSION['paypal_ec_markflow'] = 1;
  1883. // debug
  1884. $this->zcLog('getOverrideAddress - 1', 'Now in markflow mode.' . "\n" . 'SESSION[sendto] = ' . (int)$_SESSION['sendto']);
  1885. // find the users default address id
  1886. if (!empty($_SESSION['sendto'])) {
  1887. $address_id = $_SESSION['sendto'];
  1888. } else {
  1889. $sql = "SELECT customers_default_address_id
  1890. FROM " . TABLE_CUSTOMERS . "
  1891. WHERE customers_id = :customerId";
  1892. $sql = $db->bindVars($sql, ':customerId', $_SESSION['customer_id'], 'integer');
  1893. $default_address_id_arr = $db->Execute($sql);
  1894. if (!$default_address_id_arr->EOF) {
  1895. $address_id = $default_address_id_arr->fields['customers_default_address_id'];
  1896. } else {
  1897. // couldn't find an address.
  1898. return false;
  1899. }
  1900. }
  1901. // now grab the address from the database and set it as the overridden address
  1902. $sql = "SELECT entry_firstname, entry_lastname, entry_company,
  1903. entry_street_address, entry_suburb, entry_city, entry_postcode,
  1904. entry_country_id, entry_zone_id, entry_state
  1905. FROM " . TABLE_ADDRESS_BOOK . "
  1906. WHERE address_book_id = :addressId
  1907. AND customers_id = :customerId
  1908. LIMIT 1";
  1909. $sql = $db->bindVars($sql, ':addressId', $address_id, 'integer');
  1910. $sql = $db->bindVars($sql, ':customerId', $_SESSION['customer_id'], 'integer');
  1911. $address_arr = $db->Execute($sql);
  1912. // see if we found a record, if not then we have nothing to override with
  1913. if (!$address_arr->EOF) {
  1914. // get the state/prov code
  1915. $sql = "SELECT zone_code
  1916. FROM " . TABLE_ZONES . "
  1917. WHERE zone_id = :zoneId";
  1918. $sql = $db->bindVars($sql, ':zoneId', $address_arr->fields['entry_zone_id'], 'integer');
  1919. $state_code_arr = $db->Execute($sql);
  1920. if ($state_code_arr->EOF) {
  1921. $state_code_arr->fields['zone_code'] = '';
  1922. }
  1923. if ($state_code_arr->fields['zone_code'] == '' && $address_arr->fields['entry_state'] != '') {
  1924. $state_code_arr->fields['zone_code'] = $address_arr->fields['entry_state'];
  1925. }
  1926. $address_arr->fields['zone_code'] = $state_code_arr->fields['zone_code'];
  1927. // get the country code
  1928. // ISO 3166 standard country code
  1929. $sql = "SELECT countries_iso_code_2
  1930. FROM " . TABLE_COUNTRIES . "
  1931. WHERE countries_id = :countryId";
  1932. $sql = $db->bindVars($sql, ':countryId', $address_arr->fields['entry_country_id'], 'integer');
  1933. $country_code_arr = $db->Execute($sql);
  1934. if ($country_code_arr->EOF) {
  1935. // default to US if not found
  1936. $country_code_arr->fields['countries_iso_code_2'] = 'US';
  1937. }
  1938. $address_arr->fields['countries_iso_code_2'] = $country_code_arr->fields['countries_iso_code_2'];
  1939. // debug
  1940. $this->zcLog('getOverrideAddress - 2', '$address_arr->fields = ' . print_r($address_arr->fields, true));
  1941. // return address data.
  1942. return $address_arr->fields;
  1943. }
  1944. // debug
  1945. $this->zcLog('getOverrideAddress - 3', 'no override record found');
  1946. }
  1947. // debug
  1948. $this->zcLog('getOverrideAddress - 4', 'not logged in and not in markflow mode - nothing to override');
  1949. return false;
  1950. }
  1951. /**
  1952. * This method attempts to match items in an address book, to avoid
  1953. * duplicate entries to the address book. On a successful match it
  1954. * returns the address_book_id(int) - on failure it returns false.
  1955. *
  1956. * @param int $customer_id
  1957. * @param array $address_question_arr
  1958. * @return int|boolean
  1959. */
  1960. function findMatchingAddressBookEntry($customer_id, $address_question_arr) {
  1961. global $db;
  1962. // if address is blank, don't do any matching
  1963. if ($address_question_arr['street_address'] == '') return false;
  1964. // default
  1965. $country_id = '223';
  1966. $address_format_id = 2; //2 is the American format
  1967. // first get the zone id's from the 2 digit iso codes
  1968. // country first
  1969. $sql = "SELECT countries_id, address_format_id
  1970. FROM " . TABLE_COUNTRIES . "
  1971. WHERE countries_iso_code_2 = :countryId
  1972. OR countries_name = :countryId
  1973. LIMIT 1";
  1974. $sql = $db->bindVars($sql, ':countryId', $address_question_arr['country']['iso_code_2'], 'string');
  1975. $country = $db->Execute($sql);
  1976. // see if we found a record, if not default to American format
  1977. if (!$country->EOF) {
  1978. $country_id = $country->fields['countries_id'];
  1979. $address_format_id = $country->fields['address_format_id'];
  1980. }
  1981. // see if the country code has a state
  1982. $sql = "SELECT zone_id
  1983. FROM " . TABLE_ZONES . "
  1984. WHERE zone_country_id = :zoneId
  1985. LIMIT 1";
  1986. $sql = $db->bindVars($sql, ':zoneId', $country_id, 'integer');
  1987. $country_zone_check = $db->Execute($sql);
  1988. $check_zone = $country_zone_check->RecordCount();
  1989. $zone_id = 0;
  1990. $logMsg = array('zone_id' => '-not found-');
  1991. // now try and find the zone_id (state/province code)
  1992. // use the country id above
  1993. if ($check_zone) {
  1994. $sql = "SELECT zone_id
  1995. FROM " . TABLE_ZONES . "
  1996. WHERE zone_country_id = :zoneId
  1997. AND (zone_code = :zoneCode
  1998. OR zone_name = :zoneCode )
  1999. LIMIT 1";
  2000. $sql = $db->bindVars($sql, ':zoneId', $country_id, 'integer');
  2001. $sql = $db->bindVars($sql, ':zoneCode', $address_question_arr['state'], 'string');
  2002. $zone = $db->Execute($sql);
  2003. if (!$zone->EOF) {
  2004. // grab the id
  2005. $zone_id = $zone->fields['zone_id'];
  2006. $logMsg = $zone->fields;
  2007. } else {
  2008. $check_zone = false;
  2009. }
  2010. }
  2011. // debug
  2012. $this->zcLog('findMatchingAddressBookEntry - 1-stats', 'lookups:' . "\n" . print_r(array_merge($country->fields, array('zone_country_id' => $country_zone_check->fields['zone_id']), $logMsg), true) . "\n" . 'check_zone: ' . $check_zone . "\n" . 'zone:' . $zone_id . "\nSubmittedAddress:".print_r($address_question_arr, TRUE));
  2013. // do a match on address, street, street2, city
  2014. $sql = "SELECT address_book_id, entry_street_address, entry_suburb, entry_city, entry_company, entry_firstname, entry_lastname
  2015. FROM " . TABLE_ADDRESS_BOOK . "
  2016. WHERE customers_id = :customerId
  2017. AND entry_country_id = :countryId";
  2018. if ($check_zone) {
  2019. $sql .= " AND entry_zone_id = :zoneId";
  2020. }
  2021. $sql = $db->bindVars($sql, ':zoneId', $zone_id, 'integer');
  2022. $sql = $db->bindVars($sql, ':countryId', $country_id, 'integer');
  2023. $sql = $db->bindVars($sql, ':customerId', $customer_id, 'integer');
  2024. $answers_arr = $db->Execute($sql);
  2025. // debug
  2026. $this->zcLog('findMatchingAddressBookEntry - 2-read for match', "\nLookup RecordCount = " . $answers_arr->RecordCount());
  2027. if (!$answers_arr->EOF) {
  2028. // build a base string to compare street+suburb+city content
  2029. //$matchQuestion = str_replace("\n", '', $address_question_arr['company']);
  2030. //$matchQuestion = str_replace("\n", '', $address_question_arr['name']);
  2031. $matchQuestion = str_replace("\n", '', $address_question_arr['street_address']);
  2032. $matchQuestion = trim($matchQuestion);
  2033. $matchQuestion = $matchQuestion . str_replace("\n", '', $address_question_arr['suburb']);
  2034. $matchQuestion = $matchQuestion . str_replace("\n", '', $address_question_arr['city']);
  2035. $matchQuestion = str_replace("\t", '', $matchQuestion);
  2036. $matchQuestion = trim($matchQuestion);
  2037. $matchQuestion = strtolower($matchQuestion);
  2038. $matchQuestion = str_replace(' ', '', $matchQuestion);
  2039. // go through the data
  2040. while (!$answers_arr->EOF) {
  2041. // now the matching logic
  2042. // first from the db
  2043. $fromDb = '';
  2044. // $fromDb = str_replace("\n", '', $answers_arr->fields['entry_company']);
  2045. /// $fromDb = str_replace("\n", '', $answers_arr->fields['entry_firstname'].$answers_arr->fields['entry_lastname']);
  2046. $fromDb = str_replace("\n", '', $answers_arr->fields['entry_street_address']);
  2047. $fromDb = trim($fromDb);
  2048. $fromDb = $fromDb . str_replace("\n", '', $answers_arr->fields['entry_suburb']);
  2049. $fromDb = $fromDb . str_replace("\n", '', $answers_arr->fields['entry_city']);
  2050. $fromDb = str_replace("\t", '', $fromDb);
  2051. $fromDb = trim($fromDb);
  2052. $fromDb = strtolower($fromDb);
  2053. $fromDb = str_replace(' ', '', $fromDb);
  2054. // debug
  2055. $this->zcLog('findMatchingAddressBookEntry - 3a', "From PayPal:\r\n" . $matchQuestion . "\r\n\r\nFrom DB:\r\n" . $fromDb . "\r\n". print_r($answers_arr->fields, true));
  2056. // check the strings
  2057. if (strlen($fromDb) == strlen($matchQuestion)) {
  2058. if ($fromDb == $matchQuestion) {
  2059. // exact match return the id
  2060. // debug
  2061. $this->zcLog('findMatchingAddressBookEntry - 3b', "Exact match:\n" . print_r($answers_arr->fields, true));
  2062. return $answers_arr->fields['address_book_id'];
  2063. }
  2064. } elseif (strlen($fromDb) > strlen($matchQuestion)) {
  2065. if (substr($fromDb, 0, strlen($matchQuestion)) == $matchQuestion) {
  2066. // we have a match return it (PP)
  2067. // debug
  2068. $this->zcLog('findMatchingAddressBookEntry - 3b', "partial match (PP):\n" . print_r($answers_arr->fields, true));
  2069. return $answers_arr->fields['address_book_id'];
  2070. }
  2071. } else {
  2072. if ($fromDb == substr($matchQuestion, 0, strlen($fromDb))) {
  2073. // we have a match return it (DB)
  2074. // debug
  2075. $this->zcLog('findMatchingAddressBookEntry - 3b', "partial match (DB):\n" . print_r($answers_arr->fields, true));
  2076. return $answers_arr->fields['address_book_id'];
  2077. }
  2078. }
  2079. $answers_arr->MoveNext();
  2080. }
  2081. }
  2082. // debug
  2083. $this->zcLog('findMatchingAddressBookEntry - 4', "no match");
  2084. // no matches found
  2085. return false;
  2086. }
  2087. /**
  2088. * This method adds an address book entry to the database, this allows us to add addresses
  2089. * that we get back from PayPal that are not in Zen Cart
  2090. *
  2091. * @param int $customer_id
  2092. * @param array $address_question_arr
  2093. * @return int
  2094. */
  2095. function addAddressBookEntry($customer_id, $address_question_arr, $make_default = false) {
  2096. global $db;
  2097. // debug
  2098. $this->zcLog('addAddressBookEntry - 1', 'address to add: ' . "\n" . print_r($address_question_arr, true));
  2099. // set some defaults
  2100. $country_id = '223';
  2101. $address_format_id = 2; //2 is the American format
  2102. // first get the zone id's from the 2 digit iso codes
  2103. // country first
  2104. $sql = "SELECT countries_id, address_format_id
  2105. FROM " . TABLE_COUNTRIES . "
  2106. WHERE countries_iso_code_2 = :countryId
  2107. OR countries_name = :countryId
  2108. LIMIT 1";
  2109. $sql = $db->bindVars($sql, ':countryId', $address_question_arr['country']['title'], 'string');
  2110. $country = $db->Execute($sql);
  2111. // see if we found a record, if not default to American format
  2112. if (!$country->EOF) {
  2113. $country_id = $country->fields['countries_id'];
  2114. $address_format_id = (int)$country->fields['address_format_id'];
  2115. }
  2116. // see if the country code has a state
  2117. $sql = "SELECT zone_id
  2118. FROM " . TABLE_ZONES . "
  2119. WHERE zone_country_id = :zoneId
  2120. LIMIT 1";
  2121. $sql = $db->bindVars($sql, ':zoneId', $country_id, 'integer');
  2122. $country_zone_check = $db->Execute($sql);
  2123. $check_zone = $country_zone_check->RecordCount();
  2124. // now try and find the zone_id (state/province code)
  2125. // use the country id above
  2126. if ($check_zone) {
  2127. $sql = "SELECT zone_id
  2128. FROM " . TABLE_ZONES . "
  2129. WHERE zone_country_id = :zoneId
  2130. AND (zone_code = :zoneCode
  2131. OR zone_name = :zoneCode )
  2132. LIMIT 1";
  2133. $sql = $db->bindVars($sql, ':zoneId', $country_id, 'integer');
  2134. $sql = $db->bindVars($sql, ':zoneCode', $address_question_arr['state'], 'string');
  2135. $zone = $db->Execute($sql);
  2136. if (!$zone->EOF) {
  2137. // grab the id
  2138. $zone_id = $zone->fields['zone_id'];
  2139. } else {
  2140. $zone_id = 0;
  2141. }
  2142. }
  2143. // now run the insert
  2144. // this isn't the best way to get fname/lname but it will get the majority of cases
  2145. list($fname, $lname) = explode(' ', $address_question_arr['name']);
  2146. $sql_data_array= array(array('fieldName'=>'entry_firstname', 'value'=>$fname, 'type'=>'string'),
  2147. array('fieldName'=>'entry_lastname', 'value'=>$lname, 'type'=>'string'),
  2148. array('fieldName'=>'entry_street_address', 'value'=>$address_question_arr['street_address'], 'type'=>'string'),
  2149. array('fieldName'=>'entry_postcode', 'value'=>$address_question_arr['postcode'], 'type'=>'string'),
  2150. array('fieldName'=>'entry_city', 'value'=>$address_question_arr['city'], 'type'=>'string'),
  2151. array('fieldName'=>'entry_country_id', 'value'=>$country_id, 'type'=>'integer'));
  2152. if ($address_question_arr['company'] != '' && $address_question_arr['company'] != $address_question_arr['name']) array('fieldName'=>'entry_company', 'value'=>$address_question_arr['company'], 'type'=>'string');
  2153. $sql_data_array[] = array('fieldName'=>'entry_gender', 'value'=>$address_question_arr['payer_gender'], 'type'=>'enum:m|f');
  2154. $sql_data_array[] = array('fieldName'=>'entry_suburb', 'value'=>$address_question_arr['suburb'], 'type'=>'string');
  2155. if ($zone_id > 0) {
  2156. $sql_data_array[] = array('fieldName'=>'entry_zone_id', 'value'=>$zone_id, 'type'=>'integer');
  2157. $sql_data_array[] = array('fieldName'=>'entry_state', 'value'=>'', 'type'=>'string');
  2158. } else {
  2159. $sql_data_array[] = array('fieldName'=>'entry_zone_id', 'value'=>'0', 'type'=>'integer');
  2160. $sql_data_array[] = array('fieldName'=>'entry_state', 'value'=>$address_question_arr['state'], 'type'=>'string');
  2161. }
  2162. $sql_data_array[] = array('fieldName'=>'customers_id', 'value'=>$customer_id, 'type'=>'integer');
  2163. $db->perform(TABLE_ADDRESS_BOOK, $sql_data_array);
  2164. $new_address_book_id = $db->Insert_ID();
  2165. $this->notify('NOTIFY_HEADER_ADDRESS_BOOK_ADD_ENTRY_DONE');
  2166. // make default if set, update
  2167. if ($make_default) {
  2168. $sql_data_array = array();
  2169. $sql_data_array[] = array('fieldName'=>'customers_default_address_id', 'value'=>$new_address_book_id, 'type'=>'integer');
  2170. $where_clause = "customers_id = :customersID";
  2171. $where_clause = $db->bindVars($where_clause, ':customersID', $customer_id, 'integer');
  2172. $db->perform(TABLE_CUSTOMERS, $sql_data_array, 'update', $where_clause);
  2173. $_SESSION['customer_default_address_id'] = $new_address_book_id;
  2174. }
  2175. // set the sendto
  2176. $_SESSION['sendto'] = $new_address_book_id;
  2177. // debug
  2178. $this->zcLog('addAddressBookEntry - 2', 'added address #' . $new_address_book_id. "\n" . 'SESSION[sendto] is now set to ' . $_SESSION['sendto']);
  2179. // return the address_id
  2180. return $new_address_book_id;
  2181. }
  2182. /**
  2183. * If we created an account for the customer, this logs them in and notes that the record was created for PayPal EC purposes
  2184. */
  2185. function user_login($email_address, $redirect = true) {
  2186. global $db, $order, $messageStack;
  2187. global $session_started;
  2188. if ($session_started == false) {
  2189. zen_redirect(zen_href_link(FILENAME_COOKIE_USAGE));
  2190. }
  2191. $sql = "SELECT * FROM " . TABLE_CUSTOMERS . "
  2192. WHERE customers_email_address = :custEmail ";
  2193. $sql = $db->bindVars($sql, ':custEmail', $email_address, 'string');
  2194. $check_customer = $db->Execute($sql);
  2195. if ($check_customer->EOF) {
  2196. $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_BAD_LOGIN, true);
  2197. }
  2198. if (SESSION_RECREATE == 'True') {
  2199. zen_session_recreate();
  2200. }
  2201. $sql = "SELECT entry_country_id, entry_zone_id
  2202. FROM " . TABLE_ADDRESS_BOOK . "
  2203. WHERE customers_id = :custID
  2204. AND address_book_id = :addrID ";
  2205. $sql = $db->bindVars($sql, ':custID', $check_customer->fields['customers_id'], 'integer');
  2206. $sql = $db->bindVars($sql, ':addrID', $check_customer->fields['customers_default_address_id'], 'integer');
  2207. $check_country = $db->Execute($sql);
  2208. $_SESSION['customer_id'] = (int)$check_customer->fields['customers_id'];
  2209. $_SESSION['customer_default_address_id'] = $check_customer->fields['customers_default_address_id'];
  2210. $_SESSION['customer_first_name'] = $check_customer->fields['customers_firstname'];
  2211. $_SESSION['customer_country_id'] = $check_country->fields['entry_country_id'];
  2212. $_SESSION['customer_zone_id'] = $check_country->fields['entry_zone_id'];
  2213. $order->customer['id'] = $_SESSION['customer_id'];
  2214. $sql = "UPDATE " . TABLE_CUSTOMERS_INFO . "
  2215. SET customers_info_date_of_last_logon = now(),
  2216. customers_info_number_of_logons = customers_info_number_of_logons+1
  2217. WHERE customers_info_id = :custID ";
  2218. $sql = $db->bindVars($sql, ':custID', $_SESSION['customer_id'], 'integer');
  2219. $db->Execute($sql);
  2220. // bof: contents merge notice
  2221. // save current cart contents count if required
  2222. if (SHOW_SHOPPING_CART_COMBINED > 0) {
  2223. $zc_check_basket_before = $_SESSION['cart']->count_contents();
  2224. }
  2225. // bof: not require part of contents merge notice
  2226. // restore cart contents
  2227. $_SESSION['cart']->restore_contents();
  2228. // eof: not require part of contents merge notice
  2229. // check current cart contents count if required
  2230. if (SHOW_SHOPPING_CART_COMBINED > 0 && $zc_check_basket_before > 0) {
  2231. $zc_check_basket_after = $_SESSION['cart']->count_contents();
  2232. if (($zc_check_basket_before != $zc_check_basket_after) && $_SESSION['cart']->count_contents() > 0 && SHOW_SHOPPING_CART_COMBINED > 0) {
  2233. if (SHOW_SHOPPING_CART_COMBINED == 2) {
  2234. // warning only do not send to cart
  2235. $messageStack->add_session('header', WARNING_SHOPPING_CART_COMBINED, 'caution');
  2236. }
  2237. if (SHOW_SHOPPING_CART_COMBINED == 1) {
  2238. // show warning and send to shopping cart for review
  2239. $messageStack->add_session('shopping_cart', WARNING_SHOPPING_CART_COMBINED, 'caution');
  2240. zen_redirect(zen_href_link(FILENAME_SHOPPING_CART, '', 'NONSSL'));
  2241. }
  2242. }
  2243. }
  2244. // eof: contents merge notice
  2245. if ($redirect) {
  2246. $this->terminateEC();
  2247. }
  2248. return true;
  2249. }
  2250. /**
  2251. * If the account was created only for temporary purposes to place the PayPal order, delete it.
  2252. */
  2253. function ec_delete_user($cid) {
  2254. global $db;
  2255. unset($_SESSION['customer_id']);
  2256. unset($_SESSION['customer_default_address_id']);
  2257. unset($_SESSION['customer_first_name']);
  2258. unset($_SESSION['customer_country_id']);
  2259. unset($_SESSION['customer_zone_id']);
  2260. unset($_SESSION['comments']);
  2261. unset($_SESSION['customer_guest_id']);
  2262. $cid = (int)$cid;
  2263. $sql = "delete from " . TABLE_ADDRESS_BOOK . " where customers_id = " . $cid;
  2264. $db->Execute($sql);
  2265. $sql = "delete from " . TABLE_CUSTOMERS . " where customers_id = " . $cid;
  2266. $db->Execute($sql);
  2267. $sql = "delete from " . TABLE_CUSTOMERS_INFO . " where customers_info_id = " . $cid;
  2268. $db->Execute($sql);
  2269. $sql = "delete from " . TABLE_CUSTOMERS_BASKET . " where customers_id = " . $cid;
  2270. $db->Execute($sql);
  2271. $sql = "delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id = " . $cid;
  2272. $db->Execute($sql);
  2273. $sql = "delete from " . TABLE_WHOS_ONLINE . " where customer_id = " . $cid;
  2274. $db->Execute($sql);
  2275. }
  2276. /**
  2277. * If the EC flow has to be interrupted for any reason, this does the appropriate cleanup and displays status/error messages.
  2278. */
  2279. function terminateEC($error_msg = '', $kill_sess_vars = false, $goto_page = '') {
  2280. global $messageStack, $order, $order_total_modules;
  2281. $error_msg = trim($error_msg);
  2282. if (substr($error_msg, -1) == '-') $error_msg = trim(substr($error_msg, 0, strlen($error_msg) - 1));
  2283. $stackAlert = 'header';
  2284. // debug
  2285. $this->_doDebug('PayPal test Log - terminateEC-A', "goto page: " . $goto_page . "\nerror_msg: " . $error_msg . "\n\nSession data: " . print_r($_SESSION, true));
  2286. if ($kill_sess_vars) {
  2287. if (!empty($_SESSION['paypal_ec_temp'])) {
  2288. $this->ec_delete_user($_SESSION['customer_id']);
  2289. }
  2290. // Unregister the paypal session variables, making the user start over.
  2291. unset($_SESSION['paypal_ec_temp']);
  2292. unset($_SESSION['paypal_ec_token']);
  2293. unset($_SESSION['paypal_ec_payer_id']);
  2294. unset($_SESSION['paypal_ec_payer_info']);
  2295. unset($_SESSION['paypal_ec_final']);
  2296. unset($_SESSION['paypal_ec_markflow']);
  2297. // debug
  2298. $this->zcLog('termEC-1', 'Killed the session vars as requested');
  2299. }
  2300. $this->zcLog('termEC-2', 'BEFORE: $this->showPaymentPage = ' . (int)$this->showPaymentPage . "\nToken Data:" . $_SESSION['paypal_ec_token']);
  2301. // force display of payment page if GV/DC active for this customer
  2302. if (MODULE_ORDER_TOTAL_INSTALLED && $this->showPaymentPage !== true && isset($_SESSION['paypal_ec_token']) ) {
  2303. require_once(DIR_WS_CLASSES . 'order.php');
  2304. $order = new order;
  2305. require_once(DIR_WS_CLASSES . 'order_total.php');
  2306. $order_total_modules = new order_total;
  2307. $order_totals = $order_total_modules->process();
  2308. $selection = $order_total_modules->credit_selection();
  2309. if (sizeof($selection)>0) $this->showPaymentPage = true;
  2310. }
  2311. // if came from Payment page, don't go back to it
  2312. if ($_SESSION['paypal_ec_markflow'] == 1) $this->showPaymentPage = false;
  2313. // if in DP mode, don't go to payment page ... we've already been there to get here
  2314. if ($goto_page == FILENAME_CHECKOUT_PROCESS) $this->showPaymentPage = false;
  2315. // debug
  2316. $this->zcLog('termEC-3', 'AFTER: $this->showPaymentPage = ' . (int)$this->showPaymentPage);
  2317. if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id'])) {
  2318. if ($this->showPaymentPage === true || $goto_page == FILENAME_CHECKOUT_PAYMENT) {
  2319. // debug
  2320. $this->zcLog('termEC-4', 'We ARE logged in, and $this->showPaymentPage === true');
  2321. // if no shipping selected or if shipping cost is < 0 goto shipping page
  2322. if ((!$_SESSION['shipping'] || $_SESSION['shipping'] == '') || $_SESSION['shipping']['cost'] < 0) {
  2323. // debug
  2324. $this->zcLog('termEC-5', 'Have no shipping method selected, or shipping < 0 so set FILENAME_CHECKOUT_SHIPPING');
  2325. $redirect_path = FILENAME_CHECKOUT_SHIPPING;
  2326. $stackAlert = 'checkout_shipping';
  2327. } else {
  2328. // debug
  2329. $this->zcLog('termEC-6', 'We DO have a shipping method selected, so goto PAYMENT');
  2330. $redirect_path = FILENAME_CHECKOUT_PAYMENT;
  2331. $stackAlert = 'checkout_payment';
  2332. }
  2333. } elseif ($goto_page) {
  2334. // debug
  2335. $this->zcLog('termEC-7', '$this->showPaymentPage NOT true, and have custom page parameter: ' . $goto_page);
  2336. $redirect_path = $goto_page;
  2337. $stackAlert = 'header';
  2338. if ($goto_page == FILENAME_SHOPPING_CART) $stackAlert = 'shopping_cart';
  2339. } else {
  2340. // debug
  2341. $this->zcLog('termEC-8', '$this->showPaymentPage NOT true, and NO custom page selected ... using SHIPPING as default');
  2342. $redirect_path = FILENAME_CHECKOUT_SHIPPING;
  2343. $stackAlert = 'checkout_shipping';
  2344. }
  2345. } else {
  2346. // debug
  2347. $this->zcLog('termEC-9', 'We are NOT logged in, so set snapshot to Shipping page, and redirect to login');
  2348. $_SESSION['navigation']->set_snapshot(FILENAME_CHECKOUT_SHIPPING);
  2349. $redirect_path = FILENAME_LOGIN;
  2350. $stackAlert = 'login';
  2351. }
  2352. if ($error_msg) {
  2353. $messageStack->add_session($stackAlert, $error_msg, 'error');
  2354. }
  2355. // debug
  2356. $this->zcLog('termEC-10', 'Redirecting to ' . $redirect_path . ' - Stack: ' . $stackAlert . "\n" . 'Message: ' . $error_msg . "\nSession Data: " . print_r($_SESSION, true));
  2357. zen_redirect(zen_href_link($redirect_path, '', 'SSL', true, false));
  2358. }
  2359. /**
  2360. * Error / exception handling
  2361. */
  2362. function _errorHandler($response, $operation = '', $ignore_codes = '') {
  2363. global $messageStack, $doPayPal;
  2364. $gateway_mode = (isset($response['PNREF']) && $response['PNREF'] != '');
  2365. $basicError = (!$response || (isset($response['RESULT']) && $response['RESULT'] != 0) || (isset($response['ACK']) && !strstr($response['ACK'], 'Success')) || (!isset($response['RESULT']) && !isset($response['ACK'])));
  2366. $ignoreList = explode(',', str_replace(' ', '', $ignore_codes));
  2367. foreach($ignoreList as $key=>$value) {
  2368. if ($value != '' && $response['L_ERRORCODE0'] == $value) $basicError = false;
  2369. }
  2370. /** Handle unilateral **/
  2371. if ($response['RESULT'] == 'Unauthorized: Unilateral') {
  2372. $errorText = $response['RESULT'] . MODULE_PAYMENT_PAYPALWPP_TEXT_UNILATERAL;
  2373. $messageStack->add_session($errorText, 'error');
  2374. }
  2375. /** Handle FMF Scenarios **/
  2376. if (in_array($operation, array('DoExpressCheckoutPayment', 'DoDirectPayment')) && $response['PAYMENTSTATUS'] == 'Pending' && $response['L_ERRORCODE0'] == 11610) {
  2377. $this->fmfResponse = urldecode($response['L_SHORTMESSAGE0']);
  2378. $this->fmfErrors = array();
  2379. if ($response['ACK'] == 'SuccessWithWarning' && isset($response['L_FMFPENDINGID0'])) {
  2380. for ($i=0; $i<20; $i++) {
  2381. $this->fmfErrors[] = array('key' => $response['L_FMFPENDINGID' . $i], 'status' => $response['L_FMFPENDINGID' . $i], 'desc' => $response['L_FMFPENDINGDESCRIPTION' . $i]);
  2382. }
  2383. }
  2384. return (sizeof($this->fmfErrors)>0) ? $this->fmfErrors : FALSE;
  2385. }
  2386. if (!isset($response['L_SHORTMESSAGE0']) && isset($response['RESPMSG']) && $response['RESPMSG'] != '') $response['L_SHORTMESSAGE0'] = $response['RESPMSG'];
  2387. //echo '<br />basicError='.$basicError.'<br />' . urldecode(print_r($response,true)); die('halted');
  2388. $errorInfo = "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with PayPal Express Checkout.';
  2389. switch($operation) {
  2390. case 'SetExpressCheckout':
  2391. if ($basicError) {
  2392. // if error, display error message. If debug options enabled, email dump to store owner
  2393. if ($this->enableDebugging) {
  2394. $this->_doDebug('PayPal Error Log - ec_step1()', "In function: ec_step1()\r\n\r\nValue List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2395. }
  2396. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_GEN_ERROR;
  2397. $errorNum = urldecode($response['L_ERRORCODE0'] . $response['RESULT']);
  2398. if ($response['RESULT'] == 25) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_NOT_WPP_ACCOUNT_ERROR;
  2399. if ($response['L_ERRORCODE0'] == 10002) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_SANDBOX_VS_LIVE_ERROR;
  2400. if ($response['L_ERRORCODE0'] == 10565) {
  2401. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_WPP_BAD_COUNTRY_ERROR;
  2402. $_SESSION['payment'] = '';
  2403. }
  2404. if ($response['L_ERRORCODE0'] == 10736) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_ADDR_ERROR;
  2405. if ($response['L_ERRORCODE0'] == 10752) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_DECLINED;
  2406. $detailedMessage = ($errorText == MODULE_PAYMENT_PAYPALWPP_TEXT_GEN_ERROR || $this->enableDebugging || $response['CURL_ERRORS'] != '' || $this->emailAlerts) ? $errorNum . ' ' . urldecode(' ' . $response['L_SHORTMESSAGE0'] . ' - ' . $response['L_LONGMESSAGE0'] . (isset($response['RESPMSG']) ? ' ' . $response['RESPMSG'] : '') . ' ' . $response['CURL_ERRORS']) : '';
  2407. $detailedEmailMessage = ($detailedMessage == '') ? '' : MODULE_PAYMENT_PAYPALWPP_TEXT_EMAIL_ERROR_MESSAGE . urldecode($response['L_ERRORCODE0'] . "\n" . $response['L_SHORTMESSAGE0'] . "\n" . $response['L_LONGMESSAGE0'] . $response['L_ERRORCODE1'] . "\n" . $response['L_SHORTMESSAGE1'] . "\n" . $response['L_LONGMESSAGE1'] . $response['L_ERRORCODE2'] . "\n" . $response['L_SHORTMESSAGE2'] . "\n" . $response['L_LONGMESSAGE2'] . ($response['CURL_ERRORS'] != '' ? "\n" . $response['CURL_ERRORS'] : '') . "\n\n" . 'Zen Cart message: ' . $errorText) . $errorInfo;
  2408. if ($detailedEmailMessage != '') zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALWPP_TEXT_EMAIL_ERROR_SUBJECT . ' (' . zen_uncomment($errorNum) . ')', zen_uncomment($detailedMessage), STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>zen_uncomment($detailedMessage)), 'paymentalert');
  2409. $this->terminateEC($errorText . ' (' . $errorNum . ') ' . $detailedMessage, true);
  2410. return true;
  2411. }
  2412. break;
  2413. case 'GetExpressCheckoutDetails':
  2414. if ($basicError || $_SESSION['paypal_ec_token'] != urldecode($response['TOKEN'])) {
  2415. // if response indicates an error, send the customer back to checkout and display the error. Debug to store owner if active.
  2416. if ($this->enableDebugging) {
  2417. $this->_doDebug('PayPal Error Log - ec_step2()', "In function: ec_step2()\r\n\r\nValue List:\r\n" . str_replace('&',"\r\n", urldecode($doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList)))) . "\r\n\r\nResponse:\r\n" . urldecode(print_r($response, true)));
  2418. }
  2419. $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_GEN_ERROR . ' (' . $response['L_ERRORCODE0'] . ' ' . urldecode($response['L_SHORTMESSAGE0'] . $response['RESULT']) . ')', true);
  2420. return true;
  2421. }
  2422. break;
  2423. case 'DoExpressCheckoutPayment':
  2424. if ($basicError || $_SESSION['paypal_ec_token'] != urldecode($response['TOKEN'])) {
  2425. // there's an error, so alert customer, and if debug is on, notify storeowner
  2426. if ($this->enableDebugging) {
  2427. $this->_doDebug('PayPal Error Log - before_process() - EC', "In function: before_process() - Express Checkout\r\n\r\nValue List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2428. }
  2429. // if funding source problem occurred, must send back to re-select alternate funding source
  2430. if ($response['L_ERRORCODE0'] == 10422) {
  2431. $paypal_url = $this->getPayPalLoginServer();
  2432. zen_redirect($paypal_url . "?cmd=_express-checkout&token=" . $_SESSION['paypal_ec_token']);
  2433. die();
  2434. }
  2435. // some other error condition
  2436. $errorText = MODULE_PAYMENT_PAYPALWPP_INVALID_RESPONSE;
  2437. $errorNum = urldecode($response['L_ERRORCODE0']);
  2438. if ($response['L_ERRORCODE0'] == 10415) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_ORDER_ALREADY_PLACED_ERROR;
  2439. if ($response['L_ERRORCODE0'] == 10417) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_INSUFFICIENT_FUNDS_ERROR;
  2440. if ($response['L_ERRORCODE0'] == 10474) $errorText .= urldecode($response['L_LONGMESSAGE0']);
  2441. $detailedMessage = ($errorText == MODULE_PAYMENT_PAYPALWPP_INVALID_RESPONSE || $this->enableDebugging || $response['CURL_ERRORS'] != '' || $this->emailAlerts) ? $errorNum . ' ' . urldecode(' ' . $response['L_SHORTMESSAGE0'] . ' - ' . $response['L_LONGMESSAGE0'] . $response['RESULT'] . ' ' . $response['CURL_ERRORS']) : '';
  2442. $detailedEmailMessage = ($detailedMessage == '') ? '' : MODULE_PAYMENT_PAYPALWPP_TEXT_EMAIL_ERROR_MESSAGE . urldecode($response['L_ERRORCODE0'] . "\n" . $response['L_SHORTMESSAGE0'] . "\n" . $response['L_LONGMESSAGE0'] . $response['L_ERRORCODE1'] . "\n" . $response['L_SHORTMESSAGE1'] . "\n" . $response['L_LONGMESSAGE1'] . $response['L_ERRORCODE2'] . "\n" . $response['L_SHORTMESSAGE2'] . "\n" . $response['L_LONGMESSAGE2'] . ($response['CURL_ERRORS'] != '' ? "\n" . $response['CURL_ERRORS'] : '') . "\n\n" . 'Zen Cart message: ' . $errorText) . $errorInfo;
  2443. if ($detailedEmailMessage != '') zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALWPP_TEXT_EMAIL_ERROR_SUBJECT . ' (' . zen_uncomment($errorNum) . ')', zen_uncomment($detailedMessage), STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>zen_uncomment($detailedMessage)), 'paymentalert');
  2444. $this->terminateEC(($detailedEmailMessage == '' ? $errorText . ' (' . urldecode($response['L_SHORTMESSAGE0'] . $response['RESULT']) . ') ' : $detailedMessage), true);
  2445. return true;
  2446. }
  2447. break;
  2448. case 'DoRefund':
  2449. if ($basicError || (!isset($response['RESPMSG']) && !isset($response['REFUNDTRANSACTIONID']))) {
  2450. // if error, display error message. If debug options enabled, email dump to store owner
  2451. if ($this->enableDebugging) {
  2452. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2453. }
  2454. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_REFUND_ERROR;
  2455. if ($response['L_ERRORCODE0'] == 10009) $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_REFUNDFULL_ERROR;
  2456. if ($response['RESULT'] == 105 || isset($response['RESPMSG'])) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  2457. if (urldecode($response['L_LONGMESSAGE0']) == 'This transaction has already been fully refunded') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  2458. if (urldecode($response['L_LONGMESSAGE0']) == 'Can not do a full refund after a partial refund') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  2459. if (urldecode($response['L_LONGMESSAGE0']) == 'The partial refund amount must be less than or equal to the remaining amount') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  2460. if (urldecode($response['L_LONGMESSAGE0']) == 'You can not refund this type of transaction') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  2461. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  2462. $messageStack->add_session($errorText, 'error');
  2463. return true;
  2464. }
  2465. break;
  2466. case 'DoAuthorization':
  2467. case 'DoReauthorization':
  2468. if ($basicError) {
  2469. // if error, display error message. If debug options enabled, email dump to store owner
  2470. if ($this->enableDebugging) {
  2471. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2472. }
  2473. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_AUTH_ERROR;
  2474. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  2475. $messageStack->add_session($errorText, 'error');
  2476. return true;
  2477. }
  2478. break;
  2479. case 'DoCapture':
  2480. if ($basicError) {
  2481. // if error, display error message. If debug options enabled, email dump to store owner
  2482. if ($this->enableDebugging) {
  2483. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2484. }
  2485. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_CAPT_ERROR;
  2486. if ($response['RESULT'] == 111) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  2487. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  2488. $messageStack->add_session($errorText, 'error');
  2489. return true;
  2490. }
  2491. break;
  2492. case 'DoVoid':
  2493. if ($basicError) {
  2494. // if error, display error message. If debug options enabled, email dump to store owner
  2495. if ($this->enableDebugging) {
  2496. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2497. }
  2498. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_VOID_ERROR;
  2499. if ($response['RESULT'] == 12) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  2500. if ($response['RESULT'] == 108) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  2501. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  2502. $messageStack->add_session($errorText, 'error');
  2503. return true;
  2504. }
  2505. break;
  2506. case 'GetTransactionDetails':
  2507. if ($basicError) {
  2508. // if error, display error message. If debug options enabled, email dump to store owner
  2509. if ($this->enableDebugging) {
  2510. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2511. }
  2512. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_GETDETAILS_ERROR;
  2513. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  2514. $messageStack->add_session($errorText, 'error');
  2515. return true;
  2516. }
  2517. break;
  2518. case 'TransactionSearch':
  2519. if ($basicError) {
  2520. // if error, display error message. If debug options enabled, email dump to store owner
  2521. if ($this->enableDebugging) {
  2522. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2523. }
  2524. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_TRANSSEARCH_ERROR;
  2525. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  2526. $messageStack->add_session($errorText, 'error');
  2527. return true;
  2528. }
  2529. break;
  2530. default:
  2531. if ($basicError) {
  2532. // if error, display error message. If debug options enabled, email dump to store owner
  2533. if ($this->enableDebugging) {
  2534. $this->_doDebug('PayPal Error Log - ' . $operation, "Value List:\r\n" . str_replace('&',"\r\n", $doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList))) . "\r\n\r\nResponse:\r\n" . print_r($response, true));
  2535. }
  2536. $errorText = MODULE_PAYMENT_PAYPALWPP_TEXT_GEN_API_ERROR;
  2537. $errorNum .= ' (' . urldecode($response['L_SHORTMESSAGE0'] . ' <!-- ' . $response['RESPMSG']) . ' -->) ' . $response['L_ERRORCODE0'];
  2538. $detailedMessage = ($errorText == MODULE_PAYMENT_PAYPALWPP_TEXT_GEN_API_ERROR || $errorText == MODULE_PAYMENT_PAYPALWPP_TEXT_DECLINED || $this->enableDebugging || $response['CURL_ERRORS'] != '' || $this->emailAlerts) ? urldecode(' ' . $response['L_SHORTMESSAGE0'] . ' - ' . $response['L_LONGMESSAGE0'] . ' ' . $response['CURL_ERRORS']) : '';
  2539. $detailedEmailMessage = ($detailedMessage == '') ? '' : MODULE_PAYMENT_PAYPALWPP_TEXT_EMAIL_ERROR_MESSAGE . ' ' . $response['RESPMSG'] . urldecode($response['L_ERRORCODE0'] . "\n" . $response['L_SHORTMESSAGE0'] . "\n" . $response['L_LONGMESSAGE0'] . $response['L_ERRORCODE1'] . "\n" . $response['L_SHORTMESSAGE1'] . "\n" . $response['L_LONGMESSAGE1'] . $response['L_ERRORCODE2'] . "\n" . $response['L_SHORTMESSAGE2'] . "\n" . $response['L_LONGMESSAGE2'] . ($response['CURL_ERRORS'] != '' ? "\n" . $response['CURL_ERRORS'] : '') . "\n\n" . 'Zen Cart message: ' . $detailedMessage . "\n\n" . 'Transaction Response Details: ' . print_r($response, true) . "\n\n" . 'Transaction Submission: ' . urldecode($doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList), true)));
  2540. if ($detailedEmailMessage != '') zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALWPP_TEXT_EMAIL_ERROR_SUBJECT . ' (' . zen_uncomment($errorNum) . ')', zen_uncomment($detailedMessage), STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br(zen_uncomment($detailedEmailMessage))), 'paymentalert');
  2541. $messageStack->add_session($errorText . $errorNum . $detailedMessage, 'error');
  2542. return true;
  2543. }
  2544. break;
  2545. }
  2546. }
  2547. function tableCheckup() {
  2548. global $db, $sniffer;
  2549. $fieldOkay1 = (method_exists($sniffer, 'field_type')) ? $sniffer->field_type(TABLE_PAYPAL, 'txn_id', 'varchar(20)', true) : -1;
  2550. $fieldOkay2 = ($sniffer->field_exists(TABLE_PAYPAL, 'module_name')) ? true : -1;
  2551. $fieldOkay3 = ($sniffer->field_exists(TABLE_PAYPAL, 'order_id')) ? true : -1;
  2552. if ($fieldOkay1 == -1) {
  2553. $sql = "show fields from " . TABLE_PAYPAL;
  2554. $result = $db->Execute($sql);
  2555. while (!$result->EOF) {
  2556. if ($result->fields['Field'] == 'txn_id') {
  2557. if ($result->fields['Type'] == 'varchar(20)') {
  2558. $fieldOkay1 = true; // exists and matches required type, so skip to other checkup
  2559. } else {
  2560. $fieldOkay1 = $result->fields['Type']; // doesn't match, so return what it "is"
  2561. break;
  2562. }
  2563. }
  2564. $result->MoveNext();
  2565. }
  2566. }
  2567. if ($fieldOkay1 !== true) {
  2568. // temporary fix to table structure for v1.3.7.x -- may remove in later release
  2569. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payment_type payment_type varchar(40) NOT NULL default ''");
  2570. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE txn_type txn_type varchar(40) NOT NULL default ''");
  2571. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payment_status payment_status varchar(32) NOT NULL default ''");
  2572. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE reason_code reason_code varchar(40) default NULL");
  2573. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE pending_reason pending_reason varchar(32) default NULL");
  2574. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE invoice invoice varchar(128) default NULL");
  2575. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payer_business_name payer_business_name varchar(128) default NULL");
  2576. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_name address_name varchar(64) default NULL");
  2577. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_street address_street varchar(254) default NULL");
  2578. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_city address_city varchar(120) default NULL");
  2579. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_state address_state varchar(120) default NULL");
  2580. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payer_email payer_email varchar(128) NOT NULL default ''");
  2581. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE business business varchar(128) NOT NULL default ''");
  2582. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE receiver_email receiver_email varchar(128) NOT NULL default ''");
  2583. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE txn_id txn_id varchar(20) NOT NULL default ''");
  2584. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE parent_txn_id parent_txn_id varchar(20) default NULL");
  2585. }
  2586. if ($fieldOkay2 !== true) {
  2587. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " ADD COLUMN module_name varchar(40) NOT NULL default '' after txn_type");
  2588. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " ADD COLUMN module_mode varchar(40) NOT NULL default '' after module_name");
  2589. }
  2590. if ($fieldOkay3 !== true) {
  2591. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE zen_order_id order_id int(11) NOT NULL default '0'");
  2592. }
  2593. }
  2594. }