PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wp-e-commerce/wpsc-merchants/paypal-express.merchant.php

https://github.com/AaronFernandes/aquestionof
PHP | 742 lines | 512 code | 110 blank | 120 comment | 66 complexity | f000b0551cc70aec2ad4423d91a08dcf MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. <?php
  2. /**
  3. * This is the PayPal Certified 2.0 Gateway.
  4. * It uses the wpsc_merchant class as a base class which is handy for collating user details and cart contents.
  5. */
  6. /*
  7. * This is the gateway variable $nzshpcrt_gateways, it is used for displaying gateway information on the wp-admin pages and also
  8. * for internal operations.
  9. */
  10. $nzshpcrt_gateways[$num] = array(
  11. 'name' => __( 'PayPal Express Checkout 2.0', 'wpsc' ),
  12. 'api_version' => 2.0,
  13. 'image' => WPSC_URL . '/images/paypal.gif',
  14. 'class_name' => 'wpsc_merchant_paypal_express',
  15. 'has_recurring_billing' => false,
  16. 'wp_admin_cannot_cancel' => true,
  17. 'display_name' => __( 'PayPal Express', 'wpsc' ),
  18. 'requirements' => array(
  19. /// so that you can restrict merchant modules to PHP 5, if you use PHP 5 features
  20. 'php_version' => 4.3,
  21. /// for modules that may not be present, like curl
  22. 'extra_modules' => array()
  23. ),
  24. // this may be legacy, not yet decided
  25. 'internalname' => 'wpsc_merchant_paypal_express',
  26. // All array members below here are legacy, and use the code in paypal_multiple.php
  27. 'form' => 'form_paypal_express',
  28. 'submit_function' => 'submit_paypal_express',
  29. 'payment_type' => 'paypal',
  30. 'supported_currencies' => array(
  31. 'currency_list' => array('AUD', 'BRL', 'CAD', 'CHF', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HUF', 'ILS', 'JPY', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'SEK', 'SGD', 'THB', 'TWD', 'USD'),
  32. 'option_name' => 'paypal_curcode'
  33. )
  34. );
  35. /**
  36. * WP eCommerce PayPal Express Checkout Merchant Class
  37. *
  38. * This is the paypal express checkout merchant class, it extends the base merchant class
  39. *
  40. * @package wp-e-commerce
  41. * @since 3.8
  42. * @subpackage wpsc-merchants
  43. */
  44. class wpsc_merchant_paypal_express extends wpsc_merchant {
  45. var $name = 'PayPal Express';
  46. var $paypal_ipn_values = array();
  47. /**
  48. * construct value array method, converts the data gathered by the base class code to something acceptable to the gateway
  49. * @access public
  50. */
  51. function construct_value_array() {
  52. global $PAYPAL_URL;
  53. $PROXY_HOST = '127.0.0.1';
  54. $PROXY_PORT = '808';
  55. $USE_PROXY = false;
  56. $version="56.0";
  57. // PayPal API Credentials
  58. $API_UserName=get_option('paypal_certified_apiuser');
  59. $API_Password=get_option('paypal_certified_apipass');
  60. $API_Signature=get_option('paypal_certified_apisign');
  61. // BN Code is only applicable for partners
  62. $sBNCode = "PP-ECWizard";
  63. if ('sandbox' == get_option('paypal_certified_server_type')) {
  64. $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
  65. $PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
  66. }else{
  67. $API_Endpoint = "https://api-3t.paypal.com/nvp";
  68. $PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
  69. }
  70. //$collected_gateway_data
  71. $paypal_vars = array();
  72. // User settings to be sent to paypal
  73. $paypal_vars += array(
  74. 'email' => $this->cart_data['email_address'],
  75. 'first_name' => $this->cart_data['shipping_address']['first_name'],
  76. 'last_name' => $this->cart_data['shipping_address']['last_name'],
  77. 'address1' => $this->cart_data['shipping_address']['address'],
  78. 'city' => $this->cart_data['shipping_address']['city'],
  79. 'country' => $this->cart_data['shipping_address']['country'],
  80. 'zip' => $this->cart_data['shipping_address']['post_code']
  81. );
  82. if($this->cart_data['shipping_address']['state'] != '') {
  83. $paypal_vars += array(
  84. 'state' => $this->cart_data['shipping_address']['state']
  85. );
  86. }
  87. $this->collected_gateway_data = $paypal_vars;
  88. }
  89. /**
  90. * submit method, sends the received data to the payment gateway
  91. * @access public
  92. */
  93. function submit() {
  94. //$_SESSION['paypalExpressMessage']= '<h4>Transaction Canceled</h4>';
  95. // PayPal Express Checkout Module
  96. $paymentAmount = $this->cart_data['total_price'];
  97. $_SESSION['paypalAmount'] = $paymentAmount;
  98. $_SESSION['paypalexpresssessionid'] = $this->cart_data['session_id'];
  99. paypal_express_currencyconverter();
  100. $currencyCodeType = get_option('paypal_curcode');
  101. $paymentType = "Sale";
  102. if(get_option('permalink_structure') != '')
  103. $separator ="?";
  104. else
  105. $separator ="&";
  106. $transact_url = get_option('transact_url');
  107. $returnURL = $transact_url.$separator."sessionid=".$this->cart_data['session_id']."&gateway=paypal";
  108. $cancelURL = get_option('shopping_cart_url');
  109. $resArray = $this->CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL);
  110. $ack = strtoupper($resArray["ACK"]);
  111. if($ack=="SUCCESS") {
  112. $this->RedirectToPayPal ( $resArray["TOKEN"] );
  113. } else {
  114. //Display a user friendly Error on the page using any of the following error information returned by PayPal
  115. $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
  116. $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
  117. $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
  118. $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
  119. echo "SetExpressCheckout API call failed. ";
  120. echo "<br />Detailed Error Message: " . $ErrorLongMsg;
  121. echo "<br />Short Error Message: " . $ErrorShortMsg;
  122. echo "<br />Error Code: " . $ErrorCode;
  123. echo "<br />Error Severity Code: " . $ErrorSeverityCode;
  124. }
  125. exit();
  126. }
  127. function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL) {
  128. global $wpdb;
  129. $nvpstr = "&Amt=". $paymentAmount;
  130. $nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
  131. $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
  132. $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
  133. $nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCodeType;
  134. $data = array();
  135. if(!isset($this->cart_data['shipping_address']['first_name']) && !isset($this->cart_data['shipping_address']['last_name'])){
  136. $this->cart_data['shipping_address']['first_name'] =$this->cart_data['billing_address']['first_name'];
  137. $this->cart_data['shipping_address']['last_name'] = $this->cart_data['billing_address']['last_name'];
  138. }
  139. $data += array(
  140. 'SHIPTONAME' => $this->cart_data['shipping_address']['first_name'].' '.$this->cart_data['shipping_address']['last_name'],
  141. 'SHIPTOSTREET' => $this->cart_data['shipping_address']['address'],
  142. 'SHIPTOCITY' => $this->cart_data['shipping_address']['city'],
  143. 'SHIPTOCOUNTRYCODE' => $this->cart_data['shipping_address']['country'],
  144. 'SHIPTOZIP' => $this->cart_data['shipping_address']['post_code']
  145. );
  146. if( '' != $this->cart_data['shipping_address']['state']){
  147. $data += array(
  148. 'SHIPTOSTATE' => $this->cart_data['shipping_address']['state']
  149. );
  150. }
  151. if(count($data) >= 4) {
  152. $temp_data = array();
  153. foreach($data as $key => $value)
  154. $temp_data[] = $key."=".$value;
  155. $nvpstr = $nvpstr . "&".implode("&",$temp_data);
  156. }
  157. $_SESSION["currencyCodeType"] = $currencyCodeType;
  158. $_SESSION["PaymentType"] = $paymentType;
  159. $resArray= paypal_hash_call("SetExpressCheckout", $nvpstr);
  160. $ack = strtoupper($resArray["ACK"]);
  161. if($ack=="SUCCESS") {
  162. $token = urldecode($resArray["TOKEN"]);
  163. $_SESSION['token']=$token;
  164. }
  165. return $resArray;
  166. }
  167. function RedirectToPayPal ( $token ){
  168. global $PAYPAL_URL;
  169. // Redirect to paypal.com here
  170. $payPalURL = $PAYPAL_URL . $token;
  171. // echo 'REDIRECT:'.$payPalURL;
  172. wp_redirect($payPalURL);
  173. // exit();
  174. }
  175. } // end of class
  176. /**
  177. * Saving of PayPal Express Settings
  178. * @access public
  179. *
  180. * @since 3.8
  181. */
  182. function submit_paypal_express() {
  183. if(isset($_POST['paypal_certified_apiuser']))
  184. update_option('paypal_certified_apiuser', $_POST['paypal_certified_apiuser']);
  185. if(isset($_POST['paypal_certified_apipass']))
  186. update_option('paypal_certified_apipass', $_POST['paypal_certified_apipass']);
  187. if(isset($_POST['paypal_curcode']))
  188. update_option('paypal_curcode', $_POST['paypal_curcode']);
  189. if(isset($_POST['paypal_certified_apisign']))
  190. update_option('paypal_certified_apisign', $_POST['paypal_certified_apisign']);
  191. if(isset($_POST['paypal_certified_server_type']))
  192. update_option('paypal_certified_server_type', $_POST['paypal_certified_server_type']);
  193. return true;
  194. }
  195. /**
  196. * Form Express Returns the Settings Form Fields
  197. * @access public
  198. *
  199. * @since 3.8
  200. * @return $output string containing Form Fields
  201. */
  202. function form_paypal_express() {
  203. global $wpdb, $wpsc_gateways;
  204. $serverType1 = '';
  205. $serverType2 = '';
  206. $select_currency[get_option('paypal_curcode')] = "selected='selected'";
  207. if (get_option('paypal_certified_server_type') == 'sandbox')
  208. $serverType1="checked='checked'";
  209. elseif(get_option('paypal_certified_server_type') == 'production')
  210. $serverType2 ="checked='checked'";
  211. $output = "
  212. <tr>
  213. <td>" . __('API Username', 'wpsc' ) . "
  214. </td>
  215. <td>
  216. <input type='text' size='40' value='".get_option('paypal_certified_apiuser')."' name='paypal_certified_apiuser' />
  217. </td>
  218. </tr>
  219. <tr>
  220. <td>" . __('API Password', 'wpsc' ) . "
  221. </td>
  222. <td>
  223. <input type='text' size='40' value='".get_option('paypal_certified_apipass')."' name='paypal_certified_apipass' />
  224. </td>
  225. </tr>
  226. <tr>
  227. <td>" . __('API Signature', 'wpsc' ) . "
  228. </td>
  229. <td>
  230. <input type='text' size='70' value='".get_option('paypal_certified_apisign')."' name='paypal_certified_apisign' />
  231. </td>
  232. </tr>
  233. <tr>
  234. <td>" . __('Server Type', 'wpsc' ) . "
  235. </td>
  236. <td>
  237. <input $serverType1 type='radio' name='paypal_certified_server_type' value='sandbox' /> " . __('Sandbox (For testing)', 'wpsc' ) . "
  238. <input $serverType2 type='radio' name='paypal_certified_server_type' value='production' /> " . __('Production', 'wpsc' ) . "
  239. </td>
  240. </tr>";
  241. $store_currency_code = $wpdb->get_var("SELECT `code` FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `id` IN ('".absint(get_option('currency_type'))."')");
  242. $current_currency = get_option('paypal_curcode');
  243. if(($current_currency == '') && in_array($store_currency_data['code'], $wpsc_gateways['wpsc_merchant_paypal_express']['supported_currencies']['currency_list'])) {
  244. update_option('paypal_curcode', $store_currency_data['code']);
  245. $current_currency = $store_currency_data['code'];
  246. }
  247. if($current_currency != $store_currency_code) {
  248. $output .= "<tr> <td colspan='2'><strong class='form_group'>".__('Currency Converter')."</td> </tr>
  249. <tr>
  250. <td colspan='2'>".__('Your website is using a currency not accepted by PayPal, select an accepted currency using the drop down menu bellow. Buyers on your site will still pay in your local currency however we will convert the currency and send the order through to PayPal using the currency you choose below.', 'wpsc')."</td>
  251. </tr>\n";
  252. $output .= "<tr>\n <td>" . __('Convert to', 'wpsc' ) . " </td>\n ";
  253. $output .= "<td>\n <select name='paypal_curcode'>\n";
  254. if (!isset($wpsc_gateways['wpsc_merchant_paypal_express']['supported_currencies']['currency_list']))
  255. $wpsc_gateways['wpsc_merchant_paypal_express']['supported_currencies']['currency_list'] = array();
  256. $paypal_currency_list = $wpsc_gateways['wpsc_merchant_paypal_express']['supported_currencies']['currency_list'];
  257. $currency_list = $wpdb->get_results("SELECT DISTINCT `code`, `currency` FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `code` IN ('".implode("','",$paypal_currency_list)."')", ARRAY_A);
  258. foreach($currency_list as $currency_item) {
  259. $selected_currency = '';
  260. if($current_currency == $currency_item['code']) {
  261. $selected_currency = "selected='selected'";
  262. }
  263. $output .= "<option ".$selected_currency." value='{$currency_item['code']}'>{$currency_item['currency']}</option>";
  264. }
  265. $output .= " </select> \n";
  266. $output .= " </td>\n";
  267. $output .= " </tr>\n";
  268. }
  269. return $output;
  270. }
  271. function paypal_express_currencyconverter(){
  272. global $wpdb;
  273. $currency_code = $wpdb->get_var("SELECT `code` FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `id`='".get_option('currency_type')."' LIMIT 1");
  274. $local_currency_code = $currency_code;
  275. $paypal_currency_code = get_option('paypal_curcode');
  276. if($paypal_currency_code == '')
  277. $paypal_currency_code = 'US';
  278. $curr=new CURRENCYCONVERTER();
  279. if($paypal_currency_code != $local_currency_code) {
  280. $paypal_currency_productprice = $curr->convert($_SESSION['paypalAmount'],$paypal_currency_code,$local_currency_code);
  281. $paypal_currency_shipping = $curr->convert($local_currency_shipping,$paypal_currency_code,$local_currency_code);
  282. $base_shipping = $curr->convert($purchase_log['base_shipping'],$paypal_currency_code, $local_currency_code);
  283. } else {
  284. $paypal_currency_productprice = $_SESSION['paypalAmount'];
  285. $paypal_currency_shipping = $local_currency_shipping;
  286. $base_shipping = $purchase_log['base_shipping'];
  287. }
  288. switch($paypal_currency_code) {
  289. case "JPY":
  290. $decimal_places = 0;
  291. break;
  292. case "HUF":
  293. $decimal_places = 0;
  294. break;
  295. default:
  296. $decimal_places = 2;
  297. break;
  298. }
  299. $_SESSION['paypalAmount'] = number_format(sprintf("%01.2f", $paypal_currency_productprice),$decimal_places,'.','');
  300. }
  301. /**
  302. * prcessing functions, this is where the main logic of paypal express lives
  303. * @access public
  304. *
  305. * @since 3.8
  306. */
  307. function paypal_processingfunctions(){
  308. global $wpdb, $wpsc_cart;
  309. $sessionid = '';
  310. if (isset($_SESSION['paypalexpresssessionid']))
  311. $sessionid = $_SESSION['paypalexpresssessionid'];
  312. if(isset($_REQUEST['act']) && ($_REQUEST['act']=='error')){
  313. session_start();
  314. $resArray=$_SESSION['reshash'];
  315. $_SESSION['paypalExpressMessage']= '
  316. <center>
  317. <table width="700" align="left">
  318. <tr>
  319. <td colspan="2" class="header">' . __('The PayPal API has returned an error!', 'wpsc' ) . '</td>
  320. </tr>
  321. ';
  322. //it will print if any URL errors
  323. if(isset($_SESSION['curl_error_msg'])) {
  324. $errorMessage=$_SESSION['curl_error_msg'] ;
  325. $response = $_SESSION['response'];
  326. session_unset();
  327. $_SESSION['paypalExpressMessage'].='
  328. <tr>
  329. <td>response:</td>
  330. <td>'.$response.'</td>
  331. </tr>
  332. <tr>
  333. <td>Error Message:</td>
  334. <td>'.$errorMessage.'</td>
  335. </tr>';
  336. } else {
  337. /* If there is no URL Errors, Construct the HTML page with
  338. Response Error parameters. */
  339. $_SESSION['paypalExpressMessage'] .="
  340. <tr>
  341. <td>Ack:</td>
  342. <td>".$resArray['ACK']."</td>
  343. </tr>
  344. <tr>
  345. <td>Correlation ID:</td>
  346. <td>".$resArray['CORRELATIONID']."</td>
  347. </tr>
  348. <tr>
  349. <td>Version:</td>
  350. <td>".$resArray['VERSION']."</td>
  351. </tr>";
  352. $count=0;
  353. while (isset($resArray["L_SHORTMESSAGE".$count])) {
  354. $errorCode = $resArray["L_ERRORCODE".$count];
  355. $shortMessage = $resArray["L_SHORTMESSAGE".$count];
  356. $longMessage = $resArray["L_LONGMESSAGE".$count];
  357. $count=$count+1;
  358. $_SESSION['paypalExpressMessage'] .="
  359. <tr>
  360. <td>" . __('Error Number:', 'wpsc' ) . "</td>
  361. <td> $errorCode </td>
  362. </tr>
  363. <tr>
  364. <td>" . __('Short Message:', 'wpsc' ) . "</td>
  365. <td> $shortMessage </td>
  366. </tr>
  367. <tr>
  368. <td>" . __('Long Message:', 'wpsc' ) . "</td>
  369. <td> $longMessage </td>
  370. </tr>";
  371. }//end while
  372. }// end else
  373. $_SESSION['paypalExpressMessage'] .="
  374. </center>
  375. </table>";
  376. }else if(isset($_REQUEST['act']) && ($_REQUEST['act']=='do')){
  377. session_start();
  378. /* Gather the information to make the final call to
  379. finalize the PayPal payment. The variable nvpstr
  380. holds the name value pairs */
  381. $token =urlencode($_REQUEST['token']);
  382. $paymentAmount =urlencode ($_SESSION['paypalAmount']);
  383. $paymentType = urlencode($_SESSION['paymentType']);
  384. $currCodeType = urlencode(get_option('paypal_curcode'));
  385. $payerID = urlencode($_REQUEST['PayerID']);
  386. $serverName = urlencode($_SERVER['SERVER_NAME']);
  387. $BN='Instinct_e-commerce_wp-shopping-cart_NZ';
  388. $nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION=Sale&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName."&BUTTONSOURCE=".$BN ;
  389. $resArray=paypal_hash_call("DoExpressCheckoutPayment",$nvpstr);
  390. /* Display the API response back to the browser.
  391. If the response from PayPal was a success, display the response parameters'
  392. If the response was an error, display the errors received using APIError.php. */
  393. $ack = strtoupper($resArray["ACK"]);
  394. $_SESSION['reshash']=$resArray;
  395. if($ack!="SUCCESS"){
  396. $location = get_option('transact_url')."&act=error";
  397. }else{
  398. $transaction_id = $wpdb->escape($resArray['TRANSACTIONID']);
  399. switch($resArray['PAYMENTSTATUS']) {
  400. case 'Processed': // I think this is mostly equivalent to Completed
  401. case 'Completed':
  402. $wpdb->query("UPDATE `".WPSC_TABLE_PURCHASE_LOGS."` SET `processed` = '3' WHERE `sessionid` = ".$sessionid." LIMIT 1");
  403. transaction_results($_SESSION['wpsc_sessionid'], false, $transaction_id);
  404. break;
  405. case 'Pending': // need to wait for "Completed" before processing
  406. $wpdb->query("UPDATE `".WPSC_TABLE_PURCHASE_LOGS."` SET `transactid` = '".$transaction_id."',`processed` = '2', `date` = '".time()."' WHERE `sessionid` = ".$sessionid." LIMIT 1");
  407. break;
  408. }
  409. $location = add_query_arg('sessionid', $sessionid, get_option('transact_url'));
  410. $_SESSION['paypalExpressMessage'] = null;
  411. wp_redirect($location);
  412. exit();
  413. }
  414. @$_SESSION['nzshpcrt_serialized_cart'] = '';
  415. $_SESSION['nzshpcrt_cart'] = '';
  416. $_SESSION['nzshpcrt_cart'] = Array();
  417. $wpsc_cart->empty_cart();
  418. } else if(isset($_REQUEST['paymentType']) || isset($_REQUEST['token'])){
  419. $token = $_REQUEST['token'];
  420. if(!isset($token)) {
  421. $paymentAmount=$_SESSION['paypalAmount'];
  422. $currencyCodeType=get_option('paypal_curcode');
  423. $paymentType='Sale';
  424. if(get_option('permalink_structure') != '')
  425. $separator ="?";
  426. else
  427. $separator ="&";
  428. $returnURL =urlencode(get_option('transact_url').$separator.'currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType.'&paymentAmount='.$paymentAmount);
  429. $cancelURL =urlencode(get_option('transact_url').$separator.'paymentType=$paymentType' );
  430. /* Construct the parameter string that describes the PayPal payment
  431. the varialbes were set in the web form, and the resulting string
  432. is stored in $nvpstr */
  433. $nvpstr="&Amt=".$paymentAmount."&PAYMENTACTION=".$paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType;
  434. /* Make the call to PayPal to set the Express Checkout token
  435. If the API call succeded, then redirect the buyer to PayPal
  436. to begin to authorize payment. If an error occured, show the
  437. resulting errors
  438. */
  439. $resArray=paypal_hash_call("SetExpressCheckout",$nvpstr);
  440. $_SESSION['reshash']=$resArray;
  441. $ack = strtoupper($resArray["ACK"]);
  442. if($ack=="SUCCESS"){
  443. // Redirect to paypal.com here
  444. $token = urldecode($resArray["TOKEN"]);
  445. $payPalURL = $PAYPAL_URL.$token;
  446. wp_redirect($payPalURL);
  447. } else {
  448. // Redirecting to APIError.php to display errors.
  449. $location = get_option('transact_url')."&act=error";
  450. wp_redirect($location);
  451. }
  452. exit();
  453. } else {
  454. /* At this point, the buyer has completed in authorizing payment
  455. at PayPal. The script will now call PayPal with the details
  456. of the authorization, incuding any shipping information of the
  457. buyer. Remember, the authorization is not a completed transaction
  458. at this state - the buyer still needs an additional step to finalize
  459. the transaction
  460. */
  461. $token =urlencode( $_REQUEST['token']);
  462. /* Build a second API request to PayPal, using the token as the
  463. ID to get the details on the payment authorization
  464. */
  465. $nvpstr="&TOKEN=".$token;
  466. /* Make the API call and store the results in an array. If the
  467. call was a success, show the authorization details, and provide
  468. an action to complete the payment. If failed, show the error
  469. */
  470. $resArray=paypal_hash_call("GetExpressCheckoutDetails",$nvpstr);
  471. $_SESSION['reshash']=$resArray;
  472. $ack = strtoupper($resArray["ACK"]);
  473. if($ack=="SUCCESS"){
  474. /********************************************************
  475. GetExpressCheckoutDetails.php
  476. This functionality is called after the buyer returns from
  477. PayPal and has authorized the payment.
  478. Displays the payer details returned by the
  479. GetExpressCheckoutDetails response and calls
  480. DoExpressCheckoutPayment.php to complete the payment
  481. authorization.
  482. Called by ReviewOrder.php.
  483. Calls DoExpressCheckoutPayment.php and APIError.php.
  484. ********************************************************/
  485. session_start();
  486. /* Collect the necessary information to complete the
  487. authorization for the PayPal payment
  488. */
  489. $_SESSION['token']=$_REQUEST['token'];
  490. $_SESSION['payer_id'] = $_REQUEST['PayerID'];
  491. $resArray=$_SESSION['reshash'];
  492. if(get_option('permalink_structure') != '')
  493. $separator ="?";
  494. else
  495. $separator ="&";
  496. /* Display the API response back to the browser .
  497. If the response from PayPal was a success, display the response parameters
  498. */
  499. if(isset($_REQUEST['TOKEN']) && !isset($_REQUEST['PAYERID'])){
  500. $_SESSION['paypalExpressMessage']= '<h4>TRANSACTION CANCELED</h4>';
  501. }else{
  502. $output ="
  503. <table width='400' class='paypal_express_form'>
  504. <tr>
  505. <td align='left' class='firstcol'><b>" . __('Error Number:', 'wpsc' ) . "Order Total:</b></td>
  506. <td align='left'>" . wpsc_currency_display($_SESSION['paypalAmount']) . "</td>
  507. </tr>
  508. <tr>
  509. <td align='left'><b>" . __('Shipping Address:', 'wpsc' ) . " </b></td>
  510. </tr>
  511. <tr>
  512. <td align='left' class='firstcol'>
  513. " . __('Street 1:', 'wpsc' ) . "</td>
  514. <td align='left'>".$resArray['SHIPTOSTREET']."</td>
  515. </tr>
  516. <tr>
  517. <td align='left' class='firstcol'>
  518. " . __('Street 2:', 'wpsc' ) . "</td>
  519. <td align='left'>".$resArray['SHIPTOSTREET2']."
  520. </td>
  521. </tr>
  522. <tr>
  523. <td align='left' class='firstcol'>
  524. " . __('City:', 'wpsc' ) . "</td>
  525. <td align='left'>".$resArray['SHIPTOCITY']."</td>
  526. </tr>
  527. <tr>
  528. <td align='left' class='firstcol'>
  529. " . __('State:', 'wpsc' ) . "</td>
  530. <td align='left'>".$resArray['SHIPTOSTATE']."</td>
  531. </tr>
  532. <tr>
  533. <td align='left' class='firstcol'>
  534. " . __('Postal code:', 'wpsc' ) . "</td>
  535. <td align='left'>".$resArray['SHIPTOZIP']."</td>
  536. </tr>
  537. <tr>
  538. <td align='left' class='firstcol'>
  539. " . __('Country:', 'wpsc' ) . "</td>
  540. <td align='left'>".$resArray['SHIPTOCOUNTRYNAME']."</td>
  541. </tr>
  542. <tr>
  543. <td>";
  544. $output .= "<form action=".get_option('transact_url')." method='post'>\n";
  545. $output .= " <input type='hidden' name='totalAmount' value='".wpsc_cart_total(false)."' />\n";
  546. $output .= " <input type='hidden' name='shippingStreet' value='".$resArray['SHIPTOSTREET']."' />\n";
  547. $output .= " <input type='hidden' name='shippingStreet2' value='".$resArray['SHIPTOSTREET2']."' />\n";
  548. $output .= " <input type='hidden' name='shippingCity' value='".$resArray['SHIPTOCITY']."' />\n";
  549. $output .= " <input type='hidden' name='shippingState' value='".$resArray['SHIPTOSTATE']."' />\n";
  550. $output .= " <input type='hidden' name='postalCode' value='".$resArray['SHIPTOZIP']."' />\n";
  551. $output .= " <input type='hidden' name='country' value='".$resArray['SHIPTOCOUNTRYNAME']."' />\n";
  552. $output .= " <input type='hidden' name='token' value='".$_SESSION['token']."' />\n";
  553. $output .= " <input type='hidden' name='PayerID' value='".$_SESSION['payer_id']."' />\n";
  554. $output .= " <input type='hidden' name='act' value='do' />\n";
  555. $output .= " <p> <input name='usePayPal' type='submit' value='".__('Confirm Payment','wpsc')."' /></p>\n";
  556. $output .= "</form>";
  557. $output .=" </td>
  558. </tr>
  559. </table>
  560. </center>
  561. ";
  562. $_SESSION['paypalExpressMessage'] = $output;
  563. }
  564. }
  565. }
  566. }
  567. }
  568. function paypal_hash_call($methodName,$nvpStr) {
  569. //declaring of variables
  570. $version = 56;
  571. if ( 'sandbox' == get_option('paypal_certified_server_type') ) {
  572. $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
  573. $paypal_certified_url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
  574. } else {
  575. $API_Endpoint = "https://api-3t.paypal.com/nvp";
  576. $paypal_certified_url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
  577. }
  578. $USE_PROXY = false;
  579. $API_UserName=get_option('paypal_certified_apiuser');
  580. $API_Password=get_option('paypal_certified_apipass');
  581. $API_Signature=get_option('paypal_certified_apisign');
  582. $sBNCode = "PP-ECWizard";
  583. //NVPRequest for submitting to server
  584. $nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);
  585. // Configure WP_HTTP
  586. if($USE_PROXY) {
  587. if (!defined('WP_PROXY_HOST') && !defined('WP_PROXY_PORT')) {
  588. define('WP_PROXY_HOST', $PROXY_HOST);
  589. define('WP_PROXY_PORT', $PROXY_PORT);
  590. }
  591. }
  592. add_filter('http_api_curl', 'wpsc_curl_ssl');
  593. $options = array(
  594. 'timeout' => 5,
  595. 'body' => $nvpreq,
  596. );
  597. $_SESSION['nvpReqArray']=$nvpReqArray;
  598. $nvpReqArray=paypal_deformatNVP($nvpreq);
  599. $res = wp_remote_post($API_Endpoint, $options);
  600. if ( is_wp_error($res) ) {
  601. $_SESSION['curl_error_msg'] = 'WP HTTP Error: ' . $res->get_error_message();
  602. $nvpResArray=paypal_deformatNVP('');
  603. } else {
  604. $nvpResArray=paypal_deformatNVP($res['body']);
  605. }
  606. return $nvpResArray;
  607. }
  608. function paypal_deformatNVP($nvpstr) {
  609. $intial=0;
  610. $nvpArray = array();
  611. while(strlen($nvpstr)) {
  612. //postion of Key
  613. $keypos= strpos($nvpstr,'=');
  614. //position of value
  615. $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
  616. /*getting the Key and Value values and storing in a Associative Array*/
  617. $keyval=substr($nvpstr,$intial,$keypos);
  618. $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
  619. //decoding the respose
  620. $nvpArray[urldecode($keyval)] =urldecode( $valval);
  621. $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
  622. }
  623. return $nvpArray;
  624. }
  625. add_action('init', 'paypal_processingfunctions');
  626. ?>