Skip navigation
Help

uc_paypal.module

  1. drupal
    1. 6 ubercart/payment/uc_paypal/uc_paypal.module
    2. 7 ubercart/payment/uc_paypal/uc_paypal.module

Integrates various PayPal payment services and Instant Payment Notifications (IPN) with Ubercart!

You should turn on Instant Payment Notifications in your PayPal profile and set the IPN URL to http://{yoursite.com}/uc_paypal/ipn. See https://drupal.org/node/1311198 for further information.

If you have not yet signed up for your PayPal account, please support Ubercart by using the following link. Thank you!

https://www.paypal.com/us/mrb/pal=6NXAPNGSS6DFJ

Functions & methods

NameDescription
uc_payment_method_paypal_ecHandles the Express Checkout payment method.
uc_payment_method_paypal_wpsHandles the Website Payments Standard payment method.
uc_paypal_api_requestSends a request to PayPal and returns a response array.
uc_paypal_ec_checkoutRedirects if a customer selects PayPal Express Checkout as a payment method.
uc_paypal_ec_formReturns the form for Express Checkout Shortcut Flow.
uc_paypal_ec_form_submitSubmit handler for uc_paypal_ec_form().
uc_paypal_ec_submit_form_submitAdditional submit handler for uc_cart_checkout_review_form().
uc_paypal_form_uc_cart_checkout_form_alterImplements hook_form_FORM_ID_alter() for uc_cart_checkout_form().
uc_paypal_form_uc_cart_checkout_review_form_alterImplements hook_form_FORM_ID_alter() for uc_cart_checkout_review_form().
uc_paypal_menuImplements hook_menu().
uc_paypal_uc_payment_gatewayImplements hook_uc_payment_gateway().
uc_paypal_uc_payment_methodImplements hook_uc_payment_method().
uc_paypal_wpp_chargeProcesses a credit card payment through Website Payments Pro.
uc_paypal_wpp_settings_formSettings for Website Payments Pro on the credit card gateways form.
uc_paypal_wps_formReturns the form elements for the Website Payments Standard form.
_uc_paypal_avscode_messageReturns a human readable message for the AVS code.
_uc_paypal_build_error_messagesBuilds error message(s) from PayPal failure responses.
_uc_paypal_card_typeReturns the PayPal approved credit card type for a card number.
_uc_paypal_currency_arrayReturns an array of possible currency codes.
_uc_paypal_cvvmatch_messageReturns a human readable message for the CVV2 match code.
_uc_paypal_nvp_to_arrayTurns PayPal's NVP response to an API call into an associative array.
_uc_paypal_pending_messageReturns a message for the pending reason of a PayPal payment.
_uc_paypal_product_detailsReturns the description and subtotal of the products on an order.
_uc_paypal_reversal_messageReturns a message for the reason code of a PayPal reversal.

File

ubercart/payment/uc_paypal/uc_paypal.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Integrates various PayPal payment services and Instant Payment Notifications
  5. * (IPN) with Ubercart!
  6. *
  7. * You should turn on Instant Payment Notifications in your PayPal profile and
  8. * set the IPN URL to http://{yoursite.com}/uc_paypal/ipn. See
  9. * https://drupal.org/node/1311198 for further information.
  10. *
  11. * If you have not yet signed up for your PayPal account, please support
  12. * Ubercart by using the following link. Thank you!
  13. *
  14. * https://www.paypal.com/us/mrb/pal=6NXAPNGSS6DFJ
  15. */
  16. /**
  17. * Implements hook_menu().
  18. */
  19. function uc_paypal_menu() {
  20. // Always accessible, helps for testing while site is offline.
  21. $items['uc_paypal/ipn'] = array(
  22. 'title' => 'PayPal IPN',
  23. 'page callback' => 'uc_paypal_ipn',
  24. 'access callback' => TRUE,
  25. 'type' => MENU_CALLBACK,
  26. 'file' => 'uc_paypal.pages.inc',
  27. );
  28. // Callback functions for Express Checkout.
  29. $items['cart/echeckout/selected'] = array(
  30. 'title' => 'Review order',
  31. 'page callback' => 'uc_paypal_ec_review_redirect',
  32. 'access arguments' => array('access content'),
  33. 'type' => MENU_CALLBACK,
  34. 'file' => 'uc_paypal.pages.inc',
  35. );
  36. $items['cart/echeckout/review'] = array(
  37. 'title' => 'Review payment',
  38. 'page callback' => 'uc_paypal_ec_review',
  39. 'access arguments' => array('access content'),
  40. 'type' => MENU_CALLBACK,
  41. 'file' => 'uc_paypal.pages.inc',
  42. );
  43. $items['cart/echeckout/submit'] = array(
  44. 'title' => 'Submit order',
  45. 'page callback' => 'uc_paypal_ec_submit',
  46. 'access arguments' => array('access content'),
  47. 'type' => MENU_CALLBACK,
  48. 'file' => 'uc_paypal.pages.inc',
  49. );
  50. // Callback functions for Website Payments Standard.
  51. $items['uc_paypal/wps/complete/%uc_order'] = array(
  52. 'title' => 'PayPal payment complete',
  53. 'page callback' => 'uc_paypal_complete',
  54. 'page arguments' => array(3),
  55. 'access arguments' => array('access content'),
  56. 'type' => MENU_CALLBACK,
  57. 'file' => 'uc_paypal.pages.inc',
  58. );
  59. $items['uc_paypal/wps/cancel'] = array(
  60. 'title' => 'PayPal payment canceled',
  61. 'page callback' => 'uc_paypal_cancel',
  62. 'access arguments' => array('access content'),
  63. 'type' => MENU_CALLBACK,
  64. 'file' => 'uc_paypal.pages.inc',
  65. );
  66. return $items;
  67. }
  68. /**
  69. * Implements hook_form_FORM_ID_alter() for uc_cart_checkout_form().
  70. */
  71. function uc_paypal_form_uc_cart_checkout_form_alter(&$form, &$form_state, $form_id) {
  72. if (variable_get('uc_payment_method_paypal_ec_checkout', FALSE)) {
  73. $form['#submit'][] = 'uc_paypal_ec_checkout';
  74. }
  75. }
  76. /**
  77. * Implements hook_form_FORM_ID_alter() for uc_cart_checkout_review_form().
  78. */
  79. function uc_paypal_form_uc_cart_checkout_review_form_alter(&$form, &$form_state, $form_id) {
  80. if (!empty($_SESSION['TOKEN'])) {
  81. $form['#submit'][] = 'uc_paypal_ec_submit_form_submit';
  82. }
  83. }
  84. /**
  85. * Implements hook_uc_payment_gateway().
  86. */
  87. function uc_paypal_uc_payment_gateway() {
  88. if (!module_exists('uc_credit')) {
  89. drupal_set_message(t('You must <a href="@modules">enable the Credit Card module</a> to use PayPal Website Payments Pro.', array('@modules' => url('admin/modules', array('fragment' => 'edit-modules-ubercart-payment')))), 'warning');
  90. return;
  91. }
  92. $gateways['paypal_wpp'] = array(
  93. 'title' => t('PayPal Website Payments Pro'),
  94. 'description' => t('Process credit card payments using Website Payments Pro.'),
  95. 'settings' => 'uc_paypal_wpp_settings_form',
  96. 'credit' => 'uc_paypal_wpp_charge',
  97. 'credit_txn_types' => array(UC_CREDIT_AUTH_ONLY, UC_CREDIT_PRIOR_AUTH_CAPTURE, UC_CREDIT_AUTH_CAPTURE),
  98. );
  99. return $gateways;
  100. }
  101. /**
  102. * Implements hook_uc_payment_method().
  103. */
  104. function uc_paypal_uc_payment_method() {
  105. $title1 = '<img src="https://www.paypal.com/en_US/i/logo/PayPal_mark_37x23.gif" alt="PayPal" class="uc-credit-cctype" />'
  106. . ' ' . t('PayPal - pay without sharing your financial information.');
  107. $title2 = '<br /><span id="paypal-includes">' . t('Includes:');
  108. $cc_types = array(
  109. 'visa' => t('Visa'),
  110. 'mastercard' => t('MasterCard'),
  111. 'discover' => t('Discover'),
  112. 'amex' => t('American Express'),
  113. 'echeck' => t('eCheck'),
  114. );
  115. foreach ($cc_types as $type => $label) {
  116. $title2 .= ' ' . theme('image', array(
  117. 'path' => drupal_get_path('module', 'uc_credit') . '/images/' . $type . '.gif',
  118. 'alt' => $label,
  119. 'attributes' => array('class' => array('uc-credit-cctype', 'uc-credit-cctype-' . $type)),
  120. ));
  121. }
  122. $title2 .= ' <img src="https://www.paypal.com/en_US/i/logo/PayPal_mark_37x23.gif" alt="PayPal" class="uc-credit-cctype" /></span>';
  123. $methods[] = array(
  124. 'id' => 'paypal_wps',
  125. 'name' => t('PayPal Website Payments Standard'),
  126. 'title' => $title1 . $title2,
  127. 'review' => t('PayPal'),
  128. 'desc' => t('Redirect users to submit payments through PayPal.'),
  129. 'callback' => 'uc_payment_method_paypal_wps',
  130. 'redirect' => 'uc_paypal_wps_form',
  131. 'weight' => 1,
  132. 'checkout' => FALSE,
  133. 'no_gateway' => TRUE,
  134. );
  135. $methods[] = array(
  136. 'id' => 'paypal_ec',
  137. 'name' => t('PayPal Express Checkout'),
  138. 'title' => $title1,
  139. 'review' => t('PayPal'),
  140. 'desc' => t('Complete orders through PayPal Express Checkout.'),
  141. 'callback' => 'uc_payment_method_paypal_ec',
  142. 'weight' => 1,
  143. 'checkout' => FALSE,
  144. 'no_gateway' => TRUE,
  145. 'express' => 'uc_paypal_ec_form',
  146. );
  147. return $methods;
  148. }
  149. /**
  150. * Settings for Website Payments Pro on the credit card gateways form.
  151. *
  152. * This provides a subset of the Express Checkout settings.
  153. */
  154. function uc_paypal_wpp_settings_form($form, &$form_state) {
  155. $order = NULL;
  156. $form = uc_payment_method_paypal_ec('settings', $order);
  157. unset($form['ec']);
  158. return $form;
  159. }
  160. /**
  161. * Processes a credit card payment through Website Payments Pro.
  162. */
  163. function uc_paypal_wpp_charge($order_id, $amount, $data) {
  164. global $user;
  165. $order = uc_order_load($order_id);
  166. if ($data['txn_type'] == UC_CREDIT_PRIOR_AUTH_CAPTURE) {
  167. $nvp_request = array(
  168. 'METHOD' => 'DoCapture',
  169. 'AUTHORIZATIONID' => $data['auth_id'],
  170. 'AMT' => uc_currency_format($amount, FALSE, FALSE, '.'),
  171. 'CURRENCYCODE' => variable_get('uc_paypal_wpp_currency', 'USD'),
  172. 'COMPLETETYPE' => 'Complete',
  173. );
  174. }
  175. else {
  176. list($desc, $subtotal) = _uc_paypal_product_details($order->products);
  177. if (intval($order->payment_details['cc_exp_month']) < 10) {
  178. $expdate = '0' . $order->payment_details['cc_exp_month'] . $order->payment_details['cc_exp_year'];
  179. }
  180. else {
  181. $expdate = $order->payment_details['cc_exp_month'] . $order->payment_details['cc_exp_year'];
  182. }
  183. $cc_type = NULL;
  184. if (isset($order->payment_details['cc_type'])) {
  185. switch (strtolower($order->payment_details['cc_type'])) {
  186. case 'amex':
  187. case 'american express':
  188. $cc_type = 'Amex';
  189. break;
  190. case 'visa':
  191. $cc_type = 'Visa';
  192. break;
  193. case 'mastercard':
  194. case 'master card':
  195. $cc_type = 'MasterCard';
  196. break;
  197. case 'discover':
  198. $cc_type = 'Discover';
  199. break;
  200. }
  201. }
  202. if (is_null($cc_type)) {
  203. $cc_type = _uc_paypal_card_type($order->payment_details['cc_number']);
  204. if ($cc_type === FALSE) {
  205. drupal_set_message(t('The credit card type did not pass validation.'), 'error');
  206. watchdog('uc_paypal', 'Could not figure out cc type: @number / @type', array('@number' => $order->payment_details['cc_number'], '@type' => $order->payment_details['cc_type']), WATCHDOG_ERROR);
  207. return array('success' => FALSE);
  208. }
  209. }
  210. $billing_country = uc_get_country_data(array('country_id' => $order->billing_country));
  211. if ($billing_country === FALSE) {
  212. $billing_country = array(0 => array('country_iso_code_2' => 'US'));
  213. }
  214. $delivery_country = uc_get_country_data(array('country_id' => $order->delivery_country));
  215. if ($delivery_country === FALSE) {
  216. $delivery_country = array(0 => array('country_iso_code_2' => 'US'));
  217. }
  218. // Paypal doesn't accept IPv6 addresses.
  219. $ip_address = ltrim(ip_address(), '::ffff:');
  220. $nvp_request = array(
  221. 'METHOD' => 'DoDirectPayment',
  222. 'PAYMENTACTION' => $data['txn_type'] == UC_CREDIT_AUTH_ONLY ? 'Authorization' : 'Sale',
  223. 'IPADDRESS' => $ip_address,
  224. 'AMT' => uc_currency_format($amount, FALSE, FALSE, '.'),
  225. 'CREDITCARDTYPE' => $cc_type,
  226. 'ACCT' => $order->payment_details['cc_number'],
  227. 'EXPDATE' => $expdate,
  228. 'CVV2' => $order->payment_details['cc_cvv'],
  229. 'FIRSTNAME' => substr($order->billing_first_name, 0, 25),
  230. 'LASTNAME' => substr($order->billing_last_name, 0, 25),
  231. 'STREET' => substr($order->billing_street1, 0, 100),
  232. 'STREET2' => substr($order->billing_street2, 0, 100),
  233. 'CITY' => substr($order->billing_city, 0, 40),
  234. 'STATE' => uc_get_zone_code($order->billing_zone),
  235. 'ZIP' => $order->billing_postal_code,
  236. 'COUNTRYCODE' => $billing_country[0]['country_iso_code_2'],
  237. 'CURRENCYCODE' => variable_get('uc_paypal_wpp_currency', 'USD'),
  238. 'DESC' => substr($desc, 0, 127),
  239. 'INVNUM' => $order_id . '-' . REQUEST_TIME,
  240. 'BUTTONSOURCE' => 'Ubercart_ShoppingCart_DP_US',
  241. 'NOTIFYURL' => url('uc_paypal/ipn/' . $order->order_id, array('absolute' => TRUE)),
  242. 'EMAIL' => substr($order->primary_email, 0, 127),
  243. 'PHONENUM' => substr($order->billing_phone, 0, 20),
  244. );
  245. if (uc_order_is_shippable($order) && !empty($order->delivery_first_name)) {
  246. $shipdata = array(
  247. 'SHIPTONAME' => substr($order->delivery_first_name . ' ' . $order->delivery_last_name, 0, 25),
  248. 'SHIPTOSTREET' => substr($order->delivery_street1, 0, 100),
  249. 'SHIPTOSTREET2' => substr($order->delivery_street2, 0, 100),
  250. 'SHIPTOCITY' => substr($order->delivery_city, 0, 40),
  251. 'SHIPTOSTATE' => uc_get_zone_code($order->delivery_zone),
  252. 'SHIPTOZIP' => $order->delivery_postal_code,
  253. 'SHIPTOCOUNTRYCODE' => $delivery_country[0]['country_iso_code_2'],
  254. );
  255. $nvp_request += $shipdata;
  256. }
  257. if (variable_get('uc_credit_cvv_enabled', TRUE)) {
  258. $nvp_request['CVV2'] = $order->payment_details['cc_cvv'];
  259. }
  260. }
  261. $nvp_response = uc_paypal_api_request($nvp_request, variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'));
  262. $types = uc_credit_transaction_types();
  263. switch ($nvp_response['ACK']) {
  264. case 'SuccessWithWarning':
  265. watchdog('uc_payment', '<b>@type succeeded with a warning.</b>!paypal_message',
  266. array(
  267. '!paypal_message' => _uc_paypal_build_error_messages($nvp_response),
  268. '@type' => $types[$data['txn_type']],
  269. ),
  270. WATCHDOG_WARNING,
  271. l(t('view order'), 'admin/store/orders/' . $order_id)
  272. );
  273. // Fall through.
  274. case 'Success':
  275. $message = t('<b>@type</b><br /><b>Success: </b>@amount @currency', array('@type' => $types[$data['txn_type']], '@amount' => uc_currency_format($nvp_response['AMT'], FALSE), '@currency' => $nvp_response['CURRENCYCODE']));
  276. if ($data['txn_type'] != UC_CREDIT_PRIOR_AUTH_CAPTURE) {
  277. $message .= '<br />' . t('<b>Address:</b> @avscode', array('@avscode' => _uc_paypal_avscode_message($nvp_response['AVSCODE'])));
  278. if (variable_get('uc_credit_cvv_enabled', TRUE)) {
  279. $message .= '<br />' . t('<b>CVV2:</b> @cvvmatch', array('@cvvmatch' => _uc_paypal_cvvmatch_message($nvp_response['CVV2MATCH'])));
  280. }
  281. }
  282. $result = array(
  283. 'success' => TRUE,
  284. 'comment' => t('PayPal transaction ID: @transactionid', array('@transactionid' => $nvp_response['TRANSACTIONID'])),
  285. 'message' => $message,
  286. 'data' => check_plain($nvp_response['TRANSACTIONID']),
  287. 'uid' => $user->uid,
  288. );
  289. // If this was an authorization only transaction...
  290. if ($data['txn_type'] == UC_CREDIT_AUTH_ONLY) {
  291. // Log the authorization to the order.
  292. uc_credit_log_authorization($order_id, $nvp_response['TRANSACTIONID'], $nvp_response['AMT']);
  293. }
  294. elseif ($data['txn_type'] == UC_CREDIT_PRIOR_AUTH_CAPTURE) {
  295. uc_credit_log_prior_auth_capture($order_id, $data['auth_id']);
  296. }
  297. // Log the IPN to the database.
  298. db_insert('uc_payment_paypal_ipn')
  299. ->fields(array(
  300. 'order_id' => $order->order_id,
  301. 'txn_id' => $nvp_response['TRANSACTIONID'],
  302. 'txn_type' => 'web_accept',
  303. 'mc_gross' => $amount,
  304. 'status' => 'Completed',
  305. 'payer_email' => $order->primary_email,
  306. 'received' => REQUEST_TIME,
  307. ))
  308. ->execute();
  309. break;
  310. case 'FailureWithWarning':
  311. // Fall through.
  312. case 'Failure':
  313. $message = t('<b>@type failed.</b>', array('@type' => $types[$data['txn_type']])) . _uc_paypal_build_error_messages($nvp_response);
  314. $result = array(
  315. 'success' => FALSE,
  316. 'message' => $message,
  317. 'uid' => $user->uid,
  318. );
  319. break;
  320. default:
  321. $message = t('Unexpected acknowledgement status: @status', array('@status' => $nvp_response['ACK']));
  322. $result = array(
  323. 'success' => NULL,
  324. 'message' => $message,
  325. 'uid' => $user->uid,
  326. );
  327. break;
  328. }
  329. uc_order_comment_save($order_id, $user->uid, $message, 'admin');
  330. // Don't log this as a payment money wasn't actually captured.
  331. if (in_array($data['txn_type'], array(UC_CREDIT_AUTH_ONLY))) {
  332. $result['log_payment'] = FALSE;
  333. }
  334. return $result;
  335. }
  336. /**
  337. * Builds error message(s) from PayPal failure responses.
  338. */
  339. function _uc_paypal_build_error_messages($nvp_response) {
  340. $code = 0;
  341. $message = '';
  342. while (array_key_exists('L_SEVERITYCODE' . $code, $nvp_response)) {
  343. $message .= '<br /><b>' . check_plain($nvp_response['L_SEVERITYCODE' . $code]) . ':</b> ' . check_plain($nvp_response['L_ERRORCODE' . $code]) . ': ' . check_plain($nvp_response['L_LONGMESSAGE' . $code]);
  344. $code++;
  345. }
  346. return $message;
  347. }
  348. /**
  349. * Handles the Website Payments Standard payment method.
  350. */
  351. function uc_payment_method_paypal_wps($op, &$order) {
  352. switch ($op) {
  353. case 'order-view':
  354. $txn_id = db_query("SELECT txn_id FROM {uc_payment_paypal_ipn} WHERE order_id = :id ORDER BY received ASC", array(':id' => $order->order_id))->fetchField();
  355. if (empty($txn_id)) {
  356. $txn_id = t('Unknown');
  357. }
  358. $build['#markup'] = t('Transaction ID:<br />@txn_id', array('@txn_id' => $txn_id));
  359. return $build;
  360. case 'settings':
  361. $form['uc_paypal_wps_email'] = array(
  362. '#type' => 'textfield',
  363. '#title' => t('PayPal e-mail address'),
  364. '#description' => t('The e-mail address you use for the PayPal account you want to receive payments.'),
  365. '#default_value' => variable_get('uc_paypal_wps_email', ''),
  366. );
  367. $form['uc_paypal_wps_currency'] = array(
  368. '#type' => 'select',
  369. '#title' => t('Currency code'),
  370. '#description' => t('Transactions can only be processed in one of the listed currencies.'),
  371. '#options' => _uc_paypal_currency_array(),
  372. '#default_value' => variable_get('uc_paypal_wps_currency', 'USD'),
  373. );
  374. $form['uc_paypal_wps_language'] = array(
  375. '#type' => 'select',
  376. '#title' => t('PayPal login page language'),
  377. '#options' => drupal_map_assoc(array('AU', 'DE', 'FR', 'IT', 'GB', 'ES', 'US')),
  378. '#default_value' => variable_get('uc_paypal_wps_language', 'US'),
  379. );
  380. $form['uc_paypal_wps_server'] = array(
  381. '#type' => 'select',
  382. '#title' => t('PayPal server'),
  383. '#description' => t('Sign up for and use a Sandbox account for testing.'),
  384. '#options' => array(
  385. 'https://www.sandbox.paypal.com/cgi-bin/webscr' => ('Sandbox'),
  386. 'https://www.paypal.com/cgi-bin/webscr' => ('Live'),
  387. ),
  388. '#default_value' => variable_get('uc_paypal_wps_server', 'https://www.sandbox.paypal.com/cgi-bin/webscr'),
  389. );
  390. $form['uc_paypal_wps_payment_action'] = array(
  391. '#type' => 'select',
  392. '#title' => t('Payment action'),
  393. '#description' => t('"Complete sale" will authorize and capture the funds at the time the payment is processed.<br />"Authorization" will only reserve funds on the card to be captured later through your PayPal account.'),
  394. '#options' => array(
  395. 'Sale' => t('Complete sale'),
  396. 'Authorization' => t('Authorization'),
  397. ),
  398. '#default_value' => variable_get('uc_paypal_wps_payment_action', 'Sale'),
  399. );
  400. $form['uc_paypal_wps_cancel_return_url'] = array(
  401. '#type' => 'textfield',
  402. '#title' => t('Cancel return URL'),
  403. '#description' => t('Specify the path customers who cancel their PayPal WPS payment will be directed to when they return to your site.'),
  404. '#default_value' => variable_get('uc_paypal_wps_cancel_return_url', 'cart'),
  405. '#size' => 32,
  406. '#field_prefix' => url(NULL, array('absolute' => TRUE)) . (variable_get('clean_url', 0) ? '' : '?q='),
  407. );
  408. $form['uc_paypal_wps_submit_method'] = array(
  409. '#type' => 'radios',
  410. '#title' => t('PayPal cart submission method'),
  411. '#options' => array(
  412. 'single' => t('Submit the whole order as a single line item.'),
  413. 'itemized' => t('Submit an itemized order showing each product and description.'),
  414. ),
  415. '#default_value' => variable_get('uc_paypal_wps_submit_method', 'single'),
  416. );
  417. $form['uc_paypal_wps_no_shipping'] = array(
  418. '#type' => 'radios',
  419. '#title' => t('Shipping address prompt in PayPal'),
  420. '#options' => array(
  421. '1' => t('Do not show shipping address prompt at PayPal.'),
  422. '0' => t('Prompt customer to include a shipping address.'),
  423. '2' => t('Require customer to provide a shipping address.'),
  424. ),
  425. '#default_value' => variable_get('uc_paypal_wps_no_shipping', '1'),
  426. );
  427. $form['uc_paypal_wps_address_override'] = array(
  428. '#type' => 'checkbox',
  429. '#title' => t('Submit address information to PayPal to override PayPal stored addresses.'),
  430. '#description' => t('Works best with the first option above.'),
  431. '#default_value' => variable_get('uc_paypal_wps_address_override', TRUE),
  432. );
  433. $form['uc_paypal_wps_address_selection'] = array(
  434. '#type' => 'radios',
  435. '#title' => t('Sent address selection'),
  436. '#options' => array(
  437. 'billing' => t('Send billing address to PayPal.'),
  438. 'delivery' => t('Send shipping address to PayPal.'),
  439. ),
  440. '#default_value' => variable_get('uc_paypal_wps_address_selection', 'billing'),
  441. );
  442. $form['uc_paypal_wps_debug_ipn'] = array(
  443. '#type' => 'checkbox',
  444. '#title' => t('Show debug info in the logs for Instant Payment Notifications.'),
  445. '#default_value' => variable_get('uc_paypal_wps_debug_ipn', FALSE),
  446. );
  447. return $form;
  448. }
  449. }
  450. /**
  451. * Handles the Express Checkout payment method.
  452. */
  453. function uc_payment_method_paypal_ec($op, &$order) {
  454. switch ($op) {
  455. case 'order-view':
  456. $txn_id = db_query("SELECT txn_id FROM {uc_payment_paypal_ipn} WHERE order_id = :id ORDER BY received ASC", array(':id' => $order->order_id))->fetchField();
  457. if (empty($txn_id)) {
  458. $txn_id = t('Unknown');
  459. }
  460. $build['#markup'] = t('Transaction ID:<br />@txn_id', array('@txn_id' => $txn_id));
  461. return $build;
  462. case 'settings':
  463. $form['uc_paypal_wps_email'] = array(
  464. '#type' => 'textfield',
  465. '#title' => t('PayPal e-mail address'),
  466. '#description' => t('The e-mail address you use for the PayPal account you want to receive payments.'),
  467. '#default_value' => variable_get('uc_paypal_wps_email', ''),
  468. );
  469. // The DoDirectPayment API call allows fewer currencies than PayPal
  470. // in general.
  471. $form['uc_paypal_wpp_currency'] = array(
  472. '#type' => 'select',
  473. '#title' => t('Currency code'),
  474. '#description' => t('Transactions can only be processed in one of the listed currencies.'),
  475. '#options' => _uc_paypal_currency_array(),
  476. '#default_value' => variable_get('uc_paypal_wpp_currency', 'USD'),
  477. );
  478. $form['uc_paypal_wpp_server'] = array(
  479. '#type' => 'select',
  480. '#title' => t('API server'),
  481. '#description' => t('Sign up for and use a Sandbox account for testing.'),
  482. '#options' => array(
  483. 'https://api-3t.sandbox.paypal.com/nvp' => t('Sandbox'),
  484. 'https://api-3t.paypal.com/nvp' => t('Live'),
  485. ),
  486. '#default_value' => variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'),
  487. );
  488. $form['api'] = array(
  489. '#type' => 'fieldset',
  490. '#title' => t('API credentials'),
  491. '#description' => t('!link for information on obtaining credentials. You need to acquire an API Signature. If you have already requested API credentials, you can review your settings under the API Access section of your PayPal profile.', array('!link' => l(t('Click here'), 'https://developer.paypal.com/docs/classic/api/apiCredentials/'))),
  492. '#collapsible' => TRUE,
  493. '#collapsed' => variable_get('uc_paypal_api_username', '') != '',
  494. );
  495. $form['api']['uc_paypal_api_username'] = array(
  496. '#type' => 'textfield',
  497. '#title' => t('API username'),
  498. '#default_value' => variable_get('uc_paypal_api_username', ''),
  499. );
  500. $form['api']['uc_paypal_api_password'] = array(
  501. '#type' => 'textfield',
  502. '#title' => t('API password'),
  503. '#default_value' => variable_get('uc_paypal_api_password', ''),
  504. );
  505. $form['api']['uc_paypal_api_signature'] = array(
  506. '#type' => 'textfield',
  507. '#title' => t('Signature'),
  508. '#default_value' => variable_get('uc_paypal_api_signature', ''),
  509. );
  510. $form['ec']['uc_paypal_ec_landingpage_style'] = array(
  511. '#type' => 'radios',
  512. '#title' => t('Default PayPal landing page'),
  513. '#options' => array(
  514. 'Billing' => t('Credit card submission form.'),
  515. 'Login' => t('Account login form.'),
  516. ),
  517. '#default_value' => variable_get('uc_paypal_ec_landingpage_style', 'Billing'),
  518. );
  519. $form['ec']['uc_paypal_ec_rqconfirmed_addr'] = array(
  520. '#type' => 'checkbox',
  521. '#title' => t('Require Express Checkout users to use a PayPal confirmed shipping address.'),
  522. '#default_value' => variable_get('uc_paypal_ec_rqconfirmed_addr', FALSE),
  523. );
  524. $form['ec']['uc_paypal_ec_review_shipping'] = array(
  525. '#type' => 'checkbox',
  526. '#title' => t('Enable the shipping select form on the Review payment page.'),
  527. '#default_value' => variable_get('uc_paypal_ec_review_shipping', TRUE),
  528. );
  529. $form['ec']['uc_paypal_ec_review_company'] = array(
  530. '#type' => 'checkbox',
  531. '#title' => t('Enable the company name box on the Review payment page.'),
  532. '#default_value' => variable_get('uc_paypal_ec_review_company', TRUE),
  533. );
  534. $form['ec']['uc_paypal_ec_review_phone'] = array(
  535. '#type' => 'checkbox',
  536. '#title' => t('Enable the contact phone number box on the Review payment page.'),
  537. '#default_value' => variable_get('uc_paypal_ec_review_phone', TRUE),
  538. );
  539. $form['ec']['uc_paypal_ec_review_comment'] = array(
  540. '#type' => 'checkbox',
  541. '#title' => t('Enable the comment text box on the Review payment page.'),
  542. '#default_value' => variable_get('uc_paypal_ec_review_comment', TRUE),
  543. );
  544. $form['ec']['uc_pg_paypal_wpp_cc_txn_type'] = array(
  545. '#type' => 'radios',
  546. '#title' => t('Payment action'),
  547. '#description' => t('"Complete sale" will authorize and capture the funds at the time the payment is processed.<br>"Authorization" will only reserve funds on the card to be captured later through your PayPal account.'),
  548. '#options' => array(
  549. // The keys here are constants defined in uc_credit,
  550. // but uc_credit is not a dependency.
  551. 'auth_capture' => t('Complete sale'),
  552. 'authorize' => t('Authorization'),
  553. ),
  554. '#default_value' => variable_get('uc_pg_paypal_wpp_cc_txn_type', 'auth_capture'),
  555. );
  556. return $form;
  557. }
  558. }
  559. /*******************************************************************************
  560. * Module and Helper Functions
  561. ******************************************************************************/
  562. /**
  563. * Redirects if a customer selects PayPal Express Checkout as a payment method.
  564. */
  565. function uc_paypal_ec_checkout($form, &$form_state) {
  566. if ($form_state['values']['panes']['payment']['payment_method'] != 'paypal_ec') {
  567. return;
  568. }
  569. $order_id = intval($_SESSION['cart_order']);
  570. $order = uc_order_load($order_id);
  571. if ($order === FALSE || uc_order_status_data($order->order_status, 'state') != 'in_checkout') {
  572. $_SESSION['cart_order'] = NULL;
  573. unset($_SESSION['cart_order']);
  574. drupal_goto('cart');
  575. }
  576. list($desc, $subtotal) = _uc_paypal_product_details($order->products);
  577. $country = uc_get_country_data(array('country_id' => $order->billing_country));
  578. if ($country === FALSE) {
  579. $country = array(0 => array('country_iso_code_2' => 'US'));
  580. }
  581. $nvp_request = array(
  582. 'METHOD' => 'SetExpressCheckout',
  583. 'RETURNURL' => url('cart/echeckout/selected', array('absolute' => TRUE)),
  584. 'CANCELURL' => url('uc_paypal/wps/cancel', array('absolute' => TRUE)),
  585. 'AMT' => uc_currency_format($order->order_total, FALSE, FALSE, '.'),
  586. 'CURRENCYCODE' => variable_get('uc_paypal_wpp_currency', 'USD'),
  587. 'PAYMENTACTION' => variable_get('uc_pg_paypal_wpp_cc_txn_type', 'auth_capture') == 'authorize' ? 'Authorization' : 'Sale',
  588. 'DESC' => substr($desc, 0, 127),
  589. 'INVNUM' => $order->order_id . '-' . REQUEST_TIME,
  590. 'REQCONFIRMSHIPPING' => variable_get('uc_paypal_ec_rqconfirmed_addr', 0),
  591. 'ADDROVERRIDE' => 1,
  592. 'BUTTONSOURCE' => 'Ubercart_ShoppingCart_EC_US',
  593. 'NOTIFYURL' => url('uc_paypal/ipn/' . $order->order_id, array('absolute' => TRUE)),
  594. 'SHIPTONAME' => substr($order->delivery_first_name . ' ' . $order->delivery_last_name, 0, 32),
  595. 'SHIPTOSTREET' => substr($order->delivery_street1, 0, 100),
  596. 'SHIPTOSTREET2' => substr($order->delivery_street2, 0, 100),
  597. 'SHIPTOCITY' => substr($order->delivery_city, 0, 40),
  598. 'SHIPTOSTATE' => uc_get_zone_code($order->delivery_zone),
  599. 'SHIPTOCOUNTRYCODE' => $country[0]['country_iso_code_2'],
  600. 'SHIPTOZIP' => substr($order->delivery_postal_code, 0, 20),
  601. 'PHONENUM' => substr($order->delivery_phone, 0, 20),
  602. 'LANDINGPAGE' => variable_get('uc_paypal_ec_landingpage_style', 'Billing'),
  603. );
  604. if (!uc_order_is_shippable($order)) {
  605. $nvp_request['NOSHIPPING'] = 1;
  606. unset($nvp_request['ADDROVERRIDE']);
  607. }
  608. $nvp_response = uc_paypal_api_request($nvp_request, variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'));
  609. if ($nvp_response['ACK'] != 'Success') {
  610. drupal_set_message(t('Error message from PayPal:<br />@message', array('@message' => $nvp_response['L_LONGMESSAGE0'])), 'error');
  611. drupal_goto('cart/checkout');
  612. }
  613. $_SESSION['TOKEN'] = $nvp_response['TOKEN'];
  614. if (strpos(variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'), 'sandbox') > 0) {
  615. $sandbox = 'sandbox.';
  616. }
  617. header('Location: https://www.' . $sandbox . 'paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $_SESSION['TOKEN']);
  618. exit();
  619. }
  620. /**
  621. * Returns the form for Express Checkout Shortcut Flow.
  622. *
  623. * @see uc_paypal_ec_form_submit()
  624. */
  625. function uc_paypal_ec_form($form, &$form_state) {
  626. $form['uc_paypal'] = array(
  627. '#type' => 'image_button',
  628. '#button_type' => 'checkout',
  629. '#src' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckoutsm.gif',
  630. '#title' => t('Checkout with PayPal.'),
  631. '#submit' => array('uc_cart_view_form_submit', 'uc_paypal_ec_form_submit'),
  632. );
  633. return $form;
  634. }
  635. /**
  636. * Submit handler for uc_paypal_ec_form().
  637. *
  638. * @see uc_paypal_ec_form()
  639. */
  640. function uc_paypal_ec_form_submit($form, &$form_state) {
  641. global $user;
  642. $items = uc_cart_get_contents();
  643. if (!is_array($items) || count($items) == 0) {
  644. drupal_set_message(t('You do not have any items in your shopping cart.'));
  645. return;
  646. }
  647. list($desc, $subtotal) = _uc_paypal_product_details($items);
  648. $order = uc_order_new($user->uid);
  649. $nvp_request = array(
  650. 'METHOD' => 'SetExpressCheckout',
  651. 'RETURNURL' => url('cart/echeckout/review', array('absolute' => TRUE)),
  652. 'CANCELURL' => url('uc_paypal/wps/cancel', array('absolute' => TRUE)),
  653. 'AMT' => uc_currency_format($subtotal, FALSE, FALSE, '.'),
  654. 'CURRENCYCODE' => variable_get('uc_paypal_wpp_currency', 'USD'),
  655. 'PAYMENTACTION' => variable_get('uc_pg_paypal_wpp_cc_txn_type', 'auth_capture') == 'authorize' ? 'Authorization' : 'Sale',
  656. 'DESC' => substr($desc, 0, 127),
  657. 'INVNUM' => $order->order_id . '-' . REQUEST_TIME,
  658. 'REQCONFIRMSHIPPING' => variable_get('uc_paypal_ec_rqconfirmed_addr', 0),
  659. 'BUTTONSOURCE' => 'Ubercart_ShoppingCart_EC_US',
  660. 'NOTIFYURL' => url('uc_paypal/ipn/' . $order->order_id, array('absolute' => TRUE)),
  661. 'LANDINGPAGE' => variable_get('uc_paypal_ec_landingpage_style', 'Billing'),
  662. );
  663. $order->products = $items;
  664. uc_order_save($order);
  665. $nvp_response = uc_paypal_api_request($nvp_request, variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'));
  666. if ($nvp_response['ACK'] != 'Success') {
  667. drupal_set_message(t('PayPal reported an error: @code: @message', array('@code' => $nvp_response['L_ERRORCODE0'], '@message' => $nvp_response['L_LONGMESSAGE0'])), 'error');
  668. return;
  669. }
  670. $_SESSION['cart_order'] = $order->order_id;
  671. $_SESSION['TOKEN'] = $nvp_response['TOKEN'];
  672. $sandbox = '';
  673. if (strpos(variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'), 'sandbox') > 0) {
  674. $sandbox = 'sandbox.';
  675. }
  676. header('Location: https://www.' . $sandbox . 'paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $_SESSION['TOKEN']);
  677. exit();
  678. }
  679. /**
  680. * Additional submit handler for uc_cart_checkout_review_form().
  681. *
  682. * @see uc_cart_checkout_review_form()
  683. */
  684. function uc_paypal_ec_submit_form_submit($form, &$form_state) {
  685. $order = uc_order_load($_SESSION['cart_order']);
  686. list($desc, $subtotal) = _uc_paypal_product_details($order->products);
  687. $shipping = 0;
  688. if (is_array($order->line_items)) {
  689. foreach ($order->line_items as $item) {
  690. if ($item['type'] == 'shipping') {
  691. $shipping += $item['amount'];
  692. }
  693. }
  694. }
  695. $tax = 0;
  696. if (module_exists('uc_taxes')) {
  697. foreach (uc_taxes_calculate($order) as $tax_item) {
  698. $tax += $tax_item->amount;
  699. }
  700. }
  701. $subtotal = $order->order_total - $tax - $shipping;
  702. $country = uc_get_country_data(array('country_id' => $order->billing_country));
  703. if ($country === FALSE) {
  704. $country = array(0 => array('country_iso_code_2' => 'US'));
  705. }
  706. $nvp_request = array(
  707. 'METHOD' => 'DoExpressCheckoutPayment',
  708. 'TOKEN' => $_SESSION['TOKEN'],
  709. 'PAYMENTACTION' => variable_get('uc_pg_paypal_wpp_cc_txn_type', 'auth_capture') == 'authorize' ? 'Authorization' : 'Sale',
  710. 'PAYERID' => $_SESSION['PAYERID'],
  711. 'AMT' => uc_currency_format($order->order_total, FALSE, FALSE, '.'),
  712. 'DESC' => substr($desc, 0, 127),
  713. 'INVNUM' => $order->order_id . '-' . REQUEST_TIME,
  714. 'BUTTONSOURCE' => 'Ubercart_ShoppingCart_EC_US',
  715. 'NOTIFYURL' => url('uc_paypal/ipn/' . $order->order_id, array('absolute' => TRUE)),
  716. 'ITEMAMT' => uc_currency_format($subtotal, FALSE, FALSE, '.'),
  717. 'SHIPPINGAMT' => uc_currency_format($shipping, FALSE, FALSE, '.'),
  718. 'TAXAMT' => uc_currency_format($tax, FALSE, FALSE, '.'),
  719. 'CURRENCYCODE' => variable_get('uc_paypal_wpp_currency', 'USD'),
  720. );
  721. $nvp_response = uc_paypal_api_request($nvp_request, variable_get('uc_paypal_wpp_server', 'https://api-3t.sandbox.paypal.com/nvp'));
  722. unset($_SESSION['TOKEN'], $_SESSION['PAYERID']);
  723. $_SESSION['uc_checkout'][$_SESSION['cart_order']]['do_complete'] = TRUE;
  724. $form_state['redirect'] = 'cart/checkout/complete';
  725. }
  726. /**
  727. * Returns the form elements for the Website Payments Standard form.
  728. */
  729. function uc_paypal_wps_form($form, &$form_state, $order) {
  730. $shipping = 0;
  731. foreach ($order->line_items as $item) {
  732. if ($item['type'] == 'shipping') {
  733. $shipping += $item['amount'];
  734. }
  735. }
  736. $tax = 0;
  737. if (module_exists('uc_taxes')) {
  738. foreach (uc_taxes_calculate($order) as $tax_item) {
  739. $tax += $tax_item->amount;
  740. }
  741. }
  742. $address = variable_get('uc_paypal_wps_address_selection', 'billing');
  743. $country = uc_get_country_data(array('country_id' => $order->{$address . '_country'}));
  744. if ($country === FALSE) {
  745. $country = array(0 => array('country_iso_code_2' => 'US'));
  746. }
  747. $phone = '';
  748. for ($i = 0; $i < strlen($order->{$address . '_phone'}); $i++) {
  749. if (is_numeric($order->{$address . '_phone'}[$i])) {
  750. $phone .= $order->{$address . '_phone'}[$i];
  751. }
  752. }
  753. /**
  754. * night_phone_a: The area code for U.S. phone numbers, or the country code
  755. * for phone numbers outside the U.S.
  756. * night_phone_b: The three-digit prefix for U.S. phone numbers, or the
  757. * entire phone number for phone numbers outside the U.S.,
  758. * excluding country code.
  759. * night_phone_c: The four-digit phone number for U.S. phone numbers.
  760. * (Not Used for UK numbers)
  761. */
  762. if ($country[0]['country_iso_code_2'] == 'US' || $country[0]['country_iso_code_2'] == 'CA') {
  763. $phone = substr($phone, -10);
  764. $phone_a = substr($phone, 0, 3);
  765. $phone_b = substr($phone, 3, 3);
  766. $phone_c = substr($phone, 6, 4);
  767. }
  768. else {
  769. $phone_a = $phone_b = $phone_c = '';
  770. }
  771. $data = array(
  772. // PayPal command variable.
  773. 'cmd' => '_cart',
  774. // Set the correct codepage.
  775. 'charset' => 'utf-8',
  776. // IPN control notify URL.
  777. 'notify_url' => url('uc_paypal/ipn/' . $order->order_id, array('absolute' => TRUE)),
  778. // Display information.
  779. 'cancel_return' => url('uc_paypal/wps/cancel', array('absolute' => TRUE)),
  780. 'no_note' => 1,
  781. 'no_shipping' => variable_get('uc_paypal_wps_no_shipping', 1),
  782. 'return' => url('uc_paypal/wps/complete/' . $order->order_id, array('absolute' => TRUE)),
  783. 'rm' => 1,
  784. // Transaction information.
  785. 'currency_code' => variable_get('uc_paypal_wps_currency', 'USD'),
  786. 'handling_cart' => uc_currency_format($shipping, FALSE, FALSE, '.'),
  787. 'invoice' => $order->order_id . '-' . uc_cart_get_id(),
  788. 'tax_cart' => uc_currency_format($tax, FALSE, FALSE, '.'),
  789. // Shopping cart specific variables.
  790. 'business' => trim(variable_get('uc_paypal_wps_email', '')),
  791. 'upload' => 1,
  792. 'lc' => variable_get('uc_paypal_wps_language', 'US'),
  793. // Prepopulating forms/address overriding.
  794. 'address1' => substr($order->{$address . '_street1'}, 0, 100),
  795. 'address2' => substr($order->{$address . '_street2'}, 0, 100),
  796. 'city' => substr($order->{$address . '_city'}, 0, 40),
  797. 'country' => $country[0]['country_iso_code_2'],
  798. 'email' => $order->primary_email,
  799. 'first_name' => substr($order->{$address . '_first_name'}, 0, 32),
  800. 'last_name' => substr($order->{$address . '_last_name'}, 0, 64),
  801. 'state' => uc_get_zone_code($order->{$address . '_zone'}),
  802. 'zip' => $order->{$address . '_postal_code'},
  803. 'night_phone_a' => $phone_a,
  804. 'night_phone_b' => $phone_b,
  805. 'night_phone_c' => $phone_c,
  806. );
  807. if (variable_get('uc_paypal_wps_address_override', TRUE)) {
  808. $data['address_override'] = 1;
  809. }
  810. // Account for stores that just want to authorize funds instead of capture.
  811. if (variable_get('uc_paypal_wps_payment_action', 'Sale') == 'Authorization') {
  812. $data['paymentaction'] = 'authorization';
  813. }
  814. if (variable_get('uc_paypal_wps_submit_method', 'single') == 'itemized') {
  815. // List individual items.
  816. $i = 0;
  817. foreach ($order->products as $item) {
  818. $i++;
  819. $data['amount_' . $i] = uc_currency_format($item->price, FALSE, FALSE, '.');
  820. $data['item_name_' . $i] = $item->title;
  821. $data['item_number_' . $i] = $item->model;
  822. $data['quantity_' . $i] = $item->qty;
  823. // PayPal will only display the first two...
  824. if (!empty($item->data['attributes']) && count($item->data['attributes']) > 0) {
  825. $o = 0;
  826. foreach ($item->data['attributes'] as $name => $setting) {
  827. $data['on' . $o . '_' . $i] = $name;
  828. $data['os' . $o . '_' . $i] = implode(', ', (array)$setting);
  829. $o++;
  830. }
  831. }
  832. }
  833. // Apply discounts (negative amount line items). For example, this handles
  834. // line items created by uc_coupon.
  835. $discount = 0;
  836. foreach ($order->line_items as $item) {
  837. if ($item['amount'] < 0) {
  838. // The minus sign is not an error! The discount amount must be positive.
  839. $discount -= $item['amount'];
  840. }
  841. }
  842. if ($discount != 0) {
  843. $data['discount_amount_cart'] = $discount;
  844. }
  845. }
  846. else {
  847. // List the whole cart as a single item to account for fees/discounts.
  848. $data['amount_1'] = uc_currency_format($order->order_total - $shipping - $tax, FALSE, FALSE, '.');
  849. $data['item_name_1'] = t('Order @order_id at !store', array('@order_id' => $order->order_id, '!store' => uc_store_name()));
  850. $data['on0_1'] = t('Product count');
  851. $data['os0_1'] = count($order->products);
  852. }
  853. $form['#action'] = variable_get('uc_paypal_wps_server', 'https://www.sandbox.paypal.com/cgi-bin/webscr');
  854. foreach ($data as $name => $value) {
  855. if (!empty($value)) {
  856. $form[$name] = array('#type' => 'hidden', '#value' => $value);
  857. }
  858. }
  859. $form['actions'] = array('#type' => 'actions');
  860. $form['actions']['submit'] = array(
  861. '#type' => 'submit',
  862. '#value' => t('Submit order'),
  863. );
  864. return $form;
  865. }
  866. /**
  867. * Sends a request to PayPal and returns a response array.
  868. */
  869. function uc_paypal_api_request($request, $server) {
  870. // We use $request += to add API credentials so that if a key already exists,
  871. // it will not be overridden.
  872. $request += array(
  873. 'USER' => variable_get('uc_paypal_api_username', ''),
  874. 'PWD' => variable_get('uc_paypal_api_password', ''),
  875. 'VERSION' => '3.0',
  876. 'SIGNATURE' => variable_get('uc_paypal_api_signature', ''),
  877. );
  878. $data = '';
  879. foreach ($request as $key => $value) {
  880. $data .= $key . '=' . urlencode(str_replace(',', '', $value)) . '&';
  881. }
  882. $data = substr($data, 0, -1);
  883. $ch = curl_init();
  884. curl_setopt($ch, CURLOPT_URL, $server);
  885. curl_setopt($ch, CURLOPT_VERBOSE, 0);
  886. curl_setopt($ch, CURLOPT_POST, 1);
  887. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  888. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  889. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
  890. curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
  891. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  892. $response = curl_exec($ch);
  893. if ($error = curl_error($ch)) {
  894. watchdog('uc_paypal', '!error', array('!error' => $error), WATCHDOG_ERROR);
  895. }
  896. curl_close($ch);
  897. return _uc_paypal_nvp_to_array($response);
  898. }
  899. /**
  900. * Returns the description and subtotal of the products on an order.
  901. */
  902. function _uc_paypal_product_details($items) {
  903. $desc = '';
  904. $subtotal = 0;
  905. if (!empty($items)) {
  906. foreach ($items as $item) {
  907. if (!empty($desc)) {
  908. $desc .= ' / ';
  909. }
  910. $desc .= $item->qty . 'x ' . $item->title;
  911. $subtotal += $item->qty * $item->price;
  912. }
  913. }
  914. return array($desc, $subtotal);
  915. }
  916. /**
  917. * Returns the PayPal approved credit card type for a card number.
  918. */
  919. function _uc_paypal_card_type($cc_number) {
  920. switch (substr(strval($cc_number), 0, 1)) {
  921. case '3':
  922. return 'Amex';
  923. case '4':
  924. return 'Visa';
  925. case '5':
  926. return 'MasterCard';
  927. case '6':
  928. return 'Discover';
  929. }
  930. return FALSE;
  931. }
  932. /**
  933. * Turns PayPal's NVP response to an API call into an associative array.
  934. */
  935. function _uc_paypal_nvp_to_array($nvpstr) {
  936. foreach (explode('&', $nvpstr) as $nvp) {
  937. list($key, $value) = explode('=', $nvp);
  938. $nvp_array[urldecode($key)] = urldecode($value);
  939. }
  940. return $nvp_array;
  941. }
  942. /**
  943. * Returns a human readable message for the AVS code.
  944. */
  945. function _uc_paypal_avscode_message($code) {
  946. if (is_numeric($code)) {
  947. switch ($code) {
  948. case '0':
  949. return t('All the address information matched.');
  950. case '1':
  951. return t('None of the address information matched; transaction declined.');
  952. case '2':
  953. return t('Part of the address information matched.');
  954. case '3':
  955. return t('The merchant did not provide AVS information. Not processed.');
  956. case '4':
  957. return t('Address not checked, or acquirer had no response. Service not available.');
  958. default:
  959. return t('No AVS response was obtained.');
  960. }
  961. }
  962. switch ($code) {
  963. case 'A':
  964. case 'B':
  965. return t('Address matched; postal code did not');
  966. case 'C':
  967. case 'N':
  968. return t('Nothing matched; transaction declined');
  969. case 'D':
  970. case 'F':
  971. case 'X':
  972. case 'Y':
  973. return t('Address and postal code matched');
  974. case 'E':
  975. return t('Not allowed for MOTO transactions; transaction declined');
  976. case 'G':
  977. return t('Global unavailable');
  978. case 'I':
  979. return t('International unavailable');
  980. case 'P':
  981. case 'W':
  982. case 'Z':
  983. return t('Postal code matched; address did not');
  984. case 'R':
  985. return t('Retry for validation');
  986. case 'S':
  987. return t('Service not supported');
  988. case 'U':
  989. return t('Unavailable');
  990. case 'Null':
  991. return t('No AVS response was obtained.');
  992. default:
  993. return t('An unknown error occurred.');
  994. }
  995. }
  996. /**
  997. * Returns a human readable message for the CVV2 match code.
  998. */
  999. function _uc_paypal_cvvmatch_message($code) {
  1000. if (is_numeric($code)) {
  1001. switch ($code) {
  1002. case '0':
  1003. return t('Matched');
  1004. case '1':
  1005. return t('No match');
  1006. case '2':
  1007. return t('The merchant has not implemented CVV2 code handling.');
  1008. case '3':
  1009. return t('Merchant has indicated that CVV2 is not present on card.');
  1010. case '4':
  1011. return t('Service not available');
  1012. default:
  1013. return t('Unkown error');
  1014. }
  1015. }
  1016. switch ($code) {
  1017. case 'M':
  1018. return t('Match');
  1019. case 'N':
  1020. return t('No match');
  1021. case 'P':
  1022. return t('Not processed');
  1023. case 'S':
  1024. return t('Service not supported');
  1025. case 'U':
  1026. return t('Service not available');
  1027. case 'X':
  1028. return t('No response');
  1029. default:
  1030. return t('Not checked');
  1031. }
  1032. }
  1033. /**
  1034. * Returns a message for the pending reason of a PayPal payment.
  1035. */
  1036. function _uc_paypal_pending_message($reason) {
  1037. switch ($reason) {
  1038. case 'address':
  1039. return t('Customer did not include a confirmed shipping address per your address settings.');
  1040. case 'authorization':
  1041. return t('Waiting on you to capture the funds per your authorization settings.');
  1042. case 'echeck':
  1043. return t('eCheck has not yet cleared.');
  1044. case 'intl':
  1045. return t('You must manually accept or deny this international payment from your Account Overview.');
  1046. case 'multi-currency':
  1047. case 'multi_currency':
  1048. return t('You must manually accept or deny a payment of this currency from your Account Overview.');
  1049. case 'unilateral':
  1050. return t('Your e-mail address is not yet registered or confirmed.');
  1051. case 'upgrade':
  1052. return t('You must upgrade your account to Business or Premier status to receive credit card payments.');
  1053. case 'verify':
  1054. return t('You must verify your account before you can accept this payment.');
  1055. case 'other':
  1056. default:
  1057. return t('Reason "@reason" unknown; contact PayPal Customer Service for more information.', array('@reason' => $reason));
  1058. }
  1059. }
  1060. /**
  1061. * Returns a message for the reason code of a PayPal reversal.
  1062. */
  1063. function _uc_paypal_reversal_message($reason) {
  1064. switch ($reason) {
  1065. case 'chargeback':
  1066. return t('The customer has initiated a chargeback.');
  1067. case 'guarantee':
  1068. return t('The customer triggered a money-back guarantee.');
  1069. case 'buyer-complaint':
  1070. return t('The customer filed a complaint about the transaction.');
  1071. case 'refund':
  1072. return t('You gave the customer a refund.');
  1073. case 'other':
  1074. default:
  1075. return t('Reason "@reason" unknown; contact PayPal Customer Service for more information.', array('@reason' => $reason));
  1076. }
  1077. }
  1078. /**
  1079. * Returns an array of possible currency codes.
  1080. */
  1081. function _uc_paypal_currency_array() {
  1082. return drupal_map_assoc(array('AUD', 'BRL', 'CAD', 'CHF', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HUF', 'ILS', 'JPY', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'SEK', 'SGD', 'THB', 'TWD', 'USD'));
  1083. }