uc_paypal.module 44 KB

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