PageRenderTime 52ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/htdocs/paypal/lib/paypal.lib.php

https://bitbucket.org/speedealing/speedealing
PHP | 790 lines | 430 code | 87 blank | 273 comment | 99 complexity | b1297996b5c640d966b404521f393dd7 MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-3.0, MIT
  1. <?php
  2. /* Copyright (C) 2008-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2011-2012 Regis Houssin <regis.houssin@capnetworks.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/paypal/lib/paypal.lib.php
  20. * \ingroup paypal
  21. * \brief Library for common paypal functions
  22. */
  23. /**
  24. * Show header
  25. *
  26. * @param string $title Title
  27. * @param string $head More header to add
  28. * @return void
  29. */
  30. function llxHeaderPaypal($title, $head = "")
  31. {
  32. global $user, $conf, $langs;
  33. header("Content-type: text/html; charset=".$conf->file->character_set_client);
  34. print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
  35. //print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd>';
  36. print "\n";
  37. print "<html>\n";
  38. print "<head>\n";
  39. print '<meta name="robots" content="noindex,nofollow">'."\n";
  40. print '<meta name="keywords" content="dolibarr,payment,online">'."\n";
  41. print '<meta name="description" content="Welcome on Dolibarr online payment form">'."\n";
  42. print "<title>".$title."</title>\n";
  43. if ($head) print $head."\n";
  44. if (! empty($conf->global->PAYPAL_CSS_URL)) print '<link rel="stylesheet" type="text/css" href="'.$conf->global->PAYPAL_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
  45. else
  46. {
  47. print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.$conf->css.'?lang='.$langs->defaultlang.'">'."\n";
  48. print '<style type="text/css">';
  49. print '.CTableRow1 { margin: 1px; padding: 3px; font: 12px verdana,arial; background: #e6E6eE; color: #000000; -moz-border-radius-topleft:6px; -moz-border-radius-topright:6px; -moz-border-radius-bottomleft:6px; -moz-border-radius-bottomright:6px;}';
  50. print '.CTableRow2 { margin: 1px; padding: 3px; font: 12px verdana,arial; background: #FFFFFF; color: #000000; -moz-border-radius-topleft:6px; -moz-border-radius-topright:6px; -moz-border-radius-bottomleft:6px; -moz-border-radius-bottomright:6px;}';
  51. print '</style>';
  52. }
  53. if ($conf->use_javascript_ajax)
  54. {
  55. print '<!-- Includes for JQuery (Ajax library) -->'."\n";
  56. print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css" />'."\n"; // JNotify
  57. // Output standard javascript links
  58. $ext='.js';
  59. if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x01)) {
  60. $ext='.jgz';
  61. } // mini='_mini', ext='.gz'
  62. // JQuery. Must be before other includes
  63. print '<!-- Includes JS for JQuery -->'."\n";
  64. print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-latest.min'.$ext.'"></script>'."\n";
  65. // jQuery jnotify
  66. if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY))
  67. {
  68. print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js"></script>'."\n";
  69. print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/jnotify.js"></script>'."\n";
  70. }
  71. }
  72. print "</head>\n";
  73. print '<body style="margin: 20px;">'."\n";
  74. }
  75. /**
  76. * Show footer
  77. *
  78. * @return void
  79. */
  80. function llxFooterPaypal()
  81. {
  82. print "</body>\n";
  83. print "</html>\n";
  84. }
  85. /**
  86. * Show footer of company in HTML pages
  87. *
  88. * @param Societe $fromcompany Third party
  89. * @param Translate $langs Output language
  90. * @return void
  91. */
  92. function html_print_paypal_footer($fromcompany,$langs)
  93. {
  94. global $conf;
  95. // Juridical status
  96. $line1="";
  97. if ($fromcompany->forme_juridique_code)
  98. {
  99. $line1.=($line1?" - ":"").getFormeJuridiqueLabel($fromcompany->forme_juridique_code);
  100. }
  101. // Capital
  102. if ($fromcompany->capital)
  103. {
  104. $line1.=($line1?" - ":"").$langs->transnoentities("CapitalOf",$fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
  105. }
  106. // Prof Id 1
  107. if ($fromcompany->idprof1 && ($fromcompany->pays_code != 'FR' || ! $fromcompany->idprof2))
  108. {
  109. $field=$langs->transcountrynoentities("ProfId1",$fromcompany->country_code);
  110. if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
  111. $line1.=($line1?" - ":"").$field.": ".$fromcompany->idprof1;
  112. }
  113. // Prof Id 2
  114. if ($fromcompany->idprof2)
  115. {
  116. $field=$langs->transcountrynoentities("ProfId2",$fromcompany->country_code);
  117. if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
  118. $line1.=($line1?" - ":"").$field.": ".$fromcompany->idprof2;
  119. }
  120. // Second line of company infos
  121. $line2="";
  122. // Prof Id 3
  123. if ($fromcompany->idprof3)
  124. {
  125. $field=$langs->transcountrynoentities("ProfId3",$fromcompany->country_code);
  126. if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
  127. $line2.=($line2?" - ":"").$field.": ".$fromcompany->idprof3;
  128. }
  129. // Prof Id 4
  130. if ($fromcompany->idprof4)
  131. {
  132. $field=$langs->transcountrynoentities("ProfId4",$fromcompany->country_code);
  133. if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
  134. $line2.=($line2?" - ":"").$field.": ".$fromcompany->idprof4;
  135. }
  136. // IntraCommunautary VAT
  137. if ($fromcompany->tva_intra != '')
  138. {
  139. $line2.=($line2?" - ":"").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
  140. }
  141. print '<br><br><hr>'."\n";
  142. print '<center><font style="font-size: 10px;">'."\n";
  143. print $fromcompany->nom.'<br>';
  144. print $line1.'<br>';
  145. print $line2;
  146. print '</font></center>'."\n";
  147. }
  148. /**
  149. * Define head array for tabs of paypal tools setup pages
  150. *
  151. * @return Array of head
  152. */
  153. function paypaladmin_prepare_head()
  154. {
  155. global $langs, $conf;
  156. $h = 0;
  157. $head = array();
  158. $head[$h][0] = DOL_URL_ROOT."/paypal/admin/paypal.php";
  159. $head[$h][1] = $langs->trans("Account");
  160. $head[$h][2] = 'paypalaccount';
  161. $h++;
  162. $object=new stdClass();
  163. // Show more tabs from modules
  164. // Entries must be declared in modules descriptor with line
  165. // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
  166. // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab
  167. complete_head_from_modules($conf,$langs,$object,$head,$h,'paypaladmin');
  168. return $head;
  169. }
  170. /**
  171. * Return string with full Url
  172. *
  173. * @param string $type Type of URL ('free', 'order', 'invoice', 'contractline', 'membersubscription' ...)
  174. * @param string $ref Ref of object
  175. * @return string Url string
  176. */
  177. function showPaypalPaymentUrl($type,$ref)
  178. {
  179. global $conf, $langs;
  180. $langs->load("paypal");
  181. $langs->load("paybox");
  182. $servicename='PayPal';
  183. $out='<br><br>';
  184. $out.=img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePayment",$servicename).'<br>';
  185. $url=getPaypalPaymentUrl(0,$type,$ref);
  186. $out.='<input type="text" id="paypalurl" value="'.$url.'" size="60"><br>';
  187. return $out;
  188. }
  189. /**
  190. * Return string with full Url
  191. *
  192. * @param int $mode 0=True url, 1=Url formated with colors
  193. * @param string $type Type of URL ('free', 'order', 'invoice', 'contractline', 'membersubscription' ...)
  194. * @param string $ref Ref of object
  195. * @param int $amount Amount
  196. * @param string $freetag Free tag
  197. * @return string Url string
  198. */
  199. function getPaypalPaymentUrl($mode,$type,$ref='',$amount='9.99',$freetag='your_free_tag')
  200. {
  201. global $conf;
  202. if ($type == 'free')
  203. {
  204. $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode?'<font color="#666666">':'').$amount.($mode?'</font>':'').'&tag='.($mode?'<font color="#666666">':'').$freetag.($mode?'</font>':'');
  205. if (! empty($conf->global->PAYPAL_SECURITY_TOKEN))
  206. {
  207. if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
  208. else $out.='&securekey='.dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
  209. }
  210. }
  211. if ($type == 'order')
  212. {
  213. $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode?'<font color="#666666">':'');
  214. if ($mode == 1) $out.='order_ref';
  215. if ($mode == 0) $out.=urlencode($ref);
  216. $out.=($mode?'</font>':'');
  217. if (! empty($conf->global->PAYPAL_SECURITY_TOKEN))
  218. {
  219. if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
  220. else
  221. {
  222. $out.='&securekey='.($mode?'<font color="#666666">':'');
  223. if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + order + order_ref)";
  224. if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'order' . $ref, 2);
  225. $out.=($mode?'</font>':'');
  226. }
  227. }
  228. }
  229. if ($type == 'invoice')
  230. {
  231. $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode?'<font color="#666666">':'');
  232. if ($mode == 1) $out.='invoice_ref';
  233. if ($mode == 0) $out.=urlencode($ref);
  234. $out.=($mode?'</font>':'');
  235. if (! empty($conf->global->PAYPAL_SECURITY_TOKEN))
  236. {
  237. if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
  238. else
  239. {
  240. $out.='&securekey='.($mode?'<font color="#666666">':'');
  241. if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + invoice + invoice_ref)";
  242. if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'invoice' . $ref, 2);
  243. $out.=($mode?'</font>':'');
  244. }
  245. }
  246. }
  247. if ($type == 'contractline')
  248. {
  249. $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode?'<font color="#666666">':'');
  250. if ($mode == 1) $out.='contractline_ref';
  251. if ($mode == 0) $out.=urlencode($ref);
  252. $out.=($mode?'</font>':'');
  253. if (! empty($conf->global->PAYPAL_SECURITY_TOKEN))
  254. {
  255. if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
  256. else
  257. {
  258. $out.='&securekey='.($mode?'<font color="#666666">':'');
  259. if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + contactline + contractline_ref)";
  260. if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $ref, 2);
  261. $out.=($mode?'</font>':'');
  262. }
  263. }
  264. }
  265. if ($type == 'membersubscription')
  266. {
  267. $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode?'<font color="#666666">':'');
  268. if ($mode == 1) $out.='member_ref';
  269. if ($mode == 0) $out.=urlencode($ref);
  270. $out.=($mode?'</font>':'');
  271. if (! empty($conf->global->PAYPAL_SECURITY_TOKEN))
  272. {
  273. if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN;
  274. else
  275. {
  276. $out.='&securekey='.($mode?'<font color="#666666">':'');
  277. if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + membersubscription + member_ref)";
  278. if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'membersubscription' . $ref, 2);
  279. $out.=($mode?'</font>':'');
  280. }
  281. }
  282. }
  283. return $out;
  284. }
  285. /**
  286. * Send redirect to paypal to browser
  287. *
  288. * @param float $paymentAmount Amount
  289. * @param string $currencyCodeType Currency code
  290. * @param string $paymentType Payment type
  291. * @param string $returnURL Url to use if payment is OK
  292. * @param string $cancelURL Url to use if payment is KO
  293. * @param string $tag Tag
  294. * @return void
  295. */
  296. function print_paypal_redirect($paymentAmount,$currencyCodeType,$paymentType,$returnURL,$cancelURL,$tag)
  297. {
  298. //declaring of global variables
  299. global $conf, $langs;
  300. global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  301. global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
  302. global $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum;
  303. global $email, $desc;
  304. //'------------------------------------
  305. //' Calls the SetExpressCheckout API call
  306. //'
  307. //'-------------------------------------------------
  308. if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral';
  309. $solutionType='Sole';
  310. $landingPage='Billing';
  311. // For payment with Paypal only
  312. if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly')
  313. {
  314. $solutionType='Mark';
  315. $landingPage='Login';
  316. }
  317. // For payment with Credit card or Paypal
  318. if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral')
  319. {
  320. $solutionType='Sole';
  321. $landingPage='Billing';
  322. }
  323. // For payment with Credit card
  324. if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly')
  325. {
  326. $solutionType='Sole';
  327. $landingPage='Billing';
  328. }
  329. dol_syslog("expresscheckout redirect with callSetExpressCheckout $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum");
  330. $resArray = callSetExpressCheckout(
  331. $paymentAmount,
  332. $currencyCodeType,
  333. $paymentType,
  334. $returnURL,
  335. $cancelURL,
  336. $tag,
  337. $solutionType,
  338. $landingPage,
  339. $shipToName,
  340. $shipToStreet,
  341. $shipToCity,
  342. $shipToState,
  343. $shipToCountryCode,
  344. $shipToZip,
  345. $shipToStreet2,
  346. $phoneNum,
  347. $email,
  348. $desc
  349. );
  350. $ack = strtoupper($resArray["ACK"]);
  351. if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
  352. {
  353. $token=$resArray["TOKEN"];
  354. // Redirect to paypal.com here
  355. $payPalURL = $API_Url . $token;
  356. header("Location: ".$payPalURL);
  357. exit;
  358. }
  359. else
  360. {
  361. //Display a user friendly Error on the page using any of the following error information returned by PayPal
  362. $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
  363. $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
  364. $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
  365. $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
  366. echo "SetExpressCheckout API call failed. <br>\n";
  367. echo "Detailed Error Message: " . $ErrorLongMsg." <br>\n";
  368. echo "Short Error Message: " . $ErrorShortMsg." <br>\n";
  369. echo "Error Code: " . $ErrorCode." <br>\n";
  370. echo "Error Severity Code: " . $ErrorSeverityCode." <br>\n";
  371. }
  372. }
  373. /*
  374. '-------------------------------------------------------------------------------------------------------------------------------------------
  375. ' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
  376. ' Inputs:
  377. ' paymentAmount: Total value of the shopping cart
  378. ' currencyCodeType: Currency code value the PayPal API
  379. ' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
  380. ' returnURL: the page where buyers return to after they are done with the payment review on PayPal
  381. ' cancelURL: the page where buyers return to when they cancel the payment review on PayPal
  382. ' shipToName: the Ship to name entered on the merchant's site
  383. ' shipToStreet: the Ship to Street entered on the merchant's site
  384. ' shipToCity: the Ship to City entered on the merchant's site
  385. ' shipToState: the Ship to State entered on the merchant's site
  386. ' shipToCountryCode: the Code for Ship to Country entered on the merchant's site
  387. ' shipToZip: the Ship to ZipCode entered on the merchant's site
  388. ' shipToStreet2: the Ship to Street2 entered on the merchant's site
  389. ' phoneNum: the phoneNum entered on the merchant's site
  390. ' email: the buyer email
  391. ' desc: Product description
  392. '--------------------------------------------------------------------------------------------------------------------------------------------
  393. */
  394. function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum, $email='', $desc='')
  395. {
  396. //------------------------------------------------------------------------------------------------------------------------------------
  397. // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
  398. //declaring of global variables
  399. global $conf, $langs;
  400. global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  401. global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
  402. $nvpstr = '';
  403. $nvpstr = $nvpstr . "&AMT=". urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT
  404. $nvpstr = $nvpstr . "&PAYMENTACTION=" . urlencode($paymentType); // PAYMENTACTION deprecated by paypal -> PAYMENTREQUEST_n_PAYMENTACTION
  405. $nvpstr = $nvpstr . "&RETURNURL=" . urlencode($returnURL);
  406. $nvpstr = $nvpstr . "&CANCELURL=" . urlencode($cancelURL);
  407. $nvpstr = $nvpstr . "&CURRENCYCODE=" . urlencode($currencyCodeType); // CURRENCYCODE deprecated by paypal -> PAYMENTREQUEST_n_CURRENCYCODE
  408. $nvpstr = $nvpstr . "&ADDROVERRIDE=1";
  409. //$nvpstr = $nvpstr . "&ALLOWNOTE=0";
  410. $nvpstr = $nvpstr . "&SHIPTONAME=" . urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME
  411. $nvpstr = $nvpstr . "&SHIPTOSTREET=" . urlencode($shipToStreet); //
  412. $nvpstr = $nvpstr . "&SHIPTOSTREET2=" . urlencode($shipToStreet2);
  413. $nvpstr = $nvpstr . "&SHIPTOCITY=" . urlencode($shipToCity);
  414. $nvpstr = $nvpstr . "&SHIPTOSTATE=" . urlencode($shipToState);
  415. $nvpstr = $nvpstr . "&SHIPTOCOUNTRYCODE=" . urlencode($shipToCountryCode);
  416. $nvpstr = $nvpstr . "&SHIPTOZIP=" . urlencode($shipToZip);
  417. $nvpstr = $nvpstr . "&PHONENUM=" . urlencode($phoneNum);
  418. $nvpstr = $nvpstr . "&SOLUTIONTYPE=" . urlencode($solutionType);
  419. $nvpstr = $nvpstr . "&LANDINGPAGE=" . urlencode($landingPage);
  420. //$nvpstr = $nvpstr . "&CUSTOMERSERVICENUMBER=" . urlencode($tag); // Hotline phone number
  421. $nvpstr = $nvpstr . "&INVNUM=" . urlencode($tag);
  422. if (! empty($email)) $nvpstr = $nvpstr . "&EMAIL=" . urlencode($email);
  423. if (! empty($desc)) $nvpstr = $nvpstr . "&DESC=" . urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC
  424. $_SESSION["currencyCodeType"] = $currencyCodeType;
  425. $_SESSION["PaymentType"] = $paymentType;
  426. //'---------------------------------------------------------------------------------------------------------------
  427. //' Make the API call to PayPal
  428. //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
  429. //' If an error occured, show the resulting errors
  430. //'---------------------------------------------------------------------------------------------------------------
  431. $resArray=hash_call("SetExpressCheckout", $nvpstr);
  432. $ack = strtoupper($resArray["ACK"]);
  433. if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
  434. {
  435. $token = urldecode($resArray["TOKEN"]);
  436. $_SESSION['TOKEN']=$token;
  437. $_SESSION['ipaddress']=$_SERVER['REMOTE_ADDR ']; // Payer ip
  438. }
  439. return $resArray;
  440. }
  441. /**
  442. * Prepares the parameters for the GetExpressCheckoutDetails API Call.
  443. *
  444. * @param string $token Token
  445. * @return array The NVP Collection object of the GetExpressCheckoutDetails Call Response.
  446. */
  447. function getDetails($token)
  448. {
  449. //'--------------------------------------------------------------
  450. //' At this point, the buyer has completed authorizing the payment
  451. //' at PayPal. The function will call PayPal to obtain the details
  452. //' of the authorization, incuding any shipping information of the
  453. //' buyer. Remember, the authorization is not a completed transaction
  454. //' at this state - the buyer still needs an additional step to finalize
  455. //' the transaction
  456. //'--------------------------------------------------------------
  457. //declaring of global variables
  458. global $conf, $langs;
  459. global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  460. global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
  461. //'---------------------------------------------------------------------------
  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. //'---------------------------------------------------------------------------
  467. //' Make the API call and store the results in an array.
  468. //' If the call was a success, show the authorization details, and provide
  469. //' an action to complete the payment.
  470. //' If failed, show the error
  471. //'---------------------------------------------------------------------------
  472. $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
  473. $ack = strtoupper($resArray["ACK"]);
  474. if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING")
  475. {
  476. $_SESSION['payer_id'] = $resArray['PAYERID'];
  477. }
  478. return $resArray;
  479. }
  480. /**
  481. * Validate payment
  482. *
  483. * @param string $token Token
  484. * @param string $paymentType Type
  485. * @param string $currencyCodeType Currency
  486. * @param string $payerID Payer ID
  487. * @param string $ipaddress IP Address
  488. * @param string $FinalPaymentAmt Amount
  489. * @param string $tag Tag
  490. * @return void
  491. */
  492. function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
  493. {
  494. /* Gather the information to make the final call to
  495. finalize the PayPal payment. The variable nvpstr
  496. holds the name value pairs
  497. */
  498. //declaring of global variables
  499. global $conf, $langs;
  500. global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  501. global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
  502. $nvpstr = '';
  503. $nvpstr .= '&TOKEN=' . urlencode($token);
  504. $nvpstr .= '&PAYERID=' . urlencode($payerID);
  505. $nvpstr .= '&PAYMENTACTION=' . urlencode($paymentType);
  506. $nvpstr .= '&AMT=' . urlencode($FinalPaymentAmt);
  507. $nvpstr .= '&CURRENCYCODE=' . urlencode($currencyCodeType);
  508. $nvpstr .= '&IPADDRESS=' . urlencode($ipaddress);
  509. $nvpstr .= '&INVNUM=' . urlencode($tag);
  510. /* Make the call to PayPal to finalize payment
  511. If an error occured, show the resulting errors
  512. */
  513. $resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
  514. /* Display the API response back to the browser.
  515. If the response from PayPal was a success, display the response parameters'
  516. If the response was an error, display the errors received using APIError.php.
  517. */
  518. $ack = strtoupper($resArray["ACK"]);
  519. return $resArray;
  520. }
  521. /**
  522. * This function makes a DoDirectPayment API call
  523. *
  524. * paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
  525. * paymentAmount: total value of the shopping cart
  526. * currencyCode: currency code value the PayPal API
  527. * firstName: first name as it appears on credit card
  528. * lastName: last name as it appears on credit card
  529. * street: buyer's street address line as it appears on credit card
  530. * city: buyer's city
  531. * state: buyer's state
  532. * countryCode: buyer's country code
  533. * zip: buyer's zip
  534. * creditCardType: buyer's credit card type (i.e. Visa, MasterCard ... )
  535. * creditCardNumber: buyers credit card number without any spaces, dashes or any other characters
  536. * expDate: credit card expiration date
  537. * cvv2: Card Verification Value
  538. * @return array The NVP Collection object of the DoDirectPayment Call Response.
  539. */
  540. /*
  541. function DirectPayment($paymentType, $paymentAmount, $creditCardType, $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, $countryCode, $currencyCode, $tag)
  542. {
  543. //declaring of global variables
  544. global $conf, $langs;
  545. global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  546. global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
  547. //Construct the parameter string that describes DoDirectPayment
  548. $nvpstr = '';
  549. $nvpstr = $nvpstr . "&AMT=" . urlencode($paymentAmount); // deprecated by paypal
  550. $nvpstr = $nvpstr . "&CURRENCYCODE=" . urlencode($currencyCode);
  551. $nvpstr = $nvpstr . "&PAYMENTACTION=" . urlencode($paymentType); // deprecated by paypal
  552. $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . urlencode($creditCardType);
  553. $nvpstr = $nvpstr . "&ACCT=" . urlencode($creditCardNumber);
  554. $nvpstr = $nvpstr . "&EXPDATE=" . urlencode($expDate);
  555. $nvpstr = $nvpstr . "&CVV2=" . urlencode($cvv2);
  556. $nvpstr = $nvpstr . "&FIRSTNAME=" . urlencode($firstName);
  557. $nvpstr = $nvpstr . "&LASTNAME=" . urlencode($lastName);
  558. $nvpstr = $nvpstr . "&STREET=" . urlencode($street);
  559. $nvpstr = $nvpstr . "&CITY=" . urlencode($city);
  560. $nvpstr = $nvpstr . "&STATE=" . urlencode($state);
  561. $nvpstr = $nvpstr . "&COUNTRYCODE=" . urlencode($countryCode);
  562. $nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
  563. $nvpstr = $nvpstr . "&INVNUM=" . urlencode($tag);
  564. $resArray=hash_call("DoDirectPayment", $nvpstr);
  565. return $resArray;
  566. }
  567. */
  568. /**
  569. * hash_call: Function to perform the API call to PayPal using API signature
  570. *
  571. * @param string $methodName is name of API method.
  572. * @param string $nvpStr is nvp string.
  573. * @return array returns an associtive array containing the response from the server.
  574. */
  575. function hash_call($methodName,$nvpStr)
  576. {
  577. //declaring of global variables
  578. global $conf, $langs;
  579. global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT, $PROXY_USER, $PROXY_PASS;
  580. global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE;
  581. // TODO problem with triggers
  582. $API_version="56";
  583. if (! empty($conf->global->PAYPAL_API_SANDBOX))
  584. {
  585. $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
  586. $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
  587. }
  588. else
  589. {
  590. $API_Endpoint = "https://api-3t.paypal.com/nvp";
  591. $API_Url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
  592. }
  593. // Clean parameters
  594. $PAYPAL_API_USER="";
  595. if (! empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER=$conf->global->PAYPAL_API_USER;
  596. $PAYPAL_API_PASSWORD="";
  597. if (! empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD=$conf->global->PAYPAL_API_PASSWORD;
  598. $PAYPAL_API_SIGNATURE="";
  599. if (! empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE=$conf->global->PAYPAL_API_SIGNATURE;
  600. $PAYPAL_API_SANDBOX="";
  601. if (! empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX=$conf->global->PAYPAL_API_SANDBOX;
  602. // TODO END problem with triggers
  603. dol_syslog("Paypal API endpoint ".$API_Endpoint);
  604. //setting the curl parameters.
  605. $ch = curl_init();
  606. /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."<br>";
  607. print $USE_PROXY."-".$gv_ApiErrorURL."<br>";
  608. print $nvpStr;
  609. exit;*/
  610. curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
  611. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  612. curl_setopt($ch, CURLOPT_SSLVERSION, 3); // Force SSLv3
  613. //turning off the server and peer verification(TrustManager Concept).
  614. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  615. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  616. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  617. curl_setopt($ch, CURLOPT_POST, 1);
  618. //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
  619. if ($USE_PROXY)
  620. {
  621. dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST. ":" . $PROXY_PORT." - ".$PROXY_USER. ":" . $PROXY_PASS);
  622. //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
  623. curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);
  624. if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER. ":" . $PROXY_PASS);
  625. }
  626. //NVPRequest for submitting to server
  627. $nvpreq ="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($API_version) . "&PWD=" . urlencode($PAYPAL_API_PASSWORD) . "&USER=" . urlencode($PAYPAL_API_USER) . "&SIGNATURE=" . urlencode($PAYPAL_API_SIGNATURE) . $nvpStr;
  628. $nvpreq.="&LOCALECODE=".strtoupper($langs->getDefaultLang(1));
  629. //$nvpreq.="&BRANDNAME=".urlencode(); // Override merchant name
  630. //$nvpreq.="&NOTIFYURL=".urlencode(); // For Instant Payment Notification url
  631. dol_syslog("Paypal API hash_call nvpreq=".$nvpreq);
  632. //setting the nvpreq as POST FIELD to curl
  633. curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
  634. //getting response from server
  635. $response = curl_exec($ch);
  636. $nvpReqArray=deformatNVP($nvpreq);
  637. $_SESSION['nvpReqArray']=$nvpReqArray;
  638. //convrting NVPResponse to an Associative Array
  639. dol_syslog("Paypal API hash_call Response nvpresp=".$response);
  640. $nvpResArray=deformatNVP($response);
  641. if (curl_errno($ch))
  642. {
  643. // moving to display page to display curl errors
  644. $_SESSION['curl_error_no']=curl_errno($ch);
  645. $_SESSION['curl_error_msg']=curl_error($ch);
  646. //Execute the Error handling module to display errors.
  647. }
  648. else
  649. {
  650. //closing the curl
  651. curl_close($ch);
  652. }
  653. return $nvpResArray;
  654. }
  655. /**
  656. * This function will take NVPString and convert it to an Associative Array and it will decode the response.
  657. * It is usefull to search for a particular key and displaying arrays.
  658. *
  659. * @param string $nvpstr NVPString
  660. * @return array nvpArray = Associative Array
  661. */
  662. function deformatNVP($nvpstr)
  663. {
  664. $intial=0;
  665. $nvpArray = array();
  666. while(strlen($nvpstr))
  667. {
  668. //postion of Key
  669. $keypos= strpos($nvpstr,'=');
  670. //position of value
  671. $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
  672. /*getting the Key and Value values and storing in a Associative Array*/
  673. $keyval=substr($nvpstr,$intial,$keypos);
  674. $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
  675. //decoding the respose
  676. $nvpArray[urldecode($keyval)] =urldecode($valval);
  677. $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
  678. }
  679. return $nvpArray;
  680. }
  681. /**
  682. * Get API errors
  683. *
  684. * @return array Array of errors
  685. */
  686. function getApiError()
  687. {
  688. $errors=array();
  689. $resArray=$_SESSION['reshash'];
  690. if(isset($_SESSION['curl_error_no']))
  691. {
  692. $errors[] = $_SESSION['curl_error_no'].'-'.$_SESSION['curl_error_msg'];
  693. }
  694. foreach($resArray as $key => $value)
  695. {
  696. $errors[] = $key.'-'.$value;
  697. }
  698. return $errors;
  699. }
  700. ?>