PageRenderTime 71ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/modules/payment/paypaldp.php

https://bitbucket.org/gcooksey3/zencart
PHP | 2606 lines | 1900 code | 190 blank | 516 comment | 767 complexity | 993152fe9bc182ed12590a61686aa3ec MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. * paypaldp.php payment module class for Paypal Payments Pro (aka Website Payments Pro)
  4. *
  5. * @package paymentMethod
  6. * @copyright Copyright 2003-2012 Zen Cart Development Team
  7. * @copyright Portions Copyright 2005 CardinalCommerce
  8. * @copyright Portions Copyright 2003 osCommerce
  9. * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
  10. * @version GIT: $Id: Author: DrByte Tue Aug 28 14:21:34 2012 -0400 Modified in v1.5.1 $
  11. */
  12. /**
  13. * The transaction URL for the Cardinal Centinel 3D-Secure service.
  14. */
  15. define('MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL', 'https://paypal.cardinalcommerce.com/maps/processormodule.asp');
  16. //define('MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL', 'https://centineltest.cardinalcommerce.com/maps/processormodule.asp');
  17. /**
  18. * debug flag for developer use only:
  19. */
  20. if (!defined('MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING')) define('MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING', FALSE);
  21. /**
  22. * load the communications layer code
  23. */
  24. require_once(DIR_FS_CATALOG . DIR_WS_MODULES . 'payment/paypal/paypal_curl.php');
  25. /**
  26. * the PayPal payment module for PayPal Payments Pro (Direct Payment API)
  27. */
  28. class paypaldp extends base {
  29. /**
  30. * name of this module
  31. *
  32. * @var string
  33. */
  34. var $code;
  35. /**
  36. * displayed module title
  37. *
  38. * @var string
  39. */
  40. var $title;
  41. /**
  42. * displayed module description
  43. *
  44. * @var string
  45. */
  46. var $description;
  47. /**
  48. * module status - set based on various config and zone criteria
  49. *
  50. * @var string
  51. */
  52. var $enabled;
  53. /**
  54. * the zone to which this module is restricted for use
  55. *
  56. * @var string
  57. */
  58. var $zone;
  59. /**
  60. * array holding accepted DP/gateway card types
  61. *
  62. * @var array
  63. */
  64. var $cards = array();
  65. /**
  66. * JS code used for gateway/DP mode
  67. *
  68. * @var string
  69. */
  70. var $cc_type_javascript = '';
  71. /**
  72. * JS code used for gateway/DP mode
  73. *
  74. * @var string
  75. */
  76. var $cc_type_check = '';
  77. /**
  78. * debugging flag
  79. *
  80. * @var boolean
  81. */
  82. var $enableDebugging = false;
  83. /**
  84. * is DP enabled ?
  85. *
  86. * @var boolean
  87. */
  88. var $enableDirectPayment = true;
  89. /**
  90. * sort order of display
  91. *
  92. * @var int
  93. */
  94. var $sort_order = 0;
  95. /**
  96. * Button Source / BN code -- enables the module to work for Zen Cart sites
  97. *
  98. * @var string
  99. */
  100. var $buttonSource = 'ZenCart-DP_us';
  101. /**
  102. * order status setting for pending orders
  103. *
  104. * @var int
  105. */
  106. var $order_pending_status = 1;
  107. /**
  108. * order status setting for completed orders
  109. *
  110. * @var int
  111. */
  112. var $order_status = DEFAULT_ORDERS_STATUS_ID;
  113. /**
  114. * Debug tools
  115. */
  116. var $_logDir = 'includes/modules/payment/paypal/logs/';
  117. var $_logLevel = 0;
  118. /**
  119. * FMF
  120. */
  121. var $fmfResponse = '';
  122. var $fmfErrors = array();
  123. /**
  124. * class constructor
  125. */
  126. function paypaldp() {
  127. include_once(zen_get_file_directory(DIR_FS_CATALOG . DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/payment/', 'paypaldp.php', 'false'));
  128. global $order;
  129. $this->code = 'paypaldp';
  130. $this->codeTitle = MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_TITLE_WPP;
  131. $this->codeVersion = '1.5.1';
  132. $this->enableDirectPayment = true;
  133. $this->enabled = (MODULE_PAYMENT_PAYPALDP_STATUS == 'True');
  134. // Set the title & description text based on the mode we're in
  135. if (IS_ADMIN_FLAG === true) {
  136. $this->description = sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_DESCRIPTION, ' (rev' . $this->codeVersion . ')');
  137. $country = (defined('MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY')) ? MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY : STORE_COUNTRY;
  138. $this->title = $country == '223' || $country == 'USA' ? MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_TITLE_WPP : MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_TITLE_NONUSA;
  139. $this->title .= (defined('MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY') ? ' (' . MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY . ')' : '');
  140. if ($this->enabled) {
  141. if ( ((MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'US' || MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'Canada') && (MODULE_PAYMENT_PAYPALWPP_APISIGNATURE == '' || MODULE_PAYMENT_PAYPALWPP_APIUSERNAME == '' || MODULE_PAYMENT_PAYPALWPP_APIPASSWORD == ''))
  142. || (!defined('MODULE_PAYMENT_PAYPALWPP_STATUS') || MODULE_PAYMENT_PAYPALWPP_STATUS != 'True')
  143. ) $this->title .= '<span class="alert"><strong> NOT CONFIGURED YET</strong></span>';
  144. if (MODULE_PAYMENT_PAYPALDP_SERVER =='sandbox') $this->title .= '<strong><span class="alert"> (sandbox active)</span></strong>';
  145. if (MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log File' || MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log and Email') $this->title .= '<strong> (Debug)</strong>';
  146. if (!function_exists('curl_init')) $this->title .= '<strong><span class="alert"> CURL NOT FOUND. Cannot Use.</span></strong>';
  147. }
  148. } else {
  149. $this->description = MODULE_PAYMENT_PAYPALDP_TEXT_DESCRIPTION;
  150. $this->title = MODULE_PAYMENT_PAYPALDP_TEXT_TITLE; //cc
  151. }
  152. if ((!defined('PAYPAL_OVERRIDE_CURL_WARNING') || (defined('PAYPAL_OVERRIDE_CURL_WARNING') && PAYPAL_OVERRIDE_CURL_WARNING != 'True')) && !function_exists('curl_init')) $this->enabled = false;
  153. $this->enableDebugging = (MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log and Email');
  154. $this->emailAlerts = (MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log and Email' || MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Alerts Only');
  155. $this->sort_order = MODULE_PAYMENT_PAYPALDP_SORT_ORDER;
  156. $this->buttonSource = (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') ? 'ZenCart-DP_uk' : 'ZenCart-DP_us';
  157. $this->order_pending_status = MODULE_PAYMENT_PAYPALDP_ORDER_PENDING_STATUS_ID;
  158. if ((int)MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID > 0) {
  159. $this->order_status = MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID;
  160. }
  161. // $this->new_acct_notify = MODULE_PAYMENT_PAYPALDP_NEW_ACCT_NOTIFY;
  162. $this->zone = (int)MODULE_PAYMENT_PAYPALDP_ZONE;
  163. if (is_object($order)) $this->update_status();
  164. if (PROJECT_VERSION_MAJOR != '1' && substr(PROJECT_VERSION_MINOR, 0, 3) != '5.0') $this->enabled = false;
  165. // offer credit card choices for pull-down menu -- only needed for UK version
  166. $this->cards = array();
  167. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') {
  168. if (CC_ENABLED_VISA=='1') $this->cards[] = array('id' => 'Visa', 'text' => 'Visa');
  169. if (CC_ENABLED_MC=='1') $this->cards[] = array('id' => 'MasterCard', 'text' => 'MasterCard');
  170. if (CC_ENABLED_MAESTRO=='1') $this->cards[] = array('id' => 'Maestro', 'text' => 'Maestro');
  171. if (CC_ENABLED_SWITCH=='1') $this->cards[] = array('id' => 'Switch', 'text' => 'Switch');
  172. if (CC_ENABLED_SOLO=='1') $this->cards[] = array('id' => 'Solo', 'text' => 'Solo');
  173. }
  174. // debug setup
  175. if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_CATALOG . $this->_logDir;
  176. if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_SQL_CACHE;
  177. // Regular mode:
  178. if ($this->enableDebugging) $this->_logLevel = 2;
  179. // DEV MODE:
  180. if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $this->_logLevel = 3;
  181. if (IS_ADMIN_FLAG === true) $this->tableCheckup();
  182. }
  183. /**
  184. * Sets payment module status based on zone restrictions etc
  185. */
  186. function update_status() {
  187. global $order, $db;
  188. // $this->zcLog('update_status', 'Checking whether module should be enabled or not.');
  189. // if store is not running in SSL, cannot offer credit card module, for PCI reasons
  190. if (!defined('ENABLE_SSL') || ENABLE_SSL != 'true') {
  191. $this->enabled = FALSE;
  192. $this->zcLog('update_status', 'Module disabled because SSL is not enabled on this site.');
  193. }
  194. // check other reasons for the module to be deactivated:
  195. if ($this->enabled && (int)$this->zone > 0) {
  196. $check_flag = false;
  197. $sql = "SELECT zone_id
  198. FROM " . TABLE_ZONES_TO_GEO_ZONES . "
  199. WHERE geo_zone_id = :zoneId
  200. AND zone_country_id = :countryId
  201. ORDER BY zone_id";
  202. $sql = $db->bindVars($sql, ':zoneId', $this->zone, 'integer');
  203. $sql = $db->bindVars($sql, ':countryId', $order->billing['country']['id'], 'integer');
  204. $check = $db->Execute($sql);
  205. while (!$check->EOF) {
  206. if ($check->fields['zone_id'] < 1) {
  207. $check_flag = true;
  208. break;
  209. } elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
  210. $check_flag = true;
  211. break;
  212. }
  213. $check->MoveNext();
  214. }
  215. if (!$check_flag) {
  216. $this->enabled = false;
  217. $this->zcLog('update_status', 'Module disabled due to zone restriction. Billing address is not within the Payment Zone selected in the module settings.');
  218. }
  219. // module cannot be used for purchase > $10,000 USD
  220. $order_amount = $this->calc_order_amount($order->info['total'], 'USD');
  221. if ($order_amount > 10000) {
  222. $this->enabled = false;
  223. $this->zcLog('update_status', 'Module disabled because purchase price (' . $order_amount . ') exceeds PayPal-imposed maximum limit of 10,000 USD.');
  224. }
  225. if ($order->info['total'] == 0) {
  226. $this->enabled = false;
  227. $this->zcLog('update_status', 'Module disabled because purchase amount is set to 0.00.' . "\n" . print_r($order, true));
  228. }
  229. }
  230. }
  231. /**
  232. * Validate the credit card information via javascript (Number, Owner, and CVV Lengths)
  233. */
  234. function javascript_validation() {
  235. return ' if (payment_value == "' . $this->code . '") {' . "\n" .
  236. ' var cc_firstname = document.checkout_payment.paypalwpp_cc_firstname.value;' . "\n" .
  237. ' var cc_lastname = document.checkout_payment.paypalwpp_cc_lastname.value;' . "\n" .
  238. ' var cc_number = document.checkout_payment.paypalwpp_cc_number.value;' . "\n" .
  239. ' var cc_checkcode = document.checkout_payment.paypalwpp_cc_checkcode.value;' . "\n" .
  240. ' if (cc_firstname == "" || cc_lastname == "" || eval(cc_firstname.length) + eval(cc_lastname.length) < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
  241. ' error_message = error_message + "' . MODULE_PAYMENT_PAYPALDP_TEXT_JS_CC_OWNER . '";' . "\n" .
  242. ' error = 1;' . "\n" .
  243. ' }' . "\n" .
  244. ' if (cc_number == "" || cc_number.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
  245. ' error_message = error_message + "' . MODULE_PAYMENT_PAYPALDP_TEXT_JS_CC_NUMBER . '";' . "\n" .
  246. ' error = 1;' . "\n" .
  247. ' }' . "\n" .
  248. ' if (document.checkout_payment.paypalwpp_cc_checkcode.disabled == false && (cc_checkcode == "" || cc_checkcode.length < 3 || cc_checkcode.length > 4)) {' . "\n".
  249. ' error_message = error_message + "' . MODULE_PAYMENT_PAYPALDP_TEXT_JS_CC_CVV . '";' . "\n" .
  250. ' error = 1;' . "\n" .
  251. ' }' . "\n" .
  252. ' }' . "\n";
  253. }
  254. /**
  255. * Display Credit Card Information Submission Fields on the Checkout Payment Page
  256. */
  257. function selection() {
  258. global $order;
  259. $this->cc_type_check =
  260. 'var value = document.checkout_payment.paypalwpp_cc_type.value;' .
  261. 'if (value == "Solo" || value == "Maestro" || value == "Switch") {' .
  262. ' document.checkout_payment.paypalwpp_cc_issue_month.disabled = false;' .
  263. ' document.checkout_payment.paypalwpp_cc_issue_year.disabled = false;' .
  264. ' document.checkout_payment.paypalwpp_cc_checkcode.disabled = false;' .
  265. ' if (document.checkout_payment.paypalwpp_cc_issuenumber) document.checkout_payment.paypalwpp_cc_issuenumber.disabled = false;' .
  266. '} else {' .
  267. ' if (document.checkout_payment.paypalwpp_cc_issuenumber) document.checkout_payment.paypalwpp_cc_issuenumber.disabled = true;' .
  268. ' if (document.checkout_payment.paypalwpp_cc_issue_month) document.checkout_payment.paypalwpp_cc_issue_month.disabled = true;' .
  269. ' if (document.checkout_payment.paypalwpp_cc_issue_year) document.checkout_payment.paypalwpp_cc_issue_year.disabled = true;' .
  270. ' document.checkout_payment.paypalwpp_cc_checkcode.disabled = false;' .
  271. '}';
  272. if (sizeof($this->cards) == 0) $this->cc_type_check = '';
  273. /**
  274. * since we are processing via the gateway, prepare and display the CC fields
  275. */
  276. $expires_month = array();
  277. $expires_year = array();
  278. $issue_year = array();
  279. for ($i = 1; $i < 13; $i++) {
  280. $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B - (%m)',mktime(0,0,0,$i,1,2000)));
  281. }
  282. $today = getdate();
  283. for ($i = $today['year']; $i < $today['year'] + 15; $i++) {
  284. $expires_year[] = array('id' => strftime('%y', mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
  285. }
  286. $onFocus = ' onfocus="methodSelect(\'pmt-' . $this->code . '\')"';
  287. $fieldsArray = array();
  288. $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_FIRSTNAME,
  289. 'field' => zen_draw_input_field('paypalwpp_cc_firstname', $order->billing['firstname'], 'id="'.$this->code.'-cc-ownerf"'. $onFocus . ' autocomplete="off"') .
  290. '<script type="text/javascript">function paypalwpp_cc_type_check() { ' . $this->cc_type_check . ' } </script>',
  291. 'tag' => $this->code.'-cc-ownerf');
  292. $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_LASTNAME,
  293. 'field' => zen_draw_input_field('paypalwpp_cc_lastname', $order->billing['lastname'], 'id="'.$this->code.'-cc-ownerl"'. $onFocus . ' autocomplete="off"'),
  294. 'tag' => $this->code.'-cc-ownerl');
  295. if (sizeof($this->cards)>0) $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_TYPE,
  296. 'field' => zen_draw_pull_down_menu('paypalwpp_cc_type', $this->cards, '', 'onchange="paypalwpp_cc_type_check();" onblur="paypalwpp_cc_type_check();"' . 'id="'.$this->code.'-cc-type"'. $onFocus),
  297. 'tag' => $this->code.'-cc-type');
  298. $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_NUMBER,
  299. 'field' => zen_draw_input_field('paypalwpp_cc_number', $ccnum, 'id="'.$this->code.'-cc-number"' . $onFocus . ' autocomplete="off"'),
  300. 'tag' => $this->code.'-cc-number');
  301. $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_EXPIRES,
  302. 'field' => zen_draw_pull_down_menu('paypalwpp_cc_expires_month', $expires_month, strftime('%m'), 'id="'.$this->code.'-cc-expires-month"' . $onFocus) . '&nbsp;' . zen_draw_pull_down_menu('paypalwpp_cc_expires_year', $expires_year, '', 'id="'.$this->code.'-cc-expires-year"' . $onFocus),
  303. 'tag' => $this->code.'-cc-expires-month');
  304. $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_CHECKNUMBER,
  305. 'field' => zen_draw_input_field('paypalwpp_cc_checkcode', '', 'size="4" maxlength="4"' . ' id="'.$this->code.'-cc-cvv"' . $onFocus . ' autocomplete="off"') . '&nbsp;<small>' . MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_CHECKNUMBER_LOCATION . '</small><script type="text/javascript">paypalwpp_cc_type_check();</script>',
  306. 'tag' => $this->code.'-cc-cvv');
  307. $selection = array('id' => $this->code,
  308. 'module' => MODULE_PAYMENT_PAYPALDP_TEXT_TITLE,
  309. 'fields' => $fieldsArray);
  310. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && (CC_ENABLED_MAESTRO=='1' || CC_ENABLED_SWITCH=='1' || CC_ENABLED_SOLO=='1')) {
  311. // add extra fields for Switch/Solo cards
  312. for ($i = $today['year'] - 10; $i <= $today['year']; $i++) {
  313. $issue_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
  314. }
  315. array_splice($selection['fields'], 4, 0,
  316. array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_ISSUE,
  317. 'field' => zen_draw_pull_down_menu('paypalwpp_cc_issue_month', $expires_month, '', 'id="'.$this->code.'-cc-issue-month"' . $onFocus ) . '&nbsp;' . zen_draw_pull_down_menu('paypalwpp_cc_issue_year', $issue_year, '', 'id="'.$this->code.'-cc-issue-year"' . $onFocus),
  318. 'tag' => $this->code.'-cc-issue-month')));
  319. // add extra field for Maestro cards
  320. array_splice($selection['fields'], 4, 0,
  321. array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_MAESTRO_ISSUENUMBER,
  322. 'field' => zen_draw_input_field('paypalwpp_cc_issuenumber', $maestronum, 'size="4" maxlength="4"' . ' id="'.$this->code.'-cc-issuenumber"' . $onFocus . ' autocomplete="off"'),
  323. 'tag' => $this->code.'-cc-issuenumber')));
  324. // 3D-Secure
  325. $selection['fields'][] = array('title' => '',
  326. 'field' => '<div id="' . $this->code.'-cc-securetext"><p>' .
  327. '<a href="javascript:void window.open(\'vbv_learn_more.html\',\'vbv_service\',\'width=550,height=450\')">' .
  328. zen_image(DIR_WS_IMAGES.'3ds/vbv_learn_more.gif') . '</a>' .
  329. '<a href="javascript:void window.open(\'mcs_learn_more.html\',\'mcsc_service\',\'width=550,height=450\')">' .
  330. zen_image(DIR_WS_IMAGES.'3ds/mcsc_learn_more.gif') . '</a>' .
  331. '</p>' .
  332. '<p>' . TEXT_3DS_CARD_MAY_BE_ENROLLED . '</p></div>',
  333. 'tag' => $this->code.'-cc-securetext');
  334. }
  335. return $selection;
  336. }
  337. /**
  338. * This is the credit card check done between checkout_payment and
  339. * checkout_confirmation (called from checkout_confirmation).
  340. * Evaluates the Credit Card Type for acceptance and the validity of the Credit Card Number & Expiration Date
  341. */
  342. function pre_confirmation_check() {
  343. global $messageStack, $order;
  344. include(DIR_WS_CLASSES . 'cc_validation.php');
  345. $cc_validation = new cc_validation();
  346. $result = $cc_validation->validate($_POST['paypalwpp_cc_number'],
  347. $_POST['paypalwpp_cc_expires_month'], $_POST['paypalwpp_cc_expires_year'],
  348. (isset($_POST['paypalwpp_cc_issue_month']) ? $_POST['paypalwpp_cc_issue_month'] : ''), (isset($_POST['paypalwpp_cc_issue_year']) ? $_POST['paypalwpp_cc_issue_year'] : ''));
  349. $error = '';
  350. switch ($result) {
  351. case 1:
  352. break;
  353. case -1:
  354. $error = MODULE_PAYMENT_PAYPALDP_TEXT_BAD_CARD;//sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
  355. if ($_POST['paypalwpp_cc_number'] == '') $error = str_replace('\n', '', MODULE_PAYMENT_PAYPALDP_TEXT_JS_CC_NUMBER); // yes, those are supposed to be single-quotes.
  356. break;
  357. case -2:
  358. case -3:
  359. case -4:
  360. $error = TEXT_CCVAL_ERROR_INVALID_DATE;
  361. break;
  362. case false:
  363. $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
  364. break;
  365. }
  366. $_POST['paypalwpp_cc_checkcode'] = preg_replace('/[^0-9]/i', '', $_POST['paypalwpp_cc_checkcode']);
  367. if (isset($_POST['paypalwpp_cc_issuenumber'])) $_POST['paypalwpp_cc_issuenumber'] = preg_replace('/[^0-9]/i', '', $_POST['paypalwpp_cc_issuenumber']);
  368. if (($result === false) || ($result < 1) ) {
  369. $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $result . ' -->', 'error');
  370. zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
  371. }
  372. $this->cc_card_type = $cc_validation->cc_type;
  373. $this->cc_card_number = $cc_validation->cc_number;
  374. $this->cc_expiry_month = $cc_validation->cc_expiry_month;
  375. $this->cc_expiry_year = $cc_validation->cc_expiry_year;
  376. $this->cc_checkcode = $_POST['paypalwpp_cc_checkcode'];
  377. // In the case of UK cards, hook 3D-Secure if appropriate
  378. // 3D-Secure
  379. /**
  380. * Checks if the card is enrolled in an authentication program and
  381. * launches the start-authentication process if it is enrolled.
  382. * The order may continue to authorization if a card is not enrolled
  383. * or an error occurs.
  384. *
  385. * Under the Verified by Visa, MasterCard SecureCode and JCB J/Secure
  386. * program guidelines, not all credit cards are eligible for
  387. * participation in the payer authentication programs. Certain types of
  388. * credit and debit cards, such as commercial and prepaid cards,
  389. * are simply not able to participate in the programs. For this reason,
  390. * this configuration is available to provide the option to allow
  391. * transactions using credit and debit cards that are unable to be
  392. * authenticated to complete and proceed with authorization.
  393. */
  394. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && (!isset($_POST['MD']))) {
  395. if (isset($_SESSION['3Dsecure_auth_status']) && isset($_SESSION['3Dsecure_auth_xid']) && isset($_SESSION['3Dsecure_auth_cavv']) && isset($_SESSION['3Dsecure_auth_eci'])) {
  396. // at this point we have 3d-secure auth data
  397. } else {
  398. // at this stage we need to prepare for checking whether 3d-secure is needed
  399. $this->clear_3DSecure_session_vars(TRUE);
  400. $_SESSION['3Dsecure_requires_lookup'] = $this->requiresLookup($_POST['paypalwpp_cc_number']);
  401. $_SESSION['3Dsecure_card_type'] = $this->determineCardType($_POST['paypalwpp_cc_number']);
  402. }
  403. if (isset($_SESSION['3Dsecure_requires_lookup']) && $_SESSION['3Dsecure_requires_lookup'] == TRUE) {
  404. $_SESSION['3Dsecure_merchantData'] = serialize(array('im'=>$_POST['paypalwpp_cc_issue_month'], 'iy'=>$_POST['paypalwpp_cc_issue_year'], 'in'=>$_POST['paypalwpp_cc_issuenumber'], 'fn'=>$_POST['paypalwpp_cc_firstname'], 'ln'=>$_POST['paypalwpp_cc_lastname']));
  405. global $order_total_modules;
  406. $calculatedOrderTotal = $order_total_modules->pre_confirmation_check(TRUE);
  407. $lookup_data_array = array('currency' => $order->info['currency'],
  408. 'txn_amount' => $calculatedOrderTotal,
  409. 'order_desc' => 'Zen Cart(R) ' . MODULE_PAYMENT_PAYPALDP_TEXT_TRANSACTION_FOR . ' ' . $_POST['paypalwpp_cc_firstname'] . ' ' . $_POST['paypalwpp_cc_lastname'],
  410. 'cc3d_card_number' => $_POST['paypalwpp_cc_number'],
  411. 'cc3d_checkcode' => $_POST['paypalwpp_cc_checkcode'],
  412. 'cc3d_exp_month' => $_POST['paypalwpp_cc_expires_month'],
  413. 'cc3d_exp_year' => $_POST['paypalwpp_cc_expires_year'] );
  414. ////////////////////////////////////////////////////////////////////////////
  415. // Process the enrollment lookup
  416. ////////////////////////////////////////////////////////////////////////////
  417. $lookup_response = $this->get3DSecureLookupResponse($lookup_data_array);
  418. $shouldContinue = $lookup_response['continue_flag'];
  419. $errorNo = $lookup_response['error_no'];
  420. $errorDesc = $lookup_response['error_desc'];
  421. $_SESSION['3Dsecure_enrolled'] = $lookup_response['enrolled'];
  422. $_SESSION['3Dsecure_transactionId'] = $lookup_response['transaction_id'];
  423. $requestXML = $lookup_response['requestXML'];
  424. $rawXML = $lookup_response['rawXML'];
  425. if (isset($lookup_response['EciFlag'])) $_SESSION['3Dsecure_auth_eci'] = $lookup_response['EciFlag'];
  426. ////////////////////////////////////////////////////////////////////////////
  427. // Assert that there was no error code returned and the Cardholder is
  428. // enrolled in the authentication program prior to starting the
  429. // Authentication process.
  430. //
  431. // If the card is not enrolled or an error was returned, check the business
  432. // rules to determine if the order should continue.
  433. ////////////////////////////////////////////////////////////////////////////
  434. if (strcasecmp('0', $errorNo) == 0 && strcasecmp('Y', $_SESSION['3Dsecure_enrolled']) == 0) {
  435. ////////////////////////////////////////////////////////////////////////
  436. // Card is enrolled, continue to payer authentication
  437. ////////////////////////////////////////////////////////////////////////
  438. $_SESSION['3Dsecure_acsURL'] = $lookup_response['acs_url'];
  439. $_SESSION['3Dsecure_payload'] = $lookup_response['payload'];
  440. $this->form_action_url = zen_href_link(FILENAME_PAYER_AUTH_FRAME, '', 'SSL', true, false);
  441. } else {
  442. if ($shouldContinue != 'Y') {
  443. ////////////////////////////////////////////////////////////////////
  444. // Business rules are set to prompt for another form of payment
  445. ////////////////////////////////////////////////////////////////////
  446. $error= $this->get_authentication_error();
  447. if (in_array($errorNo, array('8000', '8010', '8020', '8030'))) $error = CENTINEL_PROCESSING_ERROR;
  448. $reason = $errorNo . ' - ' . $errorDesc;
  449. $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
  450. $errorText = $error . "\n\n" . $reason . "\n(" . $this->code . ")\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  451. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT . ' ' . $reason, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  452. zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
  453. } else {
  454. ////////////////////////////////////////////////////////////////////
  455. // Business rules are set to continue to authorization
  456. ////////////////////////////////////////////////////////////////////
  457. if (!isset($_SESSION['3Dsecure_auth_eci']) || $_SESSION['3Dsecure_auth_eci'] == '') {
  458. // Not enrolled or error, determine the ECI value for the card number, and make it available to the payment module.
  459. if ($_SESSION['3Dsecure_enrolled'] == 'N') {
  460. switch($_SESSION['3Dsecure_card_type']) {
  461. case 'VISA':
  462. $_SESSION['3Dsecure_auth_eci'] = "06";
  463. break;
  464. case 'MASTERCARD':
  465. $_SESSION['3Dsecure_auth_eci'] = "01";
  466. break;
  467. case 'JCB':
  468. $_SESSION['3Dsecure_auth_eci'] = "06";
  469. break;
  470. }
  471. } else if ('U' == $_SESSION['3Dsecure_enrolled'] || '0' != $errorNo) {
  472. switch($_SESSION['3Dsecure_card_type']) {
  473. case 'VISA':
  474. $_SESSION['3Dsecure_auth_eci'] = "07";
  475. break;
  476. case 'MASTERCARD':
  477. $_SESSION['3Dsecure_auth_eci'] = "01";
  478. break;
  479. case 'JCB':
  480. $_SESSION['3Dsecure_auth_eci'] = "07";
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. }
  487. }
  488. }
  489. // end uk/3d-secure check
  490. }
  491. /**
  492. * Display Credit Card Information for review on the Checkout Confirmation Page
  493. */
  494. function confirmation() {
  495. $confirmation = array('title' => '',
  496. 'fields' => array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_FIRSTNAME,
  497. 'field' => $_POST['paypalwpp_cc_firstname']),
  498. array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_LASTNAME,
  499. 'field' => $_POST['paypalwpp_cc_lastname']),
  500. array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_TYPE,
  501. 'field' => $this->cc_card_type),
  502. array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_NUMBER,
  503. 'field' => substr($_POST['paypalwpp_cc_number'], 0, 4) . str_repeat('X', (strlen($_POST['paypalwpp_cc_number']) - 8)) . substr($_POST['paypalwpp_cc_number'], -4)),
  504. array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_EXPIRES,
  505. 'field' => strftime('%B, %Y', mktime(0,0,0,$_POST['paypalwpp_cc_expires_month'], 1, '20' . $_POST['paypalwpp_cc_expires_year'])),
  506. (isset($_POST['paypalwpp_cc_issuenumber']) ? array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_ISSUE_NUMBER,
  507. 'field' => $_POST['paypalwpp_cc_issuenumber']) : '')
  508. )));
  509. // 3D-Secure
  510. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && $this->requiresLookup($_POST['paypalwpp_cc_number']) == true) {
  511. $confirmation['fields'][count($confirmation['fields'])] = array(
  512. 'title' => '',
  513. 'field' => '<div id="' . $this->code.'-cc-securetext"><p>' .
  514. '<a href="javascript:void window.open(\'vbv_learn_more.html\',\'vbv_service\',\'width=550,height=450\')">' .
  515. zen_image(DIR_WS_IMAGES.'3ds/vbv_learn_more.gif') . '</a>' .
  516. '<a href="javascript:void window.open(\'mcs_learn_more.html\',\'mcsc_service\',\'width=550,height=450\')">' .
  517. zen_image(DIR_WS_IMAGES.'3ds/mcsc_learn_more.gif') . '</a></p>' .
  518. '<p>' . TEXT_3DS_CARD_MAY_BE_ENROLLED . '</p></div>');
  519. }
  520. return $confirmation;
  521. }
  522. /**
  523. * Prepare the hidden fields comprising the parameters for the Submit button on the checkout confirmation page
  524. */
  525. function process_button() {
  526. global $order;
  527. $_SESSION['paypal_ec_markflow'] = 1;
  528. $process_button_string = '';
  529. $process_button_string .= "\n" . zen_draw_hidden_field('wpp_cc_type', $_POST['paypalwpp_cc_type']) . "\n" .
  530. zen_draw_hidden_field('wpp_cc_expdate_month', $_POST['paypalwpp_cc_expires_month']) . "\n" .
  531. zen_draw_hidden_field('wpp_cc_expdate_year', $_POST['paypalwpp_cc_expires_year']) . "\n" .
  532. zen_draw_hidden_field('wpp_cc_issuedate_month', $_POST['paypalwpp_cc_issue_month']) . "\n" .
  533. zen_draw_hidden_field('wpp_cc_issuedate_year', $_POST['paypalwpp_cc_issue_year']) . "\n" .
  534. zen_draw_hidden_field('wpp_cc_issuenumber', $_POST['paypalwpp_cc_issuenumber']) . "\n" .
  535. zen_draw_hidden_field('wpp_cc_number', $_POST['paypalwpp_cc_number']) . "\n" .
  536. zen_draw_hidden_field('wpp_cc_checkcode', $_POST['paypalwpp_cc_checkcode']) . "\n" .
  537. zen_draw_hidden_field('wpp_payer_firstname', $_POST['paypalwpp_cc_firstname']) . "\n" .
  538. zen_draw_hidden_field('wpp_payer_lastname', $_POST['paypalwpp_cc_lastname']) . "\n";
  539. $process_button_string .= zen_draw_hidden_field(zen_session_name(), zen_session_id());
  540. return $process_button_string;
  541. }
  542. /**
  543. * Prepare and submit the final authorization to PayPal via the appropriate means as configured
  544. */
  545. function before_process() {
  546. global $order, $doPayPal, $messageStack;
  547. $options = array();
  548. $optionsShip = array();
  549. $optionsNVP = array();
  550. $options = $this->getLineItemDetails($this->selectCurrency($order->info['currency']));
  551. //$this->zcLog('before_process - 1', 'Have line-item details:' . "\n" . print_r($options, true));
  552. // Initializing DESC field: using for comments related to tax-included pricing, populated by getLineItemDetails()
  553. $options['DESC'] = '';
  554. $doPayPal = $this->paypal_init();
  555. /****************************************
  556. * Do DP checkout
  557. ****************************************/
  558. $this->zcLog('before_process - DP-1', 'Beginning DP mode' /* . print_r($_POST, TRUE)*/);
  559. // Set state fields depending on what PayPal wants to see for that country
  560. $this->setStateAndCountry($order->billing);
  561. if (zen_not_null($order->delivery['street_address'])) {
  562. $this->setStateAndCountry($order->delivery);
  563. }
  564. // Validate credit card data
  565. include(DIR_WS_CLASSES . 'cc_validation.php');
  566. $cc_validation = new cc_validation();
  567. $response = $cc_validation->validate($_POST['wpp_cc_number'], $_POST['wpp_cc_expdate_month'], $_POST['wpp_cc_expdate_year'],
  568. $_POST['wpp_cc_issuedate_month'], $_POST['wpp_cc_issuedate_year']);
  569. $error = '';
  570. switch ($response) {
  571. case -1:
  572. $error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
  573. break;
  574. case -2:
  575. case -3:
  576. case -4:
  577. $error = TEXT_CCVAL_ERROR_INVALID_DATE;
  578. break;
  579. case false:
  580. $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
  581. break;
  582. }
  583. if (($response === false) || ($response < 1) ) {
  584. $this->zcLog('before_process - DP-2', 'CC validation results: ' . $error . '(' . $response . ')');
  585. $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $response . ' -->', 'error');
  586. zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
  587. }
  588. if (!in_array($cc_validation->cc_type, array('Visa', 'MasterCard', 'Switch', 'Solo', 'Discover', 'American Express', 'Maestro'))) {
  589. // $this->zcLog('before_process - DP-3', 'CC info: ' . $cc_validation->cc_type . ' ' . substr($cc_validation->cc_number, 0, 4) . str_repeat('X', (strlen($cc_validation->cc_number) - 8)) . substr($cc_validation->cc_number, -4) . ' ' . $error);
  590. $messageStack->add_session('checkout_payment', MODULE_PAYMENT_PAYPALDP_TEXT_BAD_CARD . '<!-- [' . $this->code . ' ' . $cc_validation->cc_type . '] -->', 'error');
  591. zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
  592. }
  593. // if CC validation passed, continue using the validated data
  594. $cc_type = $cc_validation->cc_type;
  595. $cc_number = $cc_validation->cc_number;
  596. $cc_first_name = ($_POST['wpp_payer_firstname'] != '' ? $_POST['wpp_payer_firstname'] : $_SESSION['customer_first_name']);
  597. $cc_last_name = ($_POST['wpp_payer_lastname'] != '' ? $_POST['wpp_payer_lastname'] : $_SESSION['customer_last_name']);
  598. $cc_checkcode = $_POST['wpp_cc_checkcode'];
  599. $cc_expdate_month = $cc_validation->cc_expiry_month;
  600. $cc_expdate_year = $cc_validation->cc_expiry_year;
  601. $cc_issuedate_month = $_POST['wpp_cc_issuedate_month'];
  602. $cc_issuedate_year = $_POST['wpp_cc_issuedate_year'];
  603. $cc_issuenumber = $_POST['wpp_cc_issuenumber'];
  604. $cc_owner_ip = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
  605. // If they're still here, set some of the order object's variables.
  606. $order->info['cc_type'] = $cc_type;
  607. $order->info['cc_number'] = substr($cc_number, 0, 4) . str_repeat('X', (strlen($cc_number) - 8)) . substr($cc_number, -4);
  608. $order->info['cc_owner'] = $cc_first_name . ' ' . $cc_last_name;
  609. $order->info['cc_expires'] = ''; //$cc_expdate_month . substr($cc_expdate_year, -2);
  610. $order->info['ip_address'] = $cc_owner_ip;
  611. // Set currency
  612. $my_currency = $this->selectCurrency($order->info['currency'], 'DP');
  613. // if CC is switch or solo, must be GBP
  614. if (in_array($cc_type, array('Switch', 'Solo', 'Maestro'))) {
  615. $my_currency = 'GBP';
  616. }
  617. // $order->info['total'] = zen_round($order->info['total'], 2);
  618. $order_amount = $this->calc_order_amount($order->info['total'], $my_currency);
  619. $display_order_amount = $this->calc_order_amount($order->info['total'], $my_currency, TRUE);
  620. // 3D-Secure
  621. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') {
  622. // determine the card type and validate that authentication was attempted and completed if applicable
  623. if (($_SESSION['3Dsecure_requires_lookup'] || $this->requiresLookup($_POST['wpp_cc_number']) == true)) { // authentication attempt required?
  624. // validate an acceptable lookup result
  625. if (isset($_SESSION['3Dsecure_enroll_lookup_attempted']) == false || strcasecmp($_SESSION['3Dsecure_enroll_lookup_attempted'], 'Y') != 0) {
  626. // lookup never attempted for required card, so need to redirect to payment-selection page
  627. $reason = 'Customer arrived on the order process page without attempting authentication lookup.';
  628. $error = MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED;
  629. $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
  630. $errorText = $reason ."\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  631. $errorText .= $this->code;
  632. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  633. zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
  634. }
  635. // if enrolled, validate an acceptable authentication result
  636. if (strcasecmp('Y', $_SESSION['3Dsecure_enrolled']) == 0) {
  637. if (isset($_SESSION['3Dsecure_authentication_attempted']) == false || strcasecmp($_SESSION['3Dsecure_authentication_attempted'], 'Y') != 0) {
  638. $reason = 'Customer arrived on the order process page without completing required authentication.';
  639. $error = MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED;
  640. $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
  641. $errorText = $reason ."\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  642. $errorText .= $this->code;
  643. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  644. // remove the lookup/auth attempted status
  645. unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
  646. unset($_SESSION['3Dsecure_authentication_attempted']);
  647. // authentication result was not acceptable, redirect
  648. zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
  649. }
  650. }
  651. }
  652. if ($cc_type != 'Solo') { // PayPal doesn't support 3d-secure on Solo cards
  653. if (isset($_SESSION['3Dsecure_enrolled'])) {
  654. $options['MPIVENDOR3DS'] = $_SESSION['3Dsecure_enrolled'];
  655. }
  656. if ($_SESSION['3Dsecure_auth_eci'] != '') {
  657. $options['ECI'] = $_SESSION['3Dsecure_auth_eci'];
  658. }
  659. if (isset($_SESSION['3Dsecure_auth_xid']) and strlen($_SESSION['3Dsecure_auth_xid']) > 0) {
  660. $options['XID'] = $_SESSION['3Dsecure_auth_xid'];
  661. $options['CAVV'] = $_SESSION['3Dsecure_auth_cavv'];
  662. $options['AUTHSTATUS3DS'] = $_SESSION['3Dsecure_auth_status'];
  663. }
  664. }
  665. }
  666. ///////////////////////////
  667. // Initialize the paypal caller object.
  668. $doPayPal = $this->paypal_init();
  669. $optionsAll = array_merge($options,
  670. array('STREET' => $order->billing['street_address'],
  671. 'ZIP' => $order->billing['postcode'],
  672. 'CITY' => $order->billing['city'],
  673. 'STATE' => $order->billing['state'],
  674. 'STREET2' => $order->billing['suburb'],
  675. 'COUNTRYCODE' => $order->billing['country']['iso_code_2'],
  676. 'EXPDATE' => $cc_expdate_month . $cc_expdate_year,
  677. 'EMAIL' => $order->customer['email_address'],
  678. 'PHONENUM' => $order->customer['telephone']));
  679. $optionsShip = array();
  680. if (isset($order->delivery) && $order->delivery['street_address'] != '') {
  681. $optionsShip= array('SHIPTONAME' => ($order->delivery['name'] == '' ? $order->delivery['firstname'] . ' ' . $order->delivery['lastname'] : $order->delivery['name']),
  682. 'SHIPTOSTREET' => $order->delivery['street_address'],
  683. 'SHIPTOSTREET2' => $order->delivery['suburb'],
  684. 'SHIPTOCITY' => $order->delivery['city'],
  685. 'SHIPTOZIP' => $order->delivery['postcode'],
  686. 'SHIPTOSTATE' => $order->delivery['state'],
  687. 'SHIPTOCOUNTRYCODE'=> $order->delivery['country']['iso_code_2']);
  688. }
  689. // if these optional parameters are blank, remove them from transaction
  690. if (isset($optionsShip['SHIPTOSTREET2']) && trim($optionsShip['SHIPTOSTREET2']) == '') unset($optionsShip['SHIPTOSTREET2']);
  691. if ($optionsAll['STREET2'] == '') unset($optionsAll['STREET2']);
  692. if (isset($optionsShip['SHIPTOPHONE']) && trim($optionsShip['SHIPTOPHONE']) == '') unset($optionsShip['SHIPTOPHONE']);
  693. // if State is not supplied, repeat the city so that it's not blank, otherwise PayPal croaks
  694. if ((!isset($optionsShip['SHIPTOSTATE']) || trim($optionsShip['SHIPTOSTATE']) == '') && isset($optionsShip['SHIPTOCITY'])) $optionsShip['SHIPTOSTATE'] = $optionsShip['SHIPTOCITY'];
  695. // Payment Transaction/Authorization Mode
  696. $optionsNVP['PAYMENTACTION'] = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Sale';
  697. if (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') $this->order_status = $this->order_pending_status;
  698. // if (in_array($cc_type, array('Switch', 'Solo'))) {
  699. // $optionsNVP['PAYMENTACTION'] = 'Authorization';
  700. // }
  701. $optionsAll['BUTTONSOURCE'] = $this->buttonSource;
  702. $optionsAll['CURRENCY'] = $my_currency;
  703. if (strlen($cc_owner_ip) > 7) {
  704. $optionsAll['IPADDRESS'] = $cc_owner_ip;
  705. }
  706. if ($cc_issuedate_month && $cc_issuedate_year) {
  707. $optionsAll['CARDSTART'] = $cc_issuedate_month . substr($cc_issuedate_year, -2);
  708. }
  709. if (isset($_POST['wpp_cc_issuenumber'])) $optionsAll['CARDISSUE'] = $_POST['wpp_cc_issuenumber'];
  710. // Add note to track that this was an API WPP transaction:
  711. $optionsAll['CUSTOM'] = 'DP-' . (int)$_SESSION['customer_id'] . '-' . time();
  712. // send the store name as transaction identifier, to help distinguish payments between multiple stores:
  713. $optionsAll['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)
  714. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' || (MODULE_PAYMENT_PAYPALWPP_PFVENDOR != '' && MODULE_PAYMENT_PAYPALWPP_PFPASSWORD != '')) { // Payflow params required
  715. if (isset($optionsAll['COUNTRYCODE'])) {
  716. $optionsAll['COUNTRY'] = $optionsAll['COUNTRYCODE'];
  717. unset($optionsAll['COUNTRYCODE']);
  718. }
  719. if (isset($optionsShip['SHIPTOCOUNTRYCODE'])) {
  720. $optionsShip['SHIPTOCOUNTRY'] = $optionsShip['SHIPTOCOUNTRYCODE'];
  721. unset($optionsShip['SHIPTOCOUNTRYCODE']);
  722. }
  723. if (isset($optionsShip['SHIPTOSTREET2'])) unset($optionsShip['SHIPTOSTREET2']);
  724. if (isset($optionsAll['STREET2'])) unset($optionsAll['STREET2']);
  725. }
  726. if (isset($optionsAll['DESC']) && $optionsAll['DESC'] == '') unset($optionsAll['DESC']);
  727. $this->zcLog('before_process - DP-4', 'options: ' . print_r(array_merge($optionsAll, $optionsNVP, $optionsShip), true) . "\n" . 'Rest of data: ' . "\n" . number_format($order_amount, 2) . ' ' . $cc_expdate_month . ' ' . substr($cc_expdate_year, -2) . ' ' . $cc_first_name . ' ' . $cc_last_name . ' ' . $cc_type);
  728. if (!isset($optionsAll['AMT'])) $optionsAll['AMT'] = number_format($order_amount, 2, '.', '');
  729. $response = $doPayPal->DoDirectPayment($cc_number,
  730. $cc_checkcode,
  731. $cc_expdate_month . substr($cc_expdate_year, -2),
  732. $cc_first_name, $cc_last_name,
  733. $cc_type,
  734. $optionsAll, array_merge($optionsNVP, $optionsShip));
  735. $this->zcLog('before_process - DP-5', 'resultset:' . "\n" . urldecode(print_r($response, true)));
  736. // CHECK RESPONSE
  737. $error = $this->_errorHandler($response, 'DoDirectPayment');
  738. if ($this->fmfResponse != '') {
  739. $this->order_status = $this->order_pending_status;
  740. }
  741. $this->feeamt = '';
  742. $this->taxamt = '';
  743. $this->pendingreason = '';
  744. $this->reasoncode = '';
  745. $this->numitems = sizeof($order->products);
  746. $this->responsedata = $response;
  747. if ($response['PNREF']) {
  748. // PNREF only comes from payflow mode
  749. $this->payment_type = MODULE_PAYMENT_PAYPALDP_PF_TEXT_TYPE;
  750. $this->transaction_id = $response['PNREF'];
  751. $this->payment_status = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Completed';
  752. $this->avs = 'AVSADDR: ' . $response['AVSADDR'] . ', AVSZIP: ' . $response['AVSZIP'] . ', IAVS: ' . $response['IAVS'];
  753. $this->cvv2 = $response['CVV2MATCH'];
  754. $this->amt = $display_order_amount . ' ' . $my_currency;
  755. $this->payment_time = date('Y-m-d h:i:s');
  756. $this->responsedata['CURRENCYCODE'] = $my_currency;
  757. $this->responsedata['EXCHANGERATE'] = $order->info['currency_value'];
  758. $this->auth_code = $this->response['AUTHCODE'];
  759. } else {
  760. // here we're in NVP mode
  761. $this->transaction_id = $response['TRANSACTIONID'];
  762. $this->payment_type = MODULE_PAYMENT_PAYPALDP_DP_TEXT_TYPE;
  763. $this->payment_status = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Completed';
  764. $this->pendingreason = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'authorization' : '';
  765. $this->avs = $response['AVSCODE'];
  766. $this->cvv2 = $response['CVV2MATCH'];
  767. $this->correlationid = $response['CORRELATIONID'];
  768. $this->payment_time = urldecode($response['TIMESTAMP']);
  769. $this->amt = urldecode($response['AMT'] . ' ' . $response['CURRENCYCODE']);
  770. $this->auth_code = (isset($this->response['AUTHCODE'])) ? $this->response['AUTHCODE'] : $this->response['TOKEN'];
  771. $this->transactiontype = 'cart';
  772. }
  773. }
  774. /**
  775. * When the order returns from the processor, this stores the results in order-status-history and logs data for subsequent use
  776. */
  777. function after_process() {
  778. global $insert_id, $db, $order;
  779. // FMF
  780. if ($this->fmfResponse != '') {
  781. $detailedMessage = $insert_id . "\n" . $this->fmfResponse . "\n" . MODULES_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_INTRO . "\n" . print_r($this->fmfErrors, TRUE);
  782. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULES_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_SUBJECT . ' (' . $insert_id . ')', $detailedMessage, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($detailedMessage)), 'paymentalert');
  783. }
  784. // add a new OSH record for this order's PP details
  785. $commentString = "Transaction ID: :transID: " .
  786. (isset($this->responsedata['PPREF']) ? "\nPPRef: " . $this->responsedata['PPREF'] : "") .
  787. (isset($this->responsedata['AUTHCODE'])? "\nAuthCode: " . $this->responsedata['AUTHCODE'] : "") .
  788. "\nPayment Type: :pmtType: " .
  789. ($this->payment_time != '' ? "\nTimestamp: :pmtTime: " : "") .
  790. "\nPayment Status: :pmtStatus: " .
  791. (isset($this->responsedata['auth_exp']) ? "\nAuth-Exp: " . $this->responsedata['auth_exp'] : "") .
  792. ($this->avs != 'N/A' ? "\nAVS Code: ".$this->avs."\nCVV2 Code: ".$this->cvv2 : '') .
  793. (trim($this->amt) != '' ? "\nAmount: :orderAmt: " : "");
  794. $commentString = $db->bindVars($commentString, ':transID:', $this->transaction_id, 'noquotestring');
  795. $commentString = $db->bindVars($commentString, ':pmtType:', $this->payment_type, 'noquotestring');
  796. $commentString = $db->bindVars($commentString, ':pmtTime:', $this->payment_time, 'noquotestring');
  797. $commentString = $db->bindVars($commentString, ':pmtStatus:', $this->payment_status, 'noquotestring');
  798. $commentString = $db->bindVars($commentString, ':orderAmt:', $this->amt, 'noquotestring');
  799. $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=>$insert_id, 'type'=>'integer'),
  800. array('fieldName'=>'orders_status_id', 'value'=>$order->info['order_status'], 'type'=>'integer'),
  801. array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
  802. array('fieldName'=>'customer_notified', 'value'=>0, 'type'=>'integer'),
  803. array('fieldName'=>'comments', 'value'=>$commentString, 'type'=>'string'));
  804. $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  805. // 3D-Secure
  806. if ($this->requiresLookup($order->info['cc_type']) == true) {
  807. // CardinalCommerce Liability Protection Status
  808. // Inserts 'PROTECTED' or 'NOT PROTECTED' status, ECI, CAVV values in the order status history comments
  809. $auth_proc_status = $this->determine3DSecureProtection($order->info['cc_type'], $_SESSION['3Dsecure_auth_eci']);
  810. $commentString = "3D-Secure: " . $auth_proc_status . "\n" . 'ECI Value = ' . $_SESSION['3Dsecure_auth_eci'] . "\n" . 'CAVV Value = ' . $_SESSION['3Dsecure_auth_cavv'];
  811. $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=> $insert_id, 'type'=>'integer'),
  812. array('fieldName'=>'orders_status_id', 'value'=> $order->info['order_status'], 'type'=>'integer'),
  813. array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
  814. array('fieldName'=>'customer_notified', 'value'=> -1, 'type'=>'integer'),
  815. array('fieldName'=>'comments', 'value'=> $commentString, 'type'=>'string'));
  816. $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  817. }
  818. // store the PayPal order meta data -- used for later matching and back-end processing activities
  819. $paypal_order = array('order_id' => $insert_id,
  820. 'txn_type' => $this->transactiontype,
  821. 'module_name' => $this->code,
  822. 'module_mode' => MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY,
  823. 'reason_code' => $this->reasoncode,
  824. 'payment_type' => $this->payment_type,
  825. 'payment_status' => $this->payment_status,
  826. 'pending_reason' => $this->pendingreason,
  827. 'invoice' => urldecode($_SESSION['paypal_ec_token'] . $this->responsedata['PPREF']),
  828. 'first_name' => $_SESSION['paypal_ec_payer_info']['payer_firstname'],
  829. 'last_name' => $_SESSION['paypal_ec_payer_info']['payer_lastname'],
  830. 'payer_business_name' => $_SESSION['paypal_ec_payer_info']['payer_business'],
  831. 'address_name' => $_SESSION['paypal_ec_payer_info']['ship_name'],
  832. 'address_street' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
  833. 'address_city' => $_SESSION['paypal_ec_payer_info']['ship_city'],
  834. 'address_state' => $_SESSION['paypal_ec_payer_info']['ship_state'],
  835. 'address_zip' => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
  836. 'address_country' => $_SESSION['paypal_ec_payer_info']['ship_country'],
  837. 'address_status' => $_SESSION['paypal_ec_payer_info']['ship_address_status'],
  838. 'payer_email' => $_SESSION['paypal_ec_payer_info']['payer_email'],
  839. 'payer_id' => $_SESSION['paypal_ec_payer_id'],
  840. 'payer_status' => $_SESSION['paypal_ec_payer_info']['payer_status'],
  841. 'payment_date' => trim(preg_replace('/[^0-9-:]/', ' ', $this->payment_time)),
  842. 'business' => '',
  843. 'receiver_email' => (MODULE_PAYMENT_PAYPALWPP_PFVENDOR != '' ? MODULE_PAYMENT_PAYPALWPP_PFVENDOR : str_replace('_api1', '', MODULE_PAYMENT_PAYPALWPP_APIUSERNAME)),
  844. 'receiver_id' => '',
  845. 'txn_id' => $this->transaction_id,
  846. 'parent_txn_id' => '',
  847. 'num_cart_items' => (float)$this->numitems,
  848. 'mc_gross' => (float)$this->amt,
  849. 'mc_fee' => (float)urldecode($this->feeamt),
  850. 'mc_currency' => $this->responsedata['CURRENCYCODE'],
  851. 'settle_amount' => (float)urldecode($this->responsedata['SETTLEAMT']),
  852. 'settle_currency' => $this->responsedata['CURRENCYCODE'],
  853. 'exchange_rate' => (urldecode($this->responsedata['EXCHANGERATE']) > 0 ? urldecode($this->responsedata['EXCHANGERATE']) : 1.0),
  854. 'notify_version' => '0',
  855. 'verify_sign' =>'',
  856. 'date_added' => 'now()',
  857. 'memo' => (sizeof($this->fmfErrors) > 0 ? 'FMF Details ' . print_r($this->fmfErrors, TRUE) : '{Record generated by payment module}'),
  858. );
  859. zen_db_perform(TABLE_PAYPAL, $paypal_order);
  860. // Unregister the paypal session variables, making it necessary to start again for another purchase
  861. unset($_SESSION['paypal_ec_temp']);
  862. unset($_SESSION['paypal_ec_token']);
  863. unset($_SESSION['paypal_ec_payer_id']);
  864. unset($_SESSION['paypal_ec_payer_info']);
  865. unset($_SESSION['paypal_ec_final']);
  866. unset($_SESSION['paypal_ec_markflow']);
  867. $this->clear_3DSecure_session_vars(TRUE);
  868. }
  869. /**
  870. * Build admin-page components
  871. *
  872. * @param int $zf_order_id
  873. * @return string
  874. */
  875. function admin_notification($zf_order_id) {
  876. if (!defined('MODULE_PAYMENT_PAYPALDP_STATUS')) return '';
  877. global $db;
  878. $module = $this->code;
  879. $output = '';
  880. $response = $this->_GetTransactionDetails($zf_order_id);
  881. //$response = $this->_TransactionSearch('2006-12-01T00:00:00Z', $zf_order_id);
  882. $sql = "SELECT * from " . TABLE_PAYPAL . " WHERE order_id = :orderID
  883. AND parent_txn_id = '' AND order_id > 0
  884. ORDER BY paypal_ipn_id DESC LIMIT 1";
  885. $sql = $db->bindVars($sql, ':orderID', $zf_order_id, 'integer');
  886. $ipn = $db->Execute($sql);
  887. if ($ipn->RecordCount() == 0) $ipn->fields = array();
  888. 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');
  889. return $output;
  890. }
  891. /**
  892. * Used to read details of an existing transaction. FOR FUTURE USE.
  893. */
  894. function _GetTransactionDetails($oID) {
  895. if ($oID == '' || $oID < 1) return FALSE;
  896. global $db, $messageStack, $doPayPal;
  897. $doPayPal = $this->paypal_init();
  898. // look up history on this order from PayPal table
  899. $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 LIMIT 2";
  900. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  901. $zc_ppHist = $db->Execute($sql);
  902. if ($zc_ppHist->RecordCount() == 0) return false;
  903. $txnID = $zc_ppHist->fields['txn_id'];
  904. if ($txnID == '' || $txnID === 0) return FALSE;
  905. /**
  906. * Read data from PayPal
  907. */
  908. $response = $doPayPal->GetTransactionDetails($txnID);
  909. if (isset($response['RESULT']) && $response['RESULT'] == '7' && $zc_ppHist->RecordCount() > 1) {
  910. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID and txn_id != :condition: order by last_modified ASC, date_added ASC, paypal_ipn_id ASC LIMIT 1";
  911. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  912. $sql = $db->bindVars($sql, ':condition:', $zc_ppHist->fields['txn_id'], 'integer');
  913. $zc_ppHist = $db->Execute($sql);
  914. if ($zc_ppHist->RecordCount() == 0) return false;
  915. $txnID = $zc_ppHist->fields['txn_id'];
  916. if ($txnID == '' || $txnID === 0) return FALSE;
  917. $response = $doPayPal->GetTransactionDetails($txnID);
  918. }
  919. $error = $this->_errorHandler($response, 'GetTransactionDetails', 10007);
  920. if ($error === true) {
  921. return false;
  922. } else {
  923. return $response;
  924. }
  925. }
  926. /**
  927. * Used to read details of existing transactions. FOR FUTURE USE.
  928. */
  929. function _TransactionSearch($startDate = '', $oID = '', $criteria = '') {
  930. global $db, $messageStack, $doPayPal;
  931. $doPayPal = $this->paypal_init();
  932. // look up history on this order from PayPal table
  933. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  934. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  935. $zc_ppHist = $db->Execute($sql);
  936. if ($zc_ppHist->RecordCount() == 0) return false;
  937. $txnID = $zc_ppHist->fields['txn_id'];
  938. $startDate = $zc_ppHist->fields['payment_date'];
  939. $timeval = time();
  940. if ($startDate == '') $startDate = date('Y-m-d', $timeval) . 'T' . date('h:i:s', $timeval) . 'Z';
  941. /**
  942. * Read data from PayPal
  943. */
  944. $response = $doPayPal->TransactionSearch($startDate, $txnID, $email, $criteria);
  945. $error = $this->_errorHandler($response, 'TransactionSearch');
  946. if ($error === false) {
  947. return false;
  948. } else {
  949. return $response;
  950. }
  951. }
  952. /**
  953. * Evaluate installation status of this module. Returns true if the status key is found.
  954. */
  955. function check() {
  956. global $db;
  957. if (!isset($this->_check)) {
  958. $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PAYPALDP_STATUS'");
  959. $this->_check = !$check_query->EOF;
  960. }
  961. return $this->_check;
  962. }
  963. /**
  964. * Installs all the configuration keys for this module
  965. */
  966. function install() {
  967. global $db, $messageStack;
  968. if (defined('MODULE_PAYMENT_PAYPALDP_STATUS')) {
  969. $messageStack->add_session('Website Payments Pro module already installed.', 'error');
  970. zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypaldp', 'NONSSL'));
  971. return 'failed';
  972. }
  973. // cannot install DP if EC not already enabled:
  974. if (!defined('MODULE_PAYMENT_PAYPALWPP_STATUS') || MODULE_PAYMENT_PAYPALWPP_STATUS != 'True') {
  975. $messageStack->add_session('<strong>Sorry, you must install and configure PayPal Express Checkout first.</strong> PayPal Website Payments Pro requires that you offer Express Checkout to your customers.<br /><a href="' . zen_href_link('modules.php?set=payment&module=paypalwpp', '', 'NONSSL') . '">Click here to set up Express Checkout.</a>' , 'error');
  976. zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypaldp', 'NONSSL'));
  977. return 'failed';
  978. }
  979. $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_PAYPALDP_STATUS', 'True', 'Do you want to enable this payment module?', '6', '25', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
  980. $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_PAYPALDP_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())");
  981. $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_PAYPALDP_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '25', now())");
  982. $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_PAYPALDP_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())");
  983. $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_PAYPALDP_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())");
  984. $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_PAYPALDP_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())");
  985. $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_PAYPALDP_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())");
  986. $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_PAYPALDP_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())");
  987. $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_PAYPALDP_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\'), ', now())");
  988. $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_PAYPALDP_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())");
  989. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Merchant Country', 'MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY', 'USA', 'Which country is your PayPal Account registered to? <br /><u>Choices:</u><br /><font color=green>You will need to supply <strong>API Settings</strong> in the Express Checkout module.</font><br /><strong>USA and Canada merchants</strong> need PayPal API credentials and a PayPal Payments Pro account.<br /><strong>UK merchants</strong> need to supply <strong>PAYFLOW settings</strong> (and have a Payflow account)', '6', '25', 'zen_cfg_select_option(array(\'USA\', \'UK\', \'Canada\'), ', now())");
  990. $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_PAYPALDP_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())");
  991. // 3D-Secure
  992. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cardinal Processor ID', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR', '134-01', 'The processor ID for the Cardinal Centinel service. ', '6', '25', now())");
  993. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cardinal Merchant ID', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT', 'enter value', 'The merchant ID for the Cardinal Centinel service. ', '6', '25', now())");
  994. $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 ('Cardinal Transaction Password', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD', '', 'Enter your Cardinal Transaction Password from your Cardinal Merchant Admin console. This is used to secure and verify that the transaction originated from your store legitimately.', '6', '25', now(), 'zen_cfg_password_input(', 'zen_cfg_password_display')");
  995. $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Only Accept Chargeback-Protected Orders via Cardinal?', 'MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ', 'No', 'Only proceed with authorization when the Cardinal authentication result provides chargeback protection? ', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
  996. $this->notify('NOTIFY_PAYMENT_PAYPALDP_INSTALLED');
  997. }
  998. function keys() {
  999. $keys_list = array('MODULE_PAYMENT_PAYPALDP_STATUS', 'MODULE_PAYMENT_PAYPALDP_SORT_ORDER', 'MODULE_PAYMENT_PAYPALDP_ZONE', 'MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID', 'MODULE_PAYMENT_PAYPALDP_ORDER_PENDING_STATUS_ID', 'MODULE_PAYMENT_PAYPALDP_REFUNDED_STATUS_ID', 'MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE', 'MODULE_PAYMENT_PAYPALDP_CURRENCY', 'MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY', 'MODULE_PAYMENT_PAYPALDP_EC_RETURN_FMF_DETAILS', 'MODULE_PAYMENT_PAYPALDP_SERVER', 'MODULE_PAYMENT_PAYPALDP_DEBUGGING');
  1000. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') {
  1001. $keys_list = array_merge($keys_list, array('MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR','MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT','MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD','MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ'));
  1002. }
  1003. return $keys_list;
  1004. }
  1005. /**
  1006. * De-install this module
  1007. */
  1008. function remove() {
  1009. global $db;
  1010. $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key LIKE 'MODULE\_PAYMENT\_PAYPALDP\_%'");
  1011. $this->notify('NOTIFY_PAYMENT_PAYPALDP_UNINSTALLED');
  1012. }
  1013. /**
  1014. * Check settings and conditions to determine whether we are in an Express Checkout phase or not
  1015. */
  1016. function in_special_checkout() {
  1017. if ((defined('MODULE_PAYMENT_PAYPALDP_STATUS') && MODULE_PAYMENT_PAYPALDP_STATUS == 'True') &&
  1018. !empty($_SESSION['paypal_ec_token']) &&
  1019. !empty($_SESSION['paypal_ec_payer_id']) &&
  1020. !empty($_SESSION['paypal_ec_payer_info'])) {
  1021. return true;
  1022. }
  1023. }
  1024. /**
  1025. * Debug Logging support
  1026. */
  1027. function zcLog($stage, $message) {
  1028. static $tokenHash;
  1029. if ($tokenHash == '') $tokenHash = '_' . zen_create_random_value(4);
  1030. if (MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log and Email' || MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log File') {
  1031. $token = (isset($_SESSION['paypal_ec_token'])) ? $_SESSION['paypal_ec_token'] : preg_replace('/[^0-9.A-Z\-]/', '', $_GET['token']);
  1032. $token = ($token == '') ? date('m-d-Y-H-i') : $token; // or time()
  1033. $token .= $tokenHash;
  1034. $file = $this->_logDir . '/' . $this->code . '_Paypal_Action_' . $token . '.log';
  1035. if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $file = $this->_logDir . '/' . $this->code . '_Paypal_Debug_' . $token . '.log';
  1036. $fp = @fopen($file, 'a');
  1037. @fwrite($fp, date('M-d-Y H:i:s') . ' (' . time() . ')' . "\n" . $stage . "\n" . $message . "\n=================================\n\n");
  1038. @fclose($fp);
  1039. }
  1040. $this->_doDebug($stage, $message, false);
  1041. }
  1042. /**
  1043. * Debug Emailing support
  1044. */
  1045. function _doDebug($subject = 'PayPal debug data', $data, $useSession = true) {
  1046. if (MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log and Email') {
  1047. $data = urldecode($data) . "\n\n";
  1048. if ($useSession) $data .= "\nSession data: " . print_r($_SESSION, true);
  1049. 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');
  1050. }
  1051. }
  1052. /**
  1053. * Initialize the PayPal/PayflowPro object for communication to the processing gateways
  1054. */
  1055. function paypal_init() {
  1056. $nvp = (MODULE_PAYMENT_PAYPALWPP_APIPASSWORD != '' && MODULE_PAYMENT_PAYPALWPP_APISIGNATURE != '') ? true : false;
  1057. $ec = ($nvp && $_GET['type'] == 'ec') ? true : false;
  1058. if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && !$ec) {
  1059. $doPayPal = new paypal_curl(array('mode' => 'payflow',
  1060. 'user' => trim(MODULE_PAYMENT_PAYPALWPP_PFUSER),
  1061. 'vendor' => trim(MODULE_PAYMENT_PAYPALWPP_PFVENDOR),
  1062. 'partner'=> trim(MODULE_PAYMENT_PAYPALWPP_PFPARTNER),
  1063. 'pwd' => trim(MODULE_PAYMENT_PAYPALWPP_PFPASSWORD),
  1064. 'server' => MODULE_PAYMENT_PAYPALDP_SERVER));
  1065. $doPayPal->_endpoints = array('live' => 'https://payflowpro.paypal.com/transaction',
  1066. 'sandbox' => 'https://pilot-payflowpro.paypal.com/transaction');
  1067. } else {
  1068. $doPayPal = new paypal_curl(array('mode' => 'nvp',
  1069. 'user' => trim(MODULE_PAYMENT_PAYPALWPP_APIUSERNAME),
  1070. 'pwd' => trim(MODULE_PAYMENT_PAYPALWPP_APIPASSWORD),
  1071. 'signature' => trim(MODULE_PAYMENT_PAYPALWPP_APISIGNATURE),
  1072. 'version' => '61.0',
  1073. 'server' => MODULE_PAYMENT_PAYPALDP_SERVER));
  1074. $doPayPal->_endpoints = array('live' => 'https://api-3t.paypal.com/nvp',
  1075. 'sandbox' => 'https://api-3t.sandbox.paypal.com/nvp');
  1076. }
  1077. // set logging options
  1078. $doPayPal->_logDir = $this->_logDir;
  1079. $doPayPal->_logLevel = $this->_logLevel;
  1080. // set proxy options if configured
  1081. if (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '') {
  1082. $proxy_tunnel_flag = (defined('CURL_PROXY_TUNNEL_FLAG') && strtoupper(CURL_PROXY_TUNNEL_FLAG) == 'FALSE') ? false : true;
  1083. $doPayPal->setCurlOption(CURLOPT_HTTPPROXYTUNNEL, $proxy_tunnel_flag);
  1084. $doPayPal->setCurlOption(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  1085. $doPayPal->setCurlOption(CURLOPT_PROXY, CURL_PROXY_SERVER_DETAILS);
  1086. }
  1087. // transaction processing mode
  1088. $doPayPal->_trxtype = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'A' : 'S';
  1089. return $doPayPal;
  1090. }
  1091. /**
  1092. * Determine which PayPal URL to direct the customer's browser to when needed
  1093. */
  1094. function getPayPalLoginServer() {
  1095. if (MODULE_PAYMENT_PAYPALDP_SERVER == 'live') {
  1096. // live url
  1097. $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
  1098. } else {
  1099. // sandbox url
  1100. $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
  1101. }
  1102. return $paypal_url;
  1103. }
  1104. /**
  1105. * Used to submit a refund for a given transaction. FOR FUTURE USE.
  1106. */
  1107. function _doRefund($oID, $amount = 'Full', $note = '') {
  1108. global $db, $doPayPal, $messageStack;
  1109. $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_REFUNDED_STATUS_ID;
  1110. $orig_order_amount = 0;
  1111. $doPayPal = $this->paypal_init();
  1112. $proceedToRefund = false;
  1113. $refundNote = strip_tags(zen_db_input($_POST['refnote']));
  1114. if (isset($_POST['fullrefund']) && $_POST['fullrefund'] == MODULE_PAYMENT_PAYPAL_ENTRY_REFUND_BUTTON_TEXT_FULL) {
  1115. $refundAmt = 'Full';
  1116. if (isset($_POST['reffullconfirm']) && $_POST['reffullconfirm'] == 'on') {
  1117. $proceedToRefund = true;
  1118. } else {
  1119. $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_REFUND_FULL_CONFIRM_ERROR, 'error');
  1120. }
  1121. }
  1122. if (isset($_POST['partialrefund']) && $_POST['partialrefund'] == MODULE_PAYMENT_PAYPAL_ENTRY_REFUND_BUTTON_TEXT_PARTIAL) {
  1123. $refundAmt = (float)$_POST['refamt'];
  1124. $proceedToRefund = true;
  1125. if ($refundAmt == 0) {
  1126. $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_INVALID_REFUND_AMOUNT, 'error');
  1127. $proceedToRefund = false;
  1128. }
  1129. }
  1130. // look up history on this order from PayPal table
  1131. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  1132. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  1133. $zc_ppHist = $db->Execute($sql);
  1134. if ($zc_ppHist->RecordCount() == 0) return false;
  1135. $txnID = $zc_ppHist->fields['txn_id'];
  1136. $curCode = $zc_ppHist->fields['mc_currency'];
  1137. $PFamt = $zc_ppHist->fields['mc_gross'];
  1138. if ($doPayPal->_mode == 'payflow' && $refundAmt == 'Full') $refundAmt = $PFamt;
  1139. /**
  1140. * Submit refund request to PayPal
  1141. */
  1142. if ($proceedToRefund) {
  1143. $response = $doPayPal->RefundTransaction($oID, $txnID, $refundAmt, $refundNote, $curCode);
  1144. $error = $this->_errorHandler($response, 'DoRefund');
  1145. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  1146. if (!$error) {
  1147. if (!isset($response['GROSSREFUNDAMT'])) $response['GROSSREFUNDAMT'] = $refundAmt;
  1148. // Success, so save the results
  1149. $sql_data_array = array('orders_id' => $oID,
  1150. 'orders_status_id' => (int)$new_order_status,
  1151. 'date_added' => 'now()',
  1152. '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,
  1153. 'customer_notified' => 0
  1154. );
  1155. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  1156. $db->Execute("update " . TABLE_ORDERS . "
  1157. set orders_status = '" . (int)$new_order_status . "'
  1158. where orders_id = '" . (int)$oID . "'");
  1159. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_REFUND_INITIATED, urldecode($response['GROSSREFUNDAMT']), urldecode($response['REFUNDTRANSACTIONID']). $response['PNREF']), 'success');
  1160. return true;
  1161. }
  1162. }
  1163. }
  1164. /**
  1165. * Used to capture part or all of a given previously-authorized transaction. FOR FUTURE USE.
  1166. * (alt value for $captureType = 'NotComplete')
  1167. */
  1168. function _doCapt($oID, $captureType = 'Complete', $amt = 0, $currency = 'USD', $note = '') {
  1169. global $db, $doPayPal, $messageStack;
  1170. $doPayPal = $this->paypal_init();
  1171. //@TODO: Read current order status and determine best status to set this to
  1172. $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID;
  1173. $orig_order_amount = 0;
  1174. $doPayPal = $this->paypal_init();
  1175. $proceedToCapture = false;
  1176. $captureNote = strip_tags(zen_db_input($_POST['captnote']));
  1177. if (isset($_POST['captfullconfirm']) && $_POST['captfullconfirm'] == 'on') {
  1178. $proceedToCapture = true;
  1179. } else {
  1180. $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_CAPTURE_FULL_CONFIRM_ERROR, 'error');
  1181. }
  1182. if (isset($_POST['captfinal']) && $_POST['captfinal'] == 'on') {
  1183. $captureType = 'Complete';
  1184. } else {
  1185. $captureType = 'NotComplete';
  1186. }
  1187. if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_PAYPAL_ENTRY_CAPTURE_BUTTON_TEXT_FULL) {
  1188. $captureAmt = (float)$_POST['captamt'];
  1189. if ($captureAmt == 0) {
  1190. $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
  1191. $proceedToCapture = false;
  1192. }
  1193. }
  1194. // look up history on this order from PayPal table
  1195. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  1196. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  1197. $zc_ppHist = $db->Execute($sql);
  1198. if ($zc_ppHist->RecordCount() == 0) return false;
  1199. $txnID = $zc_ppHist->fields['txn_id'];
  1200. /**
  1201. * Submit capture request to PayPal
  1202. */
  1203. if ($proceedToCapture) {
  1204. $response = $doPayPal->DoCapture($txnID, $captureAmt, $currency, $captureType, '', $captureNote);
  1205. $error = $this->_errorHandler($response, 'DoCapture');
  1206. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  1207. if (!$error) {
  1208. if (isset($response['PNREF'])) {
  1209. if (!isset($response['AMT'])) $response['AMT'] = $captureAmt;
  1210. if (!isset($response['ORDERTIME'])) $response['ORDERTIME'] = date("M-d-Y h:i:s");
  1211. }
  1212. // Success, so save the results
  1213. $sql_data_array = array('orders_id' => (int)$oID,
  1214. 'orders_status_id' => (int)$new_order_status,
  1215. 'date_added' => 'now()',
  1216. '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: ' . $response['AUTHCODE']) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $captureNote,
  1217. 'customer_notified' => 0
  1218. );
  1219. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  1220. $db->Execute("update " . TABLE_ORDERS . "
  1221. set orders_status = '" . (int)$new_order_status . "'
  1222. where orders_id = '" . (int)$oID . "'");
  1223. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_CAPT_INITIATED, urldecode($response['AMT']), urldecode($response['RECEIPTID'] . $response['AUTHCODE']). $response['PNREF']), 'success');
  1224. return true;
  1225. }
  1226. }
  1227. }
  1228. /**
  1229. * Used to void a given previously-authorized transaction. FOR FUTURE USE.
  1230. */
  1231. function _doVoid($oID, $note = '') {
  1232. global $db, $doPayPal, $messageStack;
  1233. $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_REFUNDED_STATUS_ID;
  1234. $doPayPal = $this->paypal_init();
  1235. $voidNote = strip_tags(zen_db_input($_POST['voidnote']));
  1236. $voidAuthID = trim(strip_tags(zen_db_input($_POST['voidauthid'])));
  1237. if (isset($_POST['ordervoid']) && $_POST['ordervoid'] == MODULE_PAYMENT_PAYPAL_ENTRY_VOID_BUTTON_TEXT_FULL) {
  1238. if (isset($_POST['voidconfirm']) && $_POST['voidconfirm'] == 'on') {
  1239. $proceedToVoid = true;
  1240. } else {
  1241. $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_VOID_CONFIRM_ERROR, 'error');
  1242. }
  1243. }
  1244. // look up history on this order from PayPal table
  1245. $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID AND parent_txn_id = '' ";
  1246. $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
  1247. $sql = $db->bindVars($sql, ':transID', $voidAuthID, 'string');
  1248. $zc_ppHist = $db->Execute($sql);
  1249. if ($zc_ppHist->RecordCount() == 0) return false;
  1250. $txnID = $zc_ppHist->fields['txn_id'];
  1251. /**
  1252. * Submit void request to PayPal
  1253. */
  1254. if ($proceedToVoid) {
  1255. $response = $doPayPal->DoVoid($voidAuthID, $voidNote);
  1256. $error = $this->_errorHandler($response, 'DoVoid');
  1257. $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
  1258. if (!$error) {
  1259. // Success, so save the results
  1260. $sql_data_array = array('orders_id' => (int)$oID,
  1261. 'orders_status_id' => (int)$new_order_status,
  1262. 'date_added' => 'now()',
  1263. 'comments' => 'VOIDED. Trans ID: ' . urldecode($response['AUTHORIZATIONID']). $response['PNREF'] . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $voidNote,
  1264. 'customer_notified' => 0
  1265. );
  1266. zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  1267. $db->Execute("update " . TABLE_ORDERS . "
  1268. set orders_status = '" . (int)$new_order_status . "'
  1269. where orders_id = '" . (int)$oID . "'");
  1270. $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_VOID_INITIATED, urldecode($response['AUTHORIZATIONID']) . $response['PNREF']), 'success');
  1271. return true;
  1272. }
  1273. }
  1274. }
  1275. /**
  1276. * Set the currency code -- use defaults if active currency is not a currency accepted by PayPal
  1277. */
  1278. function selectCurrency($val = '') {
  1279. $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', 'TKD');
  1280. $dp_currencies = array('CAD', 'EUR', 'GBP', 'JPY', 'USD', 'AUD', 'CHF', 'CZK', 'DKK', 'HKD', 'HUF', 'NOK', 'NZD', 'PLN', 'SEK', 'SGD');
  1281. $dpus_currencies = array('CAD', 'EUR', 'GBP', 'JPY', 'USD', 'AUD');
  1282. // in USA, only 6 currencies are supported. But UK and Canada support 16 currencies (as of Jan 2011):
  1283. $paypalSupportedCurrencies = (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' || MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'Canada') ? $dp_currencies : $dpus_currencies;
  1284. $my_currency = substr(MODULE_PAYMENT_PAYPALDP_CURRENCY, 5);
  1285. if (MODULE_PAYMENT_PAYPALDP_CURRENCY == 'Selected Currency') {
  1286. $my_currency = ($val == '') ? $_SESSION['currency'] : $val;
  1287. }
  1288. if (!in_array($my_currency, $paypalSupportedCurrencies)) {
  1289. $my_currency = (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') ? 'GBP' : (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'Canada' ? 'CAD' : 'USD');
  1290. }
  1291. return $my_currency;
  1292. }
  1293. /**
  1294. * Calculate the amount based on acceptable currencies
  1295. */
  1296. function calc_order_amount($amount, $paypalCurrency, $applyFormatting = false) {
  1297. global $currencies;
  1298. $amount = ($amount * $currencies->get_value($paypalCurrency));
  1299. if ($paypalCurrency == 'JPY' || (int)$currencies->get_decimal_places($paypalCurrency) == 0) {
  1300. $amount = (int)$amount;
  1301. $applyFormatting = FALSE;
  1302. }
  1303. return ($applyFormatting ? number_format($amount, $currencies->get_decimal_places($paypalCurrency)) : $amount);
  1304. }
  1305. /**
  1306. * Set the state field depending on what PayPal requires for that country.
  1307. */
  1308. function setStateAndCountry(&$info) {
  1309. global $db, $messageStack;
  1310. switch ($info['country']['iso_code_2']) {
  1311. case 'AU':
  1312. case 'US':
  1313. case 'CA':
  1314. // Paypal only accepts two character state/province codes for some countries.
  1315. if (strlen($info['state']) > 2) {
  1316. $sql = "SELECT zone_code FROM " . TABLE_ZONES . " WHERE zone_name = :zoneName";
  1317. $sql = $db->bindVars($sql, ':zoneName', $info['state'], 'string');
  1318. $state = $db->Execute($sql);
  1319. if (!$state->EOF) {
  1320. $info['state'] = $state->fields['zone_code'];
  1321. } else {
  1322. $messageStack->add_session('header', MODULE_PAYMENT_PAYPALDP_TEXT_STATE_ERROR, 'error');
  1323. }
  1324. }
  1325. break;
  1326. case 'AT':
  1327. case 'BE':
  1328. case 'FR':
  1329. case 'DE':
  1330. case 'CH':
  1331. $info['state'] = '';
  1332. break;
  1333. case 'GB':
  1334. break;
  1335. default:
  1336. $info['state'] = '';
  1337. }
  1338. }
  1339. /**
  1340. * Prepare subtotal and line-item detail content to send to PayPal
  1341. */
  1342. function getLineItemDetails($restrictedCurrency) {
  1343. global $order, $currencies, $order_totals, $order_total_modules;
  1344. // if not default currency, do not send subtotals or line-item details
  1345. if (DEFAULT_CURRENCY != $order->info['currency'] || $restrictedCurrency != DEFAULT_CURRENCY) {
  1346. $this->zcLog('getLineItemDetails 1', 'Not using default currency. Thus, no line-item details can be submitted.');
  1347. return array();
  1348. }
  1349. if ($currencies->currencies[$_SESSION['currency']]['value'] != 1 || $currencies->currencies[$order->info['currency']]['value'] != 1) {
  1350. $this->zcLog('getLineItemDetails 2', 'currency val not equal to 1.0000 - cannot proceed without coping with currency conversions. Aborting line-item details.');
  1351. return array();
  1352. }
  1353. $optionsST = array();
  1354. $optionsLI = array();
  1355. $optionsNB = array();
  1356. $numberOfLineItemsProcessed = 0;
  1357. $creditsApplied = 0;
  1358. $surcharges = 0;
  1359. $sumOfLineItems = 0;
  1360. $sumOfLineTax = 0;
  1361. $optionsST['AMT'] = 0;
  1362. $optionsST['ITEMAMT'] = 0;
  1363. $optionsST['TAXAMT'] = 0;
  1364. $optionsST['SHIPPINGAMT'] = 0;
  1365. $optionsST['SHIPDISCAMT'] = 0;
  1366. $optionsST['HANDLINGAMT'] = 0;
  1367. $optionsST['INSURANCEAMT'] = 0;
  1368. $flagSubtotalsUnknownYet = true;
  1369. $subTotalLI = 0;
  1370. $subTotalTax = 0;
  1371. $subTotalShipping = 0;
  1372. $subtotalPRE = array('no data');
  1373. $discountProblemsFlag = FALSE;
  1374. $flag_treat_as_partial = FALSE;
  1375. if (sizeof($order_totals)) {
  1376. // prepare subtotals
  1377. for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
  1378. if ($order_totals[$i]['code'] == '') continue;
  1379. if (in_array($order_totals[$i]['code'], array('ot_total','ot_subtotal','ot_tax','ot_shipping')) || strstr($order_totals[$i]['code'], 'insurance')) {
  1380. if ($order_totals[$i]['code'] == 'ot_shipping') $optionsST['SHIPPINGAMT'] = round($order_totals[$i]['value'],2);
  1381. if ($order_totals[$i]['code'] == 'ot_total') $optionsST['AMT'] = round($order_totals[$i]['value'],2);
  1382. if ($order_totals[$i]['code'] == 'ot_tax') $optionsST['TAXAMT'] += strval(round($order_totals[$i]['value'],2));
  1383. if ($order_totals[$i]['code'] == 'ot_subtotal') $optionsST['ITEMAMT'] = round($order_totals[$i]['value'],2);
  1384. if (strstr($order_totals[$i]['code'], 'insurance')) $optionsST['INSURANCEAMT'] += round($order_totals[$i]['value'],2);
  1385. //$optionsST['SHIPDISCAMT'] = ''; // Not applicable
  1386. } else {
  1387. // handle other order totals:
  1388. global $$order_totals[$i]['code'];
  1389. if ((substr($order_totals[$i]['text'], 0, 1) == '-') || (isset($$order_totals[$i]['code']->credit_class) && $$order_totals[$i]['code']->credit_class == true)) {
  1390. // handle credits
  1391. $creditsApplied += round($order_totals[$i]['value'], 2);
  1392. } else {
  1393. // treat all other OT's as if they're related to handling fees or other extra charges to be added/included
  1394. $surcharges += $order_totals[$i]['value'];
  1395. }
  1396. }
  1397. }
  1398. if ($creditsApplied > 0) $optionsST['ITEMAMT'] -= $creditsApplied;
  1399. if ($surcharges > 0) $optionsST['ITEMAMT'] += $surcharges;
  1400. // Handle tax-included scenario
  1401. if (DISPLAY_PRICE_WITH_TAX == 'true') $optionsST['TAXAMT'] = 0;
  1402. $subtotalPRE = $optionsST;
  1403. // Move shipping tax amount from Tax subtotal into Shipping subtotal for submission to PayPal, since PayPal applies tax to each line-item individually
  1404. $module = substr($_SESSION['shipping']['id'], 0, strpos($_SESSION['shipping']['id'], '_'));
  1405. if (zen_not_null($order->info['shipping_method']) && DISPLAY_PRICE_WITH_TAX != 'true') {
  1406. if ($GLOBALS[$module]->tax_class > 0) {
  1407. $shipping_tax_basis = (!isset($GLOBALS[$module]->tax_basis)) ? STORE_SHIPPING_TAX_BASIS : $GLOBALS[$module]->tax_basis;
  1408. $shippingOnBilling = zen_get_tax_rate($GLOBALS[$module]->tax_class, $order->billing['country']['id'], $order->billing['zone_id']);
  1409. $shippingOnDelivery = zen_get_tax_rate($GLOBALS[$module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
  1410. if ($shipping_tax_basis == 'Billing') {
  1411. $shipping_tax = $shippingOnBilling;
  1412. } elseif ($shipping_tax_basis == 'Shipping') {
  1413. $shipping_tax = $shippingOnDelivery;
  1414. } else {
  1415. if (STORE_ZONE == $order->billing['zone_id']) {
  1416. $shipping_tax = $shippingOnBilling;
  1417. } elseif (STORE_ZONE == $order->delivery['zone_id']) {
  1418. $shipping_tax = $shippingOnDelivery;
  1419. } else {
  1420. $shipping_tax = 0;
  1421. }
  1422. }
  1423. $taxAdjustmentForShipping = zen_round(zen_calculate_tax($order->info['shipping_cost'], $shipping_tax), $currencies->currencies[$_SESSION['currency']]['decimal_places']);
  1424. $optionsST['SHIPPINGAMT'] += $taxAdjustmentForShipping;
  1425. $optionsST['TAXAMT'] -= $taxAdjustmentForShipping;
  1426. }
  1427. }
  1428. $flagSubtotalsUnknownYet = (($optionsST['SHIPPINGAMT'] + $optionsST['SHIPDISCAMT'] + $optionsST['AMT'] + $optionsST['TAXAMT'] + $optionsST['ITEMAMT'] + $optionsST['INSURANCEAMT']) == 0);
  1429. } else {
  1430. // if we get here, we don't have any order-total information yet because the customer has clicked Express before starting normal checkout flow
  1431. // thus, we must make a note to manually calculate subtotals, rather than relying on the more robust order-total infrastructure
  1432. $flagSubtotalsUnknownYet = TRUE;
  1433. }
  1434. $decimals = $currencies->get_decimal_places($_SESSION['currency']);
  1435. // loop thru all products to prepare details of quantity and price.
  1436. for ($i=0, $n=sizeof($order->products), $k=-1; $i<$n; $i++) {
  1437. // PayPal is inconsistent in how it handles zero-value line-items, so skip this entry if price is zero
  1438. if ($order->products[$i]['final_price'] == 0) {
  1439. continue;
  1440. } else {
  1441. $k++;
  1442. }
  1443. $optionsLI["L_NUMBER$k"] = $order->products[$i]['model'];
  1444. $optionsLI["L_NAME$k"] = $order->products[$i]['name'] . ' [' . (int)$order->products[$i]['id'] . ']';
  1445. // Append *** if out-of-stock.
  1446. $optionsLI["L_NAME$k"] .= ((zen_get_products_stock($order->products[$i]['id']) - $order->products[$i]['qty']) < 0 ? STOCK_MARK_PRODUCT_OUT_OF_STOCK : '');
  1447. // if there are attributes, loop thru them and add to description
  1448. if (isset($order->products[$i]['attributes']) && sizeof($order->products[$i]['attributes']) > 0 ) {
  1449. for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
  1450. $optionsLI["L_NAME$k"] .= "\n " . $order->products[$i]['attributes'][$j]['option'] .
  1451. ': ' . $order->products[$i]['attributes'][$j]['value'];
  1452. } // end loop
  1453. } // endif attribute-info
  1454. // PayPal can't handle fractional-quantity values, so convert it to qty 1 here
  1455. if ($order->products[$i]['qty'] > 1 && ($order->products[$i]['qty'] != (int)$order->products[$i]['qty'] || $flag_treat_as_partial)) {
  1456. $optionsLI["L_NAME$k"] = '('.$order->products[$i]['qty'].' x ) ' . $optionsLI["L_NAME$k"];
  1457. // zen_add_tax already handles whether DISPLAY_PRICES_WITH_TAX is set
  1458. $optionsLI["L_AMT$k"] = zen_round(zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $decimals) * $order->products[$i]['qty'], $decimals);
  1459. $optionsLI["L_QTY$k"] = 1;
  1460. // no line-item tax component
  1461. } else {
  1462. $optionsLI["L_QTY$k"] = $order->products[$i]['qty'];
  1463. $optionsLI["L_AMT$k"] = zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $decimals);
  1464. }
  1465. $subTotalLI += ($optionsLI["L_QTY$k"] * $optionsLI["L_AMT$k"]);
  1466. // $subTotalTax += ($optionsLI["L_QTY$k"] * $optionsLI["L_TAXAMT$k"]);
  1467. // add line-item for one-time charges on this product
  1468. if ($order->products[$i]['onetime_charges'] != 0 ) {
  1469. $k++;
  1470. $optionsLI["L_NAME$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_ONETIME_CHARGES_PREFIX . substr(htmlentities($order->products[$i]['name'], ENT_QUOTES, 'UTF-8'), 0, 120);
  1471. $optionsLI["L_AMT$k"] = zen_round(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), $decimals);
  1472. $optionsLI["L_QTY$k"] = 1;
  1473. // $optionsLI["L_TAXAMT$k"] = zen_round(zen_calculate_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), $decimals);
  1474. $subTotalLI += $optionsLI["L_AMT$k"];
  1475. // $subTotalTax += $optionsLI["L_TAXAMT$k"];
  1476. }
  1477. $numberOfLineItemsProcessed = $k;
  1478. } // end for loopthru all products
  1479. // add line items for any surcharges added by order-total modules
  1480. if ($surcharges > 0) {
  1481. $numberOfLineItemsProcessed++;
  1482. $k = $numberOfLineItemsProcessed;
  1483. $optionsLI["L_NAME$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_SURCHARGES_LONG;
  1484. $optionsLI["L_AMT$k"] = $surcharges;
  1485. $optionsLI["L_QTY$k"] = 1;
  1486. $subTotalLI += $surcharges;
  1487. }
  1488. // add line items for discounts such as gift certificates and coupons
  1489. if ($creditsApplied > 0) {
  1490. $numberOfLineItemsProcessed++;
  1491. $k = $numberOfLineItemsProcessed;
  1492. $optionsLI["L_NAME$k"] = MODULES_PAYMENT_PAYPALWPP_LINEITEM_TEXT_DISCOUNTS_LONG;
  1493. $optionsLI["L_AMT$k"] = (-1 * $creditsApplied);
  1494. $optionsLI["L_QTY$k"] = 1;
  1495. $subTotalLI -= $creditsApplied;
  1496. }
  1497. // Reformat properly
  1498. // Replace & and = and % with * if found.
  1499. // reformat properly according to API specs
  1500. // Remove HTML markup from name if found
  1501. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1502. $optionsLI["L_NAME$k"] = str_replace(array('&','=','%'), '*', $optionsLI["L_NAME$k"]);
  1503. $optionsLI["L_NAME$k"] = zen_clean_html($optionsLI["L_NAME$k"], 'strong');
  1504. $optionsLI["L_NAME$k"] = substr($optionsLI["L_NAME$k"], 0, 127);
  1505. $optionsLI["L_AMT$k"] = round($optionsLI["L_AMT$k"], 2);
  1506. if (isset($optionsLI["L_NUMBER$k"])) {
  1507. if ($optionsLI["L_NUMBER$k"] == '') {
  1508. unset($optionsLI["L_NUMBER$k"]);
  1509. } else {
  1510. $optionsLI["L_NUMBER$k"] = str_replace(array('&','=','%'), '*', $optionsLI["L_NUMBER$k"]);
  1511. $optionsLI["L_NUMBER$k"] = substr($optionsLI["L_NUMBER$k"], 0, 127);
  1512. }
  1513. }
  1514. // if (isset($optionsLI["L_TAXAMT$k"]) && ($optionsLI["L_TAXAMT$k"] != '' || $optionsLI["L_TAXAMT$k"] > 0)) {
  1515. // $optionsLI["L_TAXAMT$k"] = round($optionsLI["L_TAXAMT$k"], 2);
  1516. // }
  1517. }
  1518. // Sanity Check of line-item subtotals
  1519. for ($j=0; $j<$k; $j++) {
  1520. $itemAMT = $optionsLI["L_AMT$j"];
  1521. $itemQTY = $optionsLI["L_QTY$j"];
  1522. $itemTAX = (isset($optionsLI["L_TAXAMT$j"]) ? $optionsLI["L_TAXAMT$j"] : 0);
  1523. $sumOfLineItems += ($itemQTY * $itemAMT);
  1524. $sumOfLineTax += ($itemQTY * $itemTAX);
  1525. }
  1526. $sumOfLineItems = round($sumOfLineItems, 2);
  1527. $sumOfLineTax = round($sumOfLineTax, 2);
  1528. if ($sumOfLineItems == 0) {
  1529. $sumOfLineTax = 0;
  1530. $optionsLI = array();
  1531. $discountProblemsFlag = TRUE;
  1532. if ($optionsST['SHIPPINGAMT'] == $optionsST['AMT']) {
  1533. $optionsST['SHIPPINGAMT'] = 0;
  1534. }
  1535. }
  1536. // // Sanity check -- if tax-included pricing is causing problems, remove the numbers and put them in a comment instead:
  1537. // $stDiffTaxOnly = (strval($sumOfLineItems - $sumOfLineTax - round($optionsST['AMT'], 2)) + 0);
  1538. // $this->zcLog('tax sanity check', 'stDiffTaxOnly: ' . $stDiffTaxOnly . "\nsumOfLineItems: " . $sumOfLineItems . "\nsumOfLineTax: " . $sumOfLineTax . ' ' . $subTotalTax . ' ' . print_r(array_merge($optionsST, $optionsLI), true));
  1539. // if (DISPLAY_PRICE_WITH_TAX == 'true' && $stDiffTaxOnly == 0 && ($optionsST['TAXAMT'] != 0 && $sumOfLineTax != 0)) {
  1540. // $optionsNB['DESC'] = 'Tax included in prices: ' . $sumOfLineTax . ' (' . $optionsST['TAXAMT'] . ') ';
  1541. // $optionsST['TAXAMT'] = 0;
  1542. // for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1543. // if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1544. // }
  1545. // }
  1546. // // Do sanity check -- if any of the line-item subtotal math doesn't add up properly, skip line-item details,
  1547. // // so that the order can go through even though PayPal isn't being flexible to handle Zen Cart's diversity
  1548. // if ((strval($subTotalTax) - strval($sumOfLineTax)) > 0.02) {
  1549. // $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));
  1550. // for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1551. // if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1552. // }
  1553. // $subTotalTax = 0;
  1554. // $sumOfLineTax = 0;
  1555. // }
  1556. // // If coupons exist and there's a calculation problem, then it's likely that taxes are incorrect, so reset L_TAXAMTn values
  1557. // if ($creditsApplied > 0 && (strval($optionsST['TAXAMT']) != strval($sumOfLineTax))) {
  1558. // $pre = $optionsLI;
  1559. // for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1560. // if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1561. // }
  1562. // $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));
  1563. // $subTotalTax = 0;
  1564. // $sumOfLineTax = 0;
  1565. // }
  1566. // disable line-item tax details, leaving only TAXAMT subtotal as tax indicator
  1567. for ($k=0, $n=$numberOfLineItemsProcessed+1; $k<$n; $k++) {
  1568. if (isset($optionsLI["L_TAXAMT$k"])) unset($optionsLI["L_TAXAMT$k"]);
  1569. }
  1570. // if ITEMAMT >0 and subTotalLI > 0 and they're not equal ... OR subTotalLI minus sumOfLineItems isn't 0
  1571. // check subtotals
  1572. if ((strval($optionsST['ITEMAMT']) > 0 && strval($subTotalLI) > 0 && strval($subTotalLI) != strval($optionsST['ITEMAMT'])) || strval($subTotalLI) - strval($sumOfLineItems) != 0) {
  1573. $this->zcLog('getLineItemDetails 5', 'Line-item subtotals do not add up properly. Line-item-details skipped.' . "\n" . strval($sumOfLineItems) . ' ' . strval($subTotalLI) . ' ' . print_r(array_merge($optionsST, $optionsLI), true));
  1574. $optionsLI = array();
  1575. $optionsLI["L_NAME0"] = MODULES_PAYMENT_PAYPALWPP_AGGREGATE_CART_CONTENTS;
  1576. $optionsLI["L_AMT0"] = $sumOfLineItems = $subTotalLI = $optionsST['ITEMAMT'];
  1577. }
  1578. // check whether discounts are causing a problem
  1579. if (strval($optionsST['ITEMAMT']) < 0) {
  1580. $pre = (array_merge($optionsST, $optionsLI));
  1581. $optionsST['ITEMAMT'] = $optionsST['AMT'];
  1582. $optionsLI = array();
  1583. $optionsLI["L_NAME0"] = MODULES_PAYMENT_PAYPALWPP_AGGREGATE_CART_CONTENTS;
  1584. $optionsLI["L_AMT0"] = $sumOfLineItems = $subTotalLI = $optionsST['ITEMAMT'];
  1585. if ($optionsST['AMT'] < $optionsST['TAXAMT']) $optionsST['TAXAMT'] = 0;
  1586. if ($optionsST['AMT'] < $optionsST['SHIPPINGAMT']) $optionsST['SHIPPINGAMT'] = 0;
  1587. $discountProblemsFlag = TRUE;
  1588. $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));
  1589. }
  1590. // 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
  1591. if ((!isset($optionsST['AMT']) || $optionsST['AMT'] == 0 || $flagSubtotalsUnknownYet == TRUE || $optionsST['ITEMAMT'] == 0) && $discountProblemsFlag != TRUE) {
  1592. $optionsST['ITEMAMT'] = $sumOfLineItems;
  1593. $optionsST['TAXAMT'] = $sumOfLineTax;
  1594. if ($subTotalShipping > 0) $optionsST['SHIPPINGAMT'] = $subTotalShipping;
  1595. $optionsST['AMT'] = $sumOfLineItems + $optionsST['TAXAMT'] + $optionsST['SHIPPINGAMT'];
  1596. }
  1597. $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));
  1598. // if subtotals are not adding up correctly, then skip sending any line-item or subtotal details to PayPal
  1599. $stAll = round(strval($optionsST['ITEMAMT']) + strval($optionsST['TAXAMT']) + strval($optionsST['SHIPPINGAMT']) + strval($optionsST['SHIPDISCAMT']) + strval($optionsST['HANDLINGAMT']) + strval($optionsST['INSURANCEAMT']), 2);
  1600. $stDiff = strval($optionsST['AMT'] - $stAll);
  1601. $stDiffRounded = (strval($stAll - round($optionsST['AMT'], 2)) + 0);
  1602. // unset any subtotal values that are zero
  1603. if (isset($optionsST['ITEMAMT']) && $optionsST['ITEMAMT'] == 0) unset($optionsST['ITEMAMT']);
  1604. if (isset($optionsST['TAXAMT']) && $optionsST['TAXAMT'] == 0) unset($optionsST['TAXAMT']);
  1605. if (isset($optionsST['SHIPPINGAMT']) && $optionsST['SHIPPINGAMT'] == 0) unset($optionsST['SHIPPINGAMT']);
  1606. if (isset($optionsST['SHIPDISCAMT']) && $optionsST['SHIPDISCAMT'] == 0) unset($optionsST['SHIPDISCAMT']);
  1607. if (isset($optionsST['HANDLINGAMT']) && $optionsST['HANDLINGAMT'] == 0) unset($optionsST['HANDLINGAMT']);
  1608. if (isset($optionsST['INSURANCEAMT']) && $optionsST['INSURANCEAMT'] == 0) unset($optionsST['INSURANCEAMT']);
  1609. // tidy up all values so that they comply with proper format (number_format(xxxx,2) for PayPal US use )
  1610. if (!defined('PAYPALWPP_SKIP_LINE_ITEM_DETAIL_FORMATTING') || PAYPALWPP_SKIP_LINE_ITEM_DETAIL_FORMATTING != 'true' || in_array($order->info['currency'], array('JPY', 'NOK', 'HUF'))) {
  1611. if (is_array($optionsST)) foreach ($optionsST as $key=>$value) {
  1612. $optionsST[$key] = number_format($value, ((int)$currencies->get_decimal_places($restrictedCurrency) == 0 ? 0 : 2));
  1613. }
  1614. if (is_array($optionsLI)) foreach ($optionsLI as $key=>$value) {
  1615. if (substr($key, 0, 8) == 'L_TAXAMT' && ($optionsLI[$key] == '' || $optionsLI[$key] == 0)) {
  1616. unset($optionsLI[$key]);
  1617. } else {
  1618. if (strstr($key, 'AMT')) $optionsLI[$key] = number_format($value, ((int)$currencies->get_decimal_places($restrictedCurrency) == 0 ? 0 : 2));
  1619. }
  1620. }
  1621. }
  1622. $this->zcLog('getLineItemDetails 8', 'checking subtotals... ' . "\n" . print_r(array_merge(array('calculated total'=>number_format($stAll, ((int)$currencies->get_decimal_places($restrictedCurrency) == 0 ? 0 : 2))), $optionsST), true) . "\n-------------------\ndifference: " . ($stDiff + 0) . ' (abs+rounded: ' . ($stDiffRounded + 0) . ')');
  1623. if ( $stDiffRounded != 0) {
  1624. $this->zcLog('getLineItemDetails 9', 'Subtotals Bad. Skipping line-item/subtotal details');
  1625. return array();
  1626. }
  1627. $this->zcLog('getLineItemDetails 10', 'subtotals balance - okay');
  1628. // Send Subtotal and LineItem results back to be submitted to PayPal
  1629. return array_merge($optionsST, $optionsLI, $optionsNB);
  1630. }
  1631. /**
  1632. * If the account was created only for temporary purposes to place the PayPal order, delete it.
  1633. */
  1634. function ec_delete_user($cid) {
  1635. global $db;
  1636. unset($_SESSION['customer_id']);
  1637. unset($_SESSION['customer_default_address_id']);
  1638. unset($_SESSION['customer_first_name']);
  1639. unset($_SESSION['customer_country_id']);
  1640. unset($_SESSION['customer_zone_id']);
  1641. unset($_SESSION['comments']);
  1642. unset($_SESSION['customer_guest_id']);
  1643. }
  1644. /**
  1645. * If the EC flow has to be interrupted for any reason, this does the appropriate cleanup and displays status/error messages.
  1646. */
  1647. function terminateEC($error_msg = '', $kill_sess_vars = false, $goto_page = '') {
  1648. global $messageStack, $order, $order_total_modules;
  1649. $error_msg = trim($error_msg);
  1650. if (substr($error_msg, -1) == '-') $error_msg = trim(substr($error_msg, 0, strlen($error_msg) - 1));
  1651. $stackAlert = 'checkout_payment';
  1652. // debug
  1653. $this->_doDebug('PayPal test Log - terminateEC-A', "goto page: " . $goto_page . "\nerror_msg: " . $error_msg . "\n\nSession data: " . print_r($_SESSION, true));
  1654. if ($kill_sess_vars) {
  1655. if (!empty($_SESSION['paypal_ec_temp'])) {
  1656. $this->ec_delete_user($_SESSION['customer_id']);
  1657. }
  1658. // Unregister the paypal session variables, making the user start over.
  1659. unset($_SESSION['paypal_ec_temp']);
  1660. unset($_SESSION['paypal_ec_token']);
  1661. unset($_SESSION['paypal_ec_payer_id']);
  1662. unset($_SESSION['paypal_ec_payer_info']);
  1663. unset($_SESSION['paypal_ec_final']);
  1664. unset($_SESSION['paypal_ec_markflow']);
  1665. // debug
  1666. $this->zcLog('termEC-1', 'Killed the session vars as requested');
  1667. }
  1668. $this->zcLog('termEC-2', 'BEFORE: Token Data:' . $_SESSION['paypal_ec_token']);
  1669. if ($error_msg) {
  1670. $messageStack->add_session($stackAlert, $error_msg, 'error');
  1671. }
  1672. // debug
  1673. $this->zcLog('termEC-10', 'Redirecting to ' . $goto_page . ' - Stack: ' . $stackAlert . "\n" . 'Message: ' . $error_msg . "\nSession Data: " . print_r($_SESSION, true));
  1674. zen_redirect(zen_href_link($goto_page, '', 'SSL', true, false));
  1675. }
  1676. /**
  1677. * Error / exception handling
  1678. */
  1679. function _errorHandler($response, $operation = '', $ignore_codes = '') {
  1680. global $messageStack, $doPayPal;
  1681. $gateway_mode = (isset($response['PNREF']) && $response['PNREF'] != '');
  1682. $basicError = (!$response || (isset($response['RESULT']) && $response['RESULT'] != 0) || (isset($response['ACK']) && !strstr($response['ACK'], 'Success')) || (!isset($response['RESULT']) && !isset($response['ACK'])));
  1683. $ignoreList = explode(',', str_replace(' ', '', $ignore_codes));
  1684. foreach($ignoreList as $key=>$value) {
  1685. if ($value != '' && $response['L_ERRORCODE0'] == $value) $basicError = false;
  1686. }
  1687. /** Handle FMF Scenarios **/
  1688. if (in_array($operation, array('DoExpressCheckoutPayment', 'DoDirectPayment')) && $response['PAYMENTSTATUS'] == 'Pending' && $response['L_ERRORCODE0'] == 11610) {
  1689. $this->fmfResponse = urldecode($response['L_SHORTMESSAGE0']);
  1690. $this->fmfErrors = array();
  1691. if ($response['ACK'] == 'SuccessWithWarning' && isset($response['L_FMFPENDINGID0'])) {
  1692. for ($i=0; $i<20; $i++) {
  1693. $this->fmfErrors[] = array('key' => $response['L_FMFPENDINGID' . $i], 'status' => $response['L_FMFPENDINGID' . $i], 'desc' => $response['L_FMFPENDINGDESCRIPTION' . $i]);
  1694. }
  1695. }
  1696. return (sizeof($this->fmfErrors)>0) ? $this->fmfErrors : FALSE;
  1697. }
  1698. //echo '<br />basicError='.$basicError.'<br />' . urldecode(print_r($response,true)); die('halted');
  1699. if (!isset($response['L_SHORTMESSAGE0']) && isset($response['RESPMSG']) && $response['RESPMSG'] != '') $response['L_SHORTMESSAGE0'] = $response['RESPMSG'];
  1700. $errorInfo = "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with PayPal Website Payments Pro.';
  1701. switch($operation) {
  1702. case 'DoDirectPayment':
  1703. if ($basicError ||
  1704. ((isset($_SESSION['paypal_ec_token']) && isset($response['TOKEN'])) && $_SESSION['paypal_ec_token'] != urldecode($response['TOKEN'])) ) {
  1705. // Error, so send the store owner a complete dump of the transaction.
  1706. if ($this->enableDebugging) {
  1707. $this->_doDebug('PayPal Error Log - before_process() - DP', "In function: before_process() - Direct Payment \r\nDid first contact attempt return error? " . ($error_occurred ? "Yes" : "No") . " \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)));
  1708. }
  1709. $errorText = MODULE_PAYMENT_PAYPALDP_INVALID_RESPONSE;
  1710. $errorNum = urldecode($response['L_ERRORCODE0'] . ' ' . $response['RESULT'] . ' <!-- ' . $response['RESPMSG'] . ' -->');
  1711. if ($response['RESULT'] == 25) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_NOT_WPP_ACCOUNT_ERROR;
  1712. if ($response['L_ERRORCODE0'] == 10500 || $response['L_ERRORCODE0'] == 10501) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_NOT_US_WPP_ACCOUNT_ERROR;
  1713. if ($response['HOSTCODE'] == 10500 || $response['HOSTCODE'] == 10501) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_NOT_UKWPP_ACCOUNT_ERROR;
  1714. if ($response['HOSTCODE'] == 10558) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_CANNOT_USE_THIS_CURRENCY_ERROR;
  1715. if ($response['L_ERRORCODE0'] == 10002) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_SANDBOX_VS_LIVE_ERROR;
  1716. if ($response['L_ERRORCODE0'] == 10565) {
  1717. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_WPP_BAD_COUNTRY_ERROR;
  1718. $_SESSION['payment'] = '';
  1719. }
  1720. if ($response['L_ERRORCODE0'] == 10566) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_CARD_TYPE_NOT_SUPPORTED;
  1721. if ($response['L_ERRORCODE0'] == 10736) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_ADDR_ERROR;
  1722. if ($response['L_ERRORCODE0'] == 10752) {
  1723. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_DECLINED;
  1724. $errorNum = '10752';
  1725. }
  1726. if ($response['L_ERRORCODE0'] == 15012) { // Mastercard CE agreement not signed between merchant and PayPal. Thus cannot accept mastercard.
  1727. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_CARD_TYPE_NOT_SUPPORTED;
  1728. $errorNum = '15012';
  1729. }
  1730. if ($response['L_ERRORCODE0'] == 15005) {
  1731. $errorText = 'Card rejected by the bank. Your IP address has been recorded.';
  1732. $errorNum = '15005';
  1733. }
  1734. if ($response['RESPMSG'] != '') $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_DECLINED . ' ' . $errorText;
  1735. $detailedMessage = ($errorText == MODULE_PAYMENT_PAYPALDP_INVALID_RESPONSE || $errorText == MODULE_PAYMENT_PAYPALDP_TEXT_DECLINED || (int)trim($errorNum) > 0 || $this->enableDebugging || $response['CURL_ERRORS'] != '' || $this->emailAlerts) ? (isset($response['RESULT']) && $response['RESULT'] != 0 ? MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED . ' (' . $errorNum . ')' : $errorNum) . ' ' . urldecode(' ' . $response['L_SHORTMESSAGE0'] . ' - ' . $response['L_LONGMESSAGE0'] . ' ' . $response['CURL_ERRORS']) : '';
  1736. $explain = "\n\nProblem occurred while customer #" . $_SESSION['customer_id'] . ' -- ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' -- was attempting checkout.' . "\n";
  1737. $detailedEmailMessage = MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_MESSAGE . urldecode($response['L_ERRORCODE0'] . ' ' . $response['RESPMSG']. "\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" . $errorInfo . "\n\n" . 'Transaction Response Details: ' . print_r($response, true) . "\n\n" . 'Transaction Submission: ' . urldecode($doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList), true)));
  1738. $detailedEmailMessage .= $explain;
  1739. if (!isset($response['L_ERRORCODE0']) && isset($response['RESULT'])) $detailedEmailMessage .= "\n\n" . print_r($response, TRUE);
  1740. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT . ' (' . zen_uncomment($errorNum) . ')', zen_uncomment($detailedEmailMessage), STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br(zen_uncomment($detailedEmailMessage))), 'paymentalert');
  1741. if ($response['L_ERRORCODE0'] == 15012) $detailedEmailMessage = '';
  1742. $this->terminateEC(($detailedEmailMessage == '' ? $errorText . ' (' . $errorNum . ') ' : $detailedMessage), ($gateway_mode ? true : false), FILENAME_CHECKOUT_PAYMENT);
  1743. return true;
  1744. }
  1745. break;
  1746. case 'DoRefund':
  1747. if ($basicError || (!isset($response['RESPMSG']) && !isset($response['REFUNDTRANSACTIONID']))) {
  1748. // if error, display error message. If debug options enabled, email dump to store owner
  1749. if ($this->enableDebugging) {
  1750. $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));
  1751. }
  1752. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_REFUND_ERROR;
  1753. if ($response['L_ERRORCODE0'] == 10009) $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_REFUNDFULL_ERROR;
  1754. if ($response['RESULT'] == 105 || isset($response['RESPMSG'])) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  1755. if (urldecode($response['L_LONGMESSAGE0']) == 'This transaction has already been fully refunded') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  1756. if (urldecode($response['L_LONGMESSAGE0']) == 'Can not do a full refund after a partial refund') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  1757. 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']);
  1758. if (urldecode($response['L_LONGMESSAGE0']) == 'You can not refund this type of transaction') $response['L_SHORTMESSAGE0'] = urldecode($response['L_LONGMESSAGE0']);
  1759. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  1760. $messageStack->add_session($errorText, 'error');
  1761. return true;
  1762. }
  1763. break;
  1764. case 'DoAuthorization':
  1765. case 'DoReauthorization':
  1766. if ($basicError) {
  1767. // if error, display error message. If debug options enabled, email dump to store owner
  1768. if ($this->enableDebugging) {
  1769. $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));
  1770. }
  1771. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_AUTH_ERROR;
  1772. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  1773. $messageStack->add_session($errorText, 'error');
  1774. return true;
  1775. }
  1776. break;
  1777. case 'DoCapture':
  1778. if ($basicError) {
  1779. // if error, display error message. If debug options enabled, email dump to store owner
  1780. if ($this->enableDebugging) {
  1781. $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));
  1782. }
  1783. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_CAPT_ERROR;
  1784. if ($response['RESULT'] == 111) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  1785. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  1786. $messageStack->add_session($errorText, 'error');
  1787. return true;
  1788. }
  1789. break;
  1790. case 'DoVoid':
  1791. if ($basicError) {
  1792. // if error, display error message. If debug options enabled, email dump to store owner
  1793. if ($this->enableDebugging) {
  1794. $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));
  1795. }
  1796. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_VOID_ERROR;
  1797. if ($response['RESULT'] == 12) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  1798. if ($response['RESULT'] == 108) $response['L_SHORTMESSAGE0'] = $response['RESULT'] . ' ' . $response['RESPMSG'];
  1799. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  1800. $messageStack->add_session($errorText, 'error');
  1801. return true;
  1802. }
  1803. break;
  1804. case 'GetTransactionDetails':
  1805. if ($basicError) {
  1806. if (isset($response['RESPMSG']) && $response['RESPMSG'] == 'Field format error: ORIGID missing') {
  1807. return FALSE;
  1808. }
  1809. // if error, display error message. If debug options enabled, email dump to store owner
  1810. if ($this->enableDebugging) {
  1811. $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));
  1812. }
  1813. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_GETDETAILS_ERROR;
  1814. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  1815. $messageStack->add_session($errorText, 'error');
  1816. return true;
  1817. }
  1818. break;
  1819. case 'TransactionSearch':
  1820. if ($basicError) {
  1821. // if error, display error message. If debug options enabled, email dump to store owner
  1822. if ($this->enableDebugging) {
  1823. $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));
  1824. }
  1825. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_TRANSSEARCH_ERROR;
  1826. $errorText .= ' (' . urldecode($response['L_SHORTMESSAGE0']) . ') ' . $response['L_ERRORCODE0'];
  1827. $messageStack->add_session($errorText, 'error');
  1828. return true;
  1829. }
  1830. break;
  1831. default:
  1832. if ($basicError) {
  1833. // if error, display error message. If debug options enabled, email dump to store owner
  1834. if ($this->enableDebugging) {
  1835. $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));
  1836. }
  1837. $errorText = MODULE_PAYMENT_PAYPALDP_TEXT_GEN_API_ERROR;
  1838. $errorNum .= ' (' . urldecode($response['L_SHORTMESSAGE0'] . ' <!-- ' . $response['RESPMSG']) . ' -->) ' . $response['L_ERRORCODE0'];
  1839. $detailedMessage = ($errorText == MODULE_PAYMENT_PAYPALDP_TEXT_GEN_API_ERROR || $errorText == MODULE_PAYMENT_PAYPALDP_TEXT_DECLINED || $this->enableDebugging || $response['CURL_ERRORS'] != '' || $this->emailAlerts) ? urldecode(' ' . $response['L_SHORTMESSAGE0'] . ' - ' . $response['L_LONGMESSAGE0'] . ' ' . $response['CURL_ERRORS']) : '';
  1840. $explain = "\n\nProblem occurred while customer #" . $_SESSION['customer_id'] . ' -- ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' -- was attempting checkout.' . "\n";
  1841. $detailedEmailMessage = ($detailedMessage == '') ? '' : MODULE_PAYMENT_PAYPALDP_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" . $errorInfo . "\n\n" . 'Transaction Response Details: ' . print_r($response, true) . "\n\n" . 'Transaction Submission: ' . urldecode($doPayPal->_sanitizeLog($doPayPal->_parseNameValueList($doPayPal->lastParamList), true)));
  1842. if ($detailedEmailMessage != '') $detailedEmailMessage .= $explain;
  1843. if ($detailedEmailMessage != '') zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT . ' (' . zen_uncomment($errorNum) . ')', zen_uncomment($detailedMessage . $explain), STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br(zen_uncomment($detailedEmailMessage))), 'paymentalert');
  1844. $messageStack->add_session($errorText . $errorNum . $detailedMessage, 'error');
  1845. return true;
  1846. }
  1847. break;
  1848. }
  1849. }
  1850. function tableCheckup() {
  1851. global $db, $sniffer;
  1852. $fieldOkay1 = (method_exists($sniffer, 'field_type')) ? $sniffer->field_type(TABLE_PAYPAL, 'txn_id', 'varchar(20)', true) : -1;
  1853. $fieldOkay2 = ($sniffer->field_exists(TABLE_PAYPAL, 'module_name')) ? true : -1;
  1854. $fieldOkay3 = ($sniffer->field_exists(TABLE_PAYPAL, 'order_id')) ? true : -1;
  1855. if ($fieldOkay1 == -1) {
  1856. $sql = "show fields from " . TABLE_PAYPAL;
  1857. $result = $db->Execute($sql);
  1858. while (!$result->EOF) {
  1859. if ($result->fields['Field'] == 'txn_id') {
  1860. if ($result->fields['Type'] == 'varchar(20)') {
  1861. $fieldOkay1 = true; // exists and matches required type, so skip to other checkup
  1862. } else {
  1863. $fieldOkay1 = $result->fields['Type']; // doesn't match, so return what it "is"
  1864. break;
  1865. }
  1866. }
  1867. $result->MoveNext();
  1868. }
  1869. }
  1870. if ($fieldOkay1 !== true) {
  1871. // temporary fix to table structure for v1.3.7.x -- may remove in later release
  1872. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payment_type payment_type varchar(40) NOT NULL default ''");
  1873. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE txn_type txn_type varchar(40) NOT NULL default ''");
  1874. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payment_status payment_status varchar(32) NOT NULL default ''");
  1875. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE reason_code reason_code varchar(40) default NULL");
  1876. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE pending_reason pending_reason varchar(32) default NULL");
  1877. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE invoice invoice varchar(128) default NULL");
  1878. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payer_business_name payer_business_name varchar(128) default NULL");
  1879. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_name address_name varchar(64) default NULL");
  1880. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_street address_street varchar(254) default NULL");
  1881. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_city address_city varchar(120) default NULL");
  1882. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE address_state address_state varchar(120) default NULL");
  1883. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE payer_email payer_email varchar(128) NOT NULL default ''");
  1884. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE business business varchar(128) NOT NULL default ''");
  1885. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE receiver_email receiver_email varchar(128) NOT NULL default ''");
  1886. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE txn_id txn_id varchar(20) NOT NULL default ''");
  1887. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE parent_txn_id parent_txn_id varchar(20) default NULL");
  1888. }
  1889. if ($fieldOkay2 !== true) {
  1890. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " ADD COLUMN module_name varchar(40) NOT NULL default '' after txn_type");
  1891. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " ADD COLUMN module_mode varchar(40) NOT NULL default '' after module_name");
  1892. }
  1893. if ($fieldOkay3 !== true) {
  1894. $db->Execute("ALTER TABLE " . TABLE_PAYPAL . " CHANGE zen_order_id order_id int(11) NOT NULL default '0'");
  1895. }
  1896. }
  1897. /****************************************************************************************************************************
  1898. * ADDED CODE FOR 3D-SECURE SUPPORT PROVIDED BY CARDINALCOMMERCE FOR PAYPAL-UK
  1899. */
  1900. /**
  1901. * reset session vars related to 3D-Secure processing
  1902. */
  1903. function clear_3DSecure_session_vars($thorough = FALSE) {
  1904. if ($thorough) {
  1905. if (isset($_SESSION['3Dsecure_requires_lookup'])) unset($_SESSION['3Dsecure_requires_lookup']);
  1906. if (isset($_SESSION['3Dsecure_card_type'])) unset($_SESSION['3Dsecure_card_type']);
  1907. }
  1908. if (isset($_SESSION['3Dsecure_merchantData'])) unset($_SESSION['3Dsecure_merchantData']);
  1909. if (isset($_SESSION['3Dsecure_enroll_lookup_attempted'])) unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
  1910. if (isset($_SESSION['3Dsecure_authentication_attempted'])) unset($_SESSION['3Dsecure_authentication_attempted']);
  1911. if (isset($_SESSION['3Dsecure_transactionId'])) unset($_SESSION['3Dsecure_transactionId']);
  1912. if (isset($_SESSION['3Dsecure_enrolled'])) unset($_SESSION['3Dsecure_enrolled']);
  1913. if (isset($_SESSION['3Dsecure_acsURL'])) unset($_SESSION['3Dsecure_acsURL']);
  1914. if (isset($_SESSION['3Dsecure_payload'])) unset($_SESSION['3Dsecure_payload']);
  1915. if (isset($_SESSION['3Dsecure_auth_status'])) unset($_SESSION['3Dsecure_auth_status']);
  1916. if (isset($_SESSION['3Dsecure_sig_status'])) unset($_SESSION['3Dsecure_sig_status']);
  1917. if (isset($_SESSION['3Dsecure_auth_xid'])) unset($_SESSION['3Dsecure_auth_xid']);
  1918. if (isset($_SESSION['3Dsecure_auth_cavv'])) unset($_SESSION['3Dsecure_auth_cavv']);
  1919. if (isset($_SESSION['3Dsecure_auth_eci'])) unset($_SESSION['3Dsecure_auth_eci']);
  1920. if (isset($_SESSION['3Dsecure_term_url'])) unset($_SESSION['3Dsecure_term_url']);
  1921. if (isset($_SESSION['3Dsecure_auth_url'])) unset($_SESSION['3Dsecure_auth_url']);
  1922. }
  1923. function determine3DSecureProtection($cardType, $ECI) {
  1924. $resultStatus = "NOT PROTECTED";
  1925. if (strcasecmp($cardType, "VISA") == 0){
  1926. if ((strcasecmp($ECI, "05") == 0) || (strcasecmp($ECI, "06") == 0)) {
  1927. $resultStatus = "PROTECTED";
  1928. } else {
  1929. $resultStatus = "NOT PROTECTED";
  1930. }
  1931. } else if (strcasecmp($cardType, "MASTERCARD") == 0){
  1932. if (strcasecmp($ECI, "02") == 0) {
  1933. $resultStatus = "PROTECTED";
  1934. } else {
  1935. $resultStatus = "NOT PROTECTED";
  1936. }
  1937. } else if (strcasecmp($cardType, "JCB") == 0){
  1938. if ((strcasecmp($ECI, "05") == 0) || (strcasecmp($ECI, "06") == 0)) {
  1939. $resultStatus = "PROTECTED";
  1940. } else {
  1941. $resultStatus = "NOT PROTECTED";
  1942. }
  1943. }
  1944. return $resultStatus;
  1945. }
  1946. /**
  1947. * 3D-Secure lookup
  1948. *
  1949. * @param array $lookup_data_array
  1950. * @return array
  1951. */
  1952. function get3DSecureLookupResponse($lookup_data_array) {
  1953. // Set some defaults
  1954. if (!isset($lookup_data_array['order_desc']) || $lookup_data_array['order_desc'] == '') $lookup_data_array['order_desc'] = 'Zen Cart(R) Transaction';
  1955. if (!isset($lookup_data_array['order_number']) || $lookup_data_array['order_number'] == '') $lookup_data_array['order_number'] = zen_session_id();
  1956. // format the card expiration
  1957. $lookup_data_array['cc3d_exp_year'] = (strlen($lookup_data_array['cc3d_exp_year']) == 2 ? '20' : '') . $lookup_data_array['cc3d_exp_year'];
  1958. // get the ISO 4217 currency
  1959. $iso_currency = $this->getISOCurrency($lookup_data_array['currency']);
  1960. // format the transaction amounts
  1961. $raw_amount = $this->formatRawAmount($lookup_data_array['txn_amount'], $iso_currency);
  1962. // determine the appropriate product code for submission
  1963. $prodCode = FALSE;
  1964. if (isset($_SESSION['cart'])) {
  1965. if ($_SESSION['cart']->get_cart_type == 'virtual') {
  1966. $prodCode = 'DIG';
  1967. } else {
  1968. $prodCode = 'PHY';
  1969. }
  1970. }
  1971. // DEBUG ONLY: $this->zcLog(__FILE__ . '->' . __LINE__, 'session details: ' . print_r(array_merge($_POST, $_SESSION), true));
  1972. // Build the XML cmpi_lookup message
  1973. $data = '<CardinalMPI>';
  1974. $data .= '<MsgType>cmpi_lookup</MsgType>';
  1975. $data .= '<Version>1.7</Version>';
  1976. $data .= '<ProcessorId>' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR) . '</ProcessorId>';
  1977. $data .= '<MerchantId><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]></MerchantId>';
  1978. $data .= '<TransactionPwd><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]></TransactionPwd>';
  1979. $data .= '<TransactionType>CC</TransactionType>';
  1980. $data .= '<TransactionMode>S</TransactionMode>';
  1981. $data .= '<OrderNumber>' . $this->escapeXML($lookup_data_array['order_number']) . '</OrderNumber>';
  1982. $data .= '<OrderDescription>' . $this->escapeXML($lookup_data_array['order_desc']) . '</OrderDescription>';
  1983. $data .= '<Amount>' . $this->escapeXML($raw_amount) . '</Amount>';
  1984. $data .= '<CurrencyCode>' . $this->escapeXML($iso_currency) . '</CurrencyCode>';
  1985. $data .= '<CardNumber>' . $this->escapeXML($lookup_data_array['cc3d_card_number']) . '</CardNumber>';
  1986. $data .= '<Cvv>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</Cvv>';
  1987. $data .= '<CardCode>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</CardCode>';
  1988. $data .= '<CardExpMonth>' . $this->escapeXML($lookup_data_array['cc3d_exp_month']) . '</CardExpMonth>';
  1989. $data .= '<CardExpYear>' . $this->escapeXML($lookup_data_array['cc3d_exp_year']) . '</CardExpYear>';
  1990. $data .= '<UserAgent>' . $this->escapeXML($_SERVER["HTTP_USER_AGENT"]) . '</UserAgent>';
  1991. $ipAddress = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
  1992. $data .= '<IPAddress>' . $this->escapeXML($ipAddress) . '</IPAddress>';
  1993. $data .= '<BrowserHeader>' . $this->escapeXML($_SERVER["HTTP_ACCEPT"]) . '</BrowserHeader>';
  1994. $data .= '<OrderChannel>' . $this->escapeXML('MARK') . '</OrderChannel>';
  1995. if (isset($lookup_data_array['merchantData'])) $data .= '<MerchantData>' . $this->escapeXML($lookup_data_array['merchantData']) . '</MerchantData>';
  1996. if ($prodCode !== FALSE && $prodCode != '') $data .= '<ProductCode>' . $this->escapeXML($prodCode) . '</ProductCode>';
  1997. $data .= '</CardinalMPI>';
  1998. $debugData = str_replace(array('[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]', '[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]', $this->escapeXML($lookup_data_array['cc3d_card_number']), $this->escapeXML($lookup_data_array['cc3d_checkcode'])), '********', $data);
  1999. if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
  2000. $this->zcLog('Cardinal Lookup 1', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup request (' . MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL . ') - ' . $debugData);
  2001. }
  2002. $responseString = $this->send3DSecureHttp(MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL, $data, $debugData);
  2003. if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
  2004. $this->zcLog('Cardinal Lookup 2', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup response - ' . $responseString);
  2005. }
  2006. // parse the XML
  2007. $parser = new CardinalXMLParser;
  2008. $parser->deserializeXml($responseString);
  2009. $errorNo = $parser->deserializedResponse['ErrorNo'];
  2010. $errorDesc = $parser->deserializedResponse['ErrorDesc'];
  2011. $enrolled = $parser->deserializedResponse['Enrolled'];
  2012. if ($errorNo != 0) {
  2013. $this->zcLog('Cardinal Lookup 3', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc);
  2014. $errorText = 'Cardinal Lookup 3' . '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc;
  2015. $errorText .= "\n\n" . 'There are 3 steps to configuring your Cardinal 3D-Secure service properly: ' . "\n1-Login to the Cardinal Merchant Admin URL supplied in your welcome package (NOT the test URL), and accept the license agreement.\n2-Set a transaction password.\n3-Copy your Cardinal Merchant ID and Cardinal Transaction Password into your ZC PayPal module.\n\nFor specific help, please contact implement@cardinalcommerce.com to sort out your account configuration issues.";
  2016. $errorText .= "\n\nProblem observed while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication. THEIR PURCHASE WAS NOT SUCCESSFUL. Please resolve this matter to enable future checkouts.';
  2017. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, substr($errorDesc, 0, 75) . ' (' . $errorNo . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  2018. }
  2019. // default the continue flag to 'N'
  2020. $continue_flag = 'N';
  2021. // determine whether the transaction should continue or fail based upon
  2022. // the enrollment lookup results
  2023. if (strcasecmp(MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ, 'No') == 0) {
  2024. $continue_flag = 'Y';
  2025. } else if (strcmp($errorNo, '0') == 0) {
  2026. if (strcasecmp($enrolled, 'Y') == 0) {
  2027. $continue_flag = 'Y';
  2028. } else if (strcasecmp($enrolled, 'N') == 0) {
  2029. $cardType = $this->determineCardType($this->cc_card_number);
  2030. if (strcasecmp($cardType, 'VISA') == 0 || strcasecmp($cardType, 'JCB') == 0) {
  2031. $continue_flag = 'Y';
  2032. }
  2033. }
  2034. } else if ($errorNo == 1001) { // merchant has an account configuration problem to fix
  2035. $errorText = CENTINEL_ERROR_CODE_1001 . ' - ' . CENTINEL_ERROR_CODE_1001_DESC;
  2036. $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  2037. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_1001_DESC . ' (' . CENTINEL_ERROR_CODE_1001 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  2038. $continue_flag = 'Y';
  2039. }
  2040. if (strcasecmp('Y', $continue_flag) == 0) {
  2041. // For validation/security purposes, mark the session that the lookup result was acceptable.
  2042. $_SESSION['3Dsecure_enroll_lookup_attempted'] = 'Y';
  2043. } else {
  2044. // For validation/security purposes, mark the session that the lookup result was not acceptable.
  2045. unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
  2046. }
  2047. $result = array('continue_flag' => $continue_flag,
  2048. 'enrolled' => $enrolled,
  2049. 'transaction_id' => $parser->deserializedResponse['TransactionId'],
  2050. 'error_no' => $errorNo,
  2051. 'error_desc' => $errorDesc,
  2052. 'acs_url' => $parser->deserializedResponse['ACSUrl'],
  2053. 'spa_hidden_fields' => $parser->deserializedResponse['SPAHiddenFields'],
  2054. 'payload' => $parser->deserializedResponse['Payload'],
  2055. 'cc3d_card_number' => $parser->deserializedResponse['CardNumber'],
  2056. 'cc3d_checkcode' => $parser->deserializedResponse['CardCode'],
  2057. 'cc3d_exp_month' => $parser->deserializedResponse['CardExpMonth'],
  2058. 'cc3d_exp_year' => $parser->deserializedResponse['CardExpYear'],
  2059. 'EciFlag' => $parser->deserializedResponse['EciFlag'],
  2060. 'cc3d_merchantdata' => $parser->deserializedResponse['MerchantData']);
  2061. return $result;
  2062. }
  2063. /**
  2064. * 3D-Secure Authenticate
  2065. * @param array $authenticate_data_array
  2066. * @return array
  2067. */
  2068. function get3DSecureAuthenticateResponse($authenticate_data_array) {
  2069. // Build the XML cmpi_authenticate message
  2070. $data = '<CardinalMPI>';
  2071. $data .= '<MsgType>cmpi_authenticate</MsgType>';
  2072. $data .= '<Version>1.7</Version>';
  2073. $data .= '<ProcessorId>' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR) . '</ProcessorId>';
  2074. $data .= '<MerchantId><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]></MerchantId>';
  2075. $data .= '<TransactionType>CC</TransactionType>';
  2076. $data .= '<TransactionPwd><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]></TransactionPwd>';
  2077. $data .= '<TransactionId>' . $this->escapeXML($authenticate_data_array['transaction_id']) . '</TransactionId>';
  2078. $data .= '<PAResPayload>' . $this->escapeXML($authenticate_data_array['payload']) . '</PAResPayload>';
  2079. if (isset($authenticate_data_array['merchantData'])) $data .= '<MerchantData>' . $this->escapeXML($authenticate_data_array['merchantData']) . '</MerchantData>';
  2080. $data .= '</CardinalMPI>';
  2081. $debugData = str_replace(array('[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]', '[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]'), '********', $data);
  2082. if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
  2083. $this->zcLog('Cardinal Auth 1', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_authenticate request (' . MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL . ') - ' . $debugData);
  2084. }
  2085. $responseString = $this->send3DSecureHttp(MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL, $data, $debugData);
  2086. if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
  2087. $this->zcLog('Cardinal Auth 2', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_authenticate response - ' . $responseString);
  2088. }
  2089. // parse the XML
  2090. $parser = new CardinalXMLParser;
  2091. $parser->deserializeXml($responseString);
  2092. $errorNo = $parser->deserializedResponse['ErrorNo'];
  2093. $errorDesc = $parser->deserializedResponse['ErrorDesc'];
  2094. $authStatus = $parser->deserializedResponse['PAResStatus'];
  2095. $sigStatus = $parser->deserializedResponse['SignatureVerification'];
  2096. $xid = $parser->deserializedResponse['Xid'];
  2097. $cavv = $parser->deserializedResponse['Cavv'];
  2098. $eci = $parser->deserializedResponse['EciFlag'];
  2099. // default the continue flag to 'N'
  2100. $continue_flag = 'N';
  2101. if ($errorNo == 0) {
  2102. if (strcasecmp($authStatus, 'Y') == 0 || strcasecmp($authStatus, 'A') == 0) {
  2103. $continue_flag = 'Y';
  2104. } else if (strcasecmp($authStatus, 'N') == 0) {
  2105. $continue_flag = 'N';
  2106. } else if (strcasecmp($authStatus, 'U') == 0) {
  2107. if (strcasecmp(MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ, 'No') == 0) {
  2108. $this->zcLog('Cardinal Auth 3', 'Business rule in effect (not requiring chargeback protection), so setting to continue to Y');
  2109. $continue_flag = 'Y';
  2110. }
  2111. }
  2112. } else {
  2113. $this->zcLog('Cardinal Auth 4', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_authenticate returned an error - ' . $errorNo . ' - ' . $errorDesc);
  2114. $continue_flag = 'N';
  2115. }
  2116. if ($continue_flag =='Y' && strcasecmp($sigStatus, 'N') == 0) {
  2117. // Signature status is 'N', do not continue
  2118. $continue_flag = 'N';
  2119. }
  2120. if ($continue_flag == 'Y') {
  2121. // For validation/security purposes, mark the session that the
  2122. // authentication result was acceptable.
  2123. $_SESSION['3Dsecure_authentication_attempted'] = 'Y';
  2124. } else {
  2125. // For validation/security purposes, mark the session that the
  2126. // authentication result was not acceptable.
  2127. unset($_SESSION['3Dsecure_authentication_attempted']);
  2128. }
  2129. $result = array('continue_flag' => $continue_flag,
  2130. 'auth_status' => $authStatus,
  2131. 'sig_status' => $sigStatus,
  2132. 'error_no' => $errorNo,
  2133. 'error_desc' => $errorDesc,
  2134. 'auth_xid' => $xid,
  2135. 'auth_cavv' => $cavv,
  2136. 'auth_eci' => $eci,
  2137. 'cc3d_card_number' => $parser->deserializedResponse['CardNumber'],
  2138. 'cc3d_checkcode' => $parser->deserializedResponse['CardCode'],
  2139. 'cc3d_exp_month' => $parser->deserializedResponse['CardExpMonth'],
  2140. 'cc3d_exp_year' => $parser->deserializedResponse['CardExpYear'],
  2141. 'cc3d_merchantdata' => $parser->deserializedResponse['MerchantData']);
  2142. return $result;
  2143. }
  2144. /////////////////////////////////////////////////////////////////////////////////////////////
  2145. // Function sendHttp(url, data)
  2146. //
  2147. // HTTP POST the form payload to the url using cURL.
  2148. // form payload according to the Centinel XML Message APIs. The form payload is returned from
  2149. // the function.
  2150. /////////////////////////////////////////////////////////////////////////////////////////////
  2151. function send3DSecureHttp($url, $data, $debugData) {
  2152. // verify that the URL uses a supported protocol.
  2153. if ((strpos($url, "http://")=== 0) || (strpos($url, "https://")=== 0)) {
  2154. // create a new cURL resource and set params
  2155. $ch = curl_init($url);
  2156. curl_setopt($ch, CURLOPT_POST,1);
  2157. curl_setopt($ch, CURLOPT_POSTFIELDS, "cmpi_msg=".urlencode($data));
  2158. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  2159. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  2160. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  2161. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  2162. // Execute the request.
  2163. $result = curl_exec($ch);
  2164. $succeeded = curl_errno($ch) == 0 ? true : false;
  2165. $error = curl_errno($ch) . '-' . curl_error($ch);
  2166. // close cURL resource, and free up system resources
  2167. curl_close($ch);
  2168. // If Communication was not successful set error result
  2169. if (!$succeeded) {
  2170. $this->zcLog('Cardinal Send 1', '[' . zen_session_id() . '] Cardinal Centinel - ' . CENTINEL_ERROR_CODE_8030_DESC);
  2171. $this->zcLog('Cardinal Send 2', '[' . zen_session_id() . '] Centinel Request: ' . $debugData);
  2172. $this->zcLog('Cardinal Send 3', '[' . zen_session_id() . '] Centinel Response: ' . $result);
  2173. $result = $this->setErrorResponse(CENTINEL_ERROR_CODE_8030, CENTINEL_ERROR_CODE_8030_DESC);
  2174. $errorText = CENTINEL_ERROR_CODE_8030 . ' - ' . CENTINEL_ERROR_CODE_8030_DESC;
  2175. $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  2176. if ($error != '-') $errorText .= "\n\nCURL error: " . $error;
  2177. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_8030_DESC . ' (' . CENTINEL_ERROR_CODE_8030 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  2178. } else if (strpos($result, "<CardinalMPI>") === false) {
  2179. // Assert that we received an expected Centinel Message in response.
  2180. $this->zcLog('Cardinal Send 4', '[' . zen_session_id() . '] Cardinal Centinel - ' . CENTINEL_ERROR_CODE_8010_DESC);
  2181. $this->zcLog('Cardinal Send 5', '[' . zen_session_id() . '] Centinel Request: ' . $debugData);
  2182. $this->zcLog('Cardinal Send 6', '[' . zen_session_id() . '] Centinel Response: ' . $result);
  2183. $result = $this->setErrorResponse(CENTINEL_ERROR_CODE_8010, CENTINEL_ERROR_CODE_8010_DESC);
  2184. $errorText = CENTINEL_ERROR_CODE_8010 . ' - ' . CENTINEL_ERROR_CODE_8010_DESC;
  2185. $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  2186. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_8010_DESC . ' (' . CENTINEL_ERROR_CODE_8010 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  2187. } else {
  2188. // Check whether the merchant has a properly configured 3D-Secure account
  2189. if (strpos($result, "<ErrorNo>4243") > 0) {
  2190. $this->zcLog('Cardinal Send 4', '[' . zen_session_id() . '] Cardinal Centinel - ' . CENTINEL_ERROR_CODE_4243_DESC);
  2191. $this->zcLog('Cardinal Send 5', '[' . zen_session_id() . '] Centinel Request: ' . $debugData);
  2192. $this->zcLog('Cardinal Send 6', '[' . zen_session_id() . '] Centinel Response: ' . $result);
  2193. $result = $this->setErrorResponse(CENTINEL_ERROR_CODE_4243, CENTINEL_ERROR_CODE_4243_DESC);
  2194. $errorText = CENTINEL_ERROR_CODE_4243 . ' - ' . CENTINEL_ERROR_CODE_4243_DESC;
  2195. $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  2196. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_4243_DESC . ' (' . CENTINEL_ERROR_CODE_4243 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  2197. }
  2198. }
  2199. } else {
  2200. $this->zcLog('Cardinal Send 7', '[' . zen_session_id() . '] Cardinal Centinel - ' . CENTINEL_ERROR_CODE_8000_DESC . ' - ' . $url);
  2201. $result = $this->setErrorResponse(CENTINEL_ERROR_CODE_8000, CENTINEL_ERROR_CODE_8000_DESC);
  2202. $errorText = CENTINEL_ERROR_CODE_8000 . ' - ' . CENTINEL_ERROR_CODE_8000_DESC;
  2203. $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
  2204. zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_8000_DESC . ' (' . CENTINEL_ERROR_CODE_8000 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
  2205. }
  2206. return $result;
  2207. }
  2208. /////////////////////////////////////////////////////////////////////////////////////////////
  2209. // Function escapeXML(value)
  2210. //
  2211. // Escaped string converting all '&' to '&amp;' and all '<' to '&lt'. Return the escaped value.
  2212. /////////////////////////////////////////////////////////////////////////////////////////////
  2213. function escapeXML($elementValue){
  2214. $escapedValue = str_replace("&", "&amp;", trim($elementValue));
  2215. $escapedValue = str_replace("<", "&lt;", $escapedValue);
  2216. return $escapedValue;
  2217. }
  2218. /////////////////////////////////////////////////////////////////////////////////////////////
  2219. // Function setErrorResponse(errorNo, errorDesc)
  2220. //
  2221. // Initialize an Error response to ensure that parsing will be handled properly.
  2222. /////////////////////////////////////////////////////////////////////////////////////////////
  2223. function setErrorResponse($errorNo, $errorDesc) {
  2224. $resultText = "<CardinalMPI>";
  2225. $resultText = $resultText."<ErrorNo>".($errorNo)."</ErrorNo>" ;
  2226. $resultText = $resultText."<ErrorDesc>".($errorDesc)."</ErrorDesc>" ;
  2227. $resultText = $resultText."</CardinalMPI>";
  2228. return $resultText;
  2229. }
  2230. function get_authentication_error() {
  2231. $this->clear_3DSecure_session_vars();
  2232. return CENTINEL_AUTHENTICATION_ERROR;
  2233. }
  2234. // Convert Currency to ISO4217 3 digit code
  2235. // If curr is char code will convert to digit code
  2236. // If curr is digits less than 3, will pad with leading zeros
  2237. // If we are unable to format curr, curr is returned unformatted.
  2238. // MAPs will return the appropriate error code.
  2239. function getISOCurrency($curr) {
  2240. $out = "";
  2241. if(ctype_digit($curr) || is_int($curr)) {
  2242. $numCurr = $curr + 0;
  2243. if($numCurr < 10) {
  2244. $out = "00" . $numCurr;
  2245. } else if ($numCurr < 100) {
  2246. $out = "0" . $numCurr;
  2247. } else {
  2248. //Assume 3 digits (if greater let MAPs handle error)
  2249. $out = "" . $numCurr;
  2250. }
  2251. } else {
  2252. // Convert char to digit
  2253. $curCode = Array();
  2254. $curCode["AUD"]="036";
  2255. $curCode["CAD"]="124";
  2256. $curCode["CHF"]="756";
  2257. $curCode["CZK"]="203";
  2258. $curCode["DKK"]="208";
  2259. $curCode["EUR"]="978";
  2260. $curCode["GBP"]="826";
  2261. $curCode["HUF"]="348";
  2262. $curCode["JPY"]="392";
  2263. $curCode["NOK"]="578";
  2264. $curCode["NZD"]="554";
  2265. $curCode["PLN"]="985";
  2266. $curCode["SEK"]="752";
  2267. $curCode["SGD"]="702";
  2268. $curCode["USD"]="840";
  2269. $out = $curCode[$curr];
  2270. }
  2271. return $out;
  2272. }
  2273. // Format Amount to rawamount
  2274. // Rawamount does not contain a decimal and is rounded and padded
  2275. // based on the currency exponenet value
  2276. // amount - Double floating point
  2277. // curr - ISO4217 Currency code, 3char or 3digit
  2278. function formatRawAmount($amount, $curr) {
  2279. $dblAmount = $amount + 0.0;
  2280. // Build Currency format table
  2281. $curFormat = Array();
  2282. $curFormat["036"]=2;
  2283. $curFormat["124"]=2;
  2284. $curFormat["203"]=2;
  2285. $curFormat["208"]=2;
  2286. $curFormat["348"]=2;
  2287. $curFormat["392"]=0;
  2288. $curFormat["554"]=2;
  2289. $curFormat["578"]=2;
  2290. $curFormat["702"]=2;
  2291. $curFormat["752"]=2;
  2292. $curFormat["756"]=2;
  2293. $curFormat["826"]=2;
  2294. $curFormat["840"]=2;
  2295. $curFormat["978"]=2;
  2296. $curFormat["985"]=2;
  2297. $digCurr = $this->getISOCurrency("" . $curr);
  2298. $exponent = $curFormat[$digCurr];
  2299. $strAmount = "" . Round($dblAmount, $exponent);
  2300. $strRetVal = "" . $strAmount;
  2301. // decimal position
  2302. $curpos = strpos($strRetVal, ".");
  2303. // Pad with zeros
  2304. if($curpos == true) {
  2305. $padCount = $exponent - (strlen($strRetVal) - $curpos - 1);
  2306. for($i=0;$i<$padCount;$i++) {
  2307. $strRetVal .= "0";
  2308. }
  2309. } else {
  2310. $padCount = $exponent;
  2311. for($i=0;$i<$padCount;$i++) {
  2312. $strRetVal .= "0";
  2313. }
  2314. }
  2315. if($curpos !== false) {
  2316. $strRetVal = substr($strRetVal, 0, $curpos) . substr($strRetVal, $curpos+1);
  2317. }
  2318. return $strRetVal;
  2319. }
  2320. function requiresLookup($info) {
  2321. if (is_numeric($info)) {
  2322. $cardType = $this->determineCardType($info);
  2323. } else {
  2324. $cardType = $info;
  2325. }
  2326. if (in_array(strtoupper($cardType), array('VISA', 'MASTERCARD', 'JCB', 'MAESTRO'))) {
  2327. return true;
  2328. } else {
  2329. return false;
  2330. }
  2331. }
  2332. function determineCardType($cardNumber) {
  2333. $cardNumber = preg_replace('/[^0-9]/', '', $cardNumber);
  2334. // NOTE: We check Solo before Maestro, and Maestro/Switch *before* we check Visa/Mastercard, so we don't have to rule-out numerous types from V/MC matching rules.
  2335. if (preg_match('/^(6334[5-9][0-9]|6767[0-9]{2})[0-9]{10}([0-9]{2,3}?)?$/', $cardNumber)) {
  2336. $cardType = "SOLO";
  2337. } else if (preg_match('/^(49369[8-9]|490303|6333[0-4][0-9]|6759[0-9]{2}|5[0678][0-9]{4}|6[0-9][02-9][02-9][0-9]{2})[0-9]{6,13}?$/', $cardNumber)) {
  2338. $cardType = "MAESTRO";
  2339. } else if (preg_match('/^(49030[2-9]|49033[5-9]|4905[0-9]{2}|49110[1-2]|49117[4-9]|49918[0-2]|4936[0-9]{2}|564182|6333[0-4][0-9])[0-9]{10}([0-9]{2,3}?)?$/', $cardNumber)) {
  2340. $cardType = "MAESTRO"; // SWITCH is now Maestro
  2341. } elseif (preg_match('/^4[0-9]{12}([0-9]{3})?$/', $cardNumber)) {
  2342. $cardType = 'VISA';
  2343. } elseif (preg_match('/^5[1-5][0-9]{14}$/', $cardNumber)) {
  2344. $cardType = 'MASTERCARD';
  2345. } elseif (preg_match('/^3[47][0-9]{13}$/', $cardNumber)) {
  2346. $cardType = 'AMEX';
  2347. } elseif (preg_match('/^3(0[0-5]|[68][0-9])[0-9]{11}$/', $cardNumber)) {
  2348. $cardType = 'DINERS CLUB';
  2349. } elseif (preg_match('/^(6011[0-9]{12}|622[1-9][0-9]{12}|64[4-9][0-9]{13}|65[0-9]{14})$/', $cardNumber)) {
  2350. $cardType = 'DISCOVER';
  2351. } elseif (preg_match('/^(35(28|29|[3-8][0-9])[0-9]{12}|2131[0-9]{11}|1800[0-9]{11})$/', $cardNumber)) {
  2352. $cardType = "JCB";
  2353. } else {
  2354. $cardType = "UNKNOWN";
  2355. }
  2356. return $cardType;
  2357. }
  2358. }
  2359. class CardinalXMLParser{
  2360. var $xml_parser;
  2361. var $deseralizedResponse;
  2362. var $elementName;
  2363. var $elementValue;
  2364. /////////////////////////////////////////////////////////////////////////////////////////////
  2365. // Function CardinalXMLParser()
  2366. //
  2367. // Initialize the XML parser.
  2368. /////////////////////////////////////////////////////////////////////////////////////////////
  2369. function CardinalXMLParser() {
  2370. $this->xml_parser = xml_parser_create();
  2371. }
  2372. /////////////////////////////////////////////////////////////////////////////////////////////
  2373. // Function startElement(parser, name, attribute)
  2374. //
  2375. // Start Tag Element Handler
  2376. /////////////////////////////////////////////////////////////////////////////////////////////
  2377. function startElement($parser, $name, $attrs='') {
  2378. $this->elementName = $name;
  2379. }
  2380. /////////////////////////////////////////////////////////////////////////////////////////////
  2381. // Function elementData(parser, data)
  2382. //
  2383. // Element Data Handler
  2384. /////////////////////////////////////////////////////////////////////////////////////////////
  2385. function elementData($parser, $data) {
  2386. $this->elementValue .= $data;
  2387. }
  2388. /////////////////////////////////////////////////////////////////////////////////////////////
  2389. // Function endElement(name, value)
  2390. //
  2391. // End Tag Element Handler
  2392. /////////////////////////////////////////////////////////////////////////////////////////////
  2393. function endElement($parser, $name) {
  2394. if (substr($this->elementValue, 0, 1) == "\n") $this->elementValue = substr($this->elementValue, 1);
  2395. $this->deserializedResponse[$this->elementName]= $this->elementValue;
  2396. $this->elementName = "";
  2397. $this->elementValue = "";
  2398. }
  2399. /////////////////////////////////////////////////////////////////////////////////////////////
  2400. // Function deserialize(xmlString)
  2401. //
  2402. // Deserialize the XML reponse message and add each element to the deserializedResponse collection.
  2403. // Once complete, then each element reference will be available using the getValue function.
  2404. /////////////////////////////////////////////////////////////////////////////////////////////
  2405. function deserializeXml($responseString) {
  2406. xml_set_object($this->xml_parser, $this);
  2407. xml_parser_set_option($this->xml_parser,XML_OPTION_CASE_FOLDING,FALSE);
  2408. xml_set_element_handler($this->xml_parser, "startElement", "endElement");
  2409. xml_set_character_data_handler($this->xml_parser, "elementData");
  2410. if (!xml_parse($this->xml_parser, $responseString)) {
  2411. $this->deserializedResponse["ErrorNo"]= CENTINEL_ERROR_CODE_8020;
  2412. $this->deserializedResponse["ErrorDesc"]= CENTINEL_ERROR_CODE_8020_DESC;
  2413. }
  2414. xml_parser_free($this->xml_parser);
  2415. }
  2416. }