paypalfunctions.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. /*
  3. * PayPal API Module
  4. *
  5. * Defines all the global variables and the wrapper functions
  6. */
  7. $PROXY_HOST = '127.0.0.1';
  8. $PROXY_PORT = '808';
  9. $SandboxFlag = $pruebas;
  10. /**
  11. * PayPal API Credentials
  12. * Replace <API_USERNAME> with your API Username
  13. * Replace <API_PASSWORD> with your API Password
  14. * Replace <API_SIGNATURE> with your Signature.
  15. */
  16. $API_UserName = $paypalUsername;
  17. $API_Password = $paypalPassword;
  18. $API_Signature = $paypalSignature;
  19. // BN Code is only applicable for partners
  20. $sBNCode = "PP-ECWizard";
  21. /**
  22. * Define the PayPal Redirect URLs.
  23. * This is the URL that the buyer is first sent to do authorize payment with their paypal account
  24. * change the URL depending if you are testing on the sandbox or the live PayPal site.
  25. *
  26. * For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
  27. * For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token=
  28. */
  29. if ($SandboxFlag == true) {
  30. $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
  31. $PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
  32. } else {
  33. $API_Endpoint = "https://api-3t.paypal.com/nvp";
  34. $PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
  35. }
  36. $USE_PROXY = false;
  37. $version = "93";
  38. if (session_id() == "") {
  39. session_start();
  40. }
  41. /**
  42. * An express checkout transaction starts with a token, that
  43. * identifies to PayPal your transaction
  44. * In this example, when the script sees a token, the script
  45. * knows that the buyer has already authorized payment through
  46. * paypal. If no token was found, the action is to send the buyer
  47. * to PayPal to first authorize payment.
  48. */
  49. /**
  50. * Purpose: Prepares the parameters for the SetExpressCheckout API Call.
  51. * Inputs:
  52. * paymentAmount: Total value of the shopping cart
  53. * currencyCodeType: Currency code value the PayPal API
  54. * paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
  55. * returnURL: the page where buyers return to after they are done with the payment review on PayPal
  56. * cancelURL: the page where buyers return to when they cancel the payment review on PayPal.
  57. */
  58. function CallShortcutExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $extra)
  59. {
  60. // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
  61. $nvpstr = "&PAYMENTREQUEST_0_AMT=".$paymentAmount;
  62. $nvpstr .= "&PAYMENTREQUEST_0_ITEMAMT=".$paymentAmount;
  63. $nvpstr .= "&PAYMENTREQUEST_0_PAYMENTACTION=".$paymentType;
  64. $nvpstr .= "&RETURNURL=".$returnURL;
  65. $nvpstr .= "&CANCELURL=".$cancelURL;
  66. $nvpstr .= "&PAYMENTREQUEST_0_CURRENCYCODE=".$currencyCodeType;
  67. $nvpstr .= $extra;
  68. $_SESSION["currencyCodeType"] = $currencyCodeType;
  69. $_SESSION["PaymentType"] = $paymentType;
  70. /**
  71. * Make the API call to PayPal
  72. * If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
  73. * If an error occured, show the resulting errors.
  74. */
  75. $resArray = hash_call("SetExpressCheckout", $nvpstr);
  76. $ack = strtoupper($resArray["ACK"]);
  77. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  78. $token = urldecode($resArray["TOKEN"]);
  79. $_SESSION['TOKEN'] = $token;
  80. }
  81. return $resArray;
  82. }
  83. /**
  84. * Purpose: Prepares the parameters for the SetExpressCheckout API Call.
  85. * Inputs:
  86. * paymentAmount: Total value of the shopping cart
  87. * currencyCodeType: Currency code value the PayPal API
  88. * paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
  89. * returnURL: the page where buyers return to after they are done with the payment review on PayPal
  90. * cancelURL: the page where buyers return to when they cancel the payment review on PayPal
  91. * shipToName: the Ship to name entered on the merchant's site
  92. * shipToStreet: the Ship to Street entered on the merchant's site
  93. * shipToCity: the Ship to City entered on the merchant's site
  94. * shipToState: the Ship to State entered on the merchant's site
  95. * shipToCountryCode: the Code for Ship to Country entered on the merchant's site
  96. * shipToZip: the Ship to ZipCode entered on the merchant's site
  97. * shipToStreet2: the Ship to Street2 entered on the merchant's site
  98. * phoneNum: the phoneNum entered on the merchant's site.
  99. */
  100. function CallMarkExpressCheckout(
  101. $paymentAmount,
  102. $currencyCodeType,
  103. $paymentType,
  104. $returnURL,
  105. $cancelURL,
  106. $shipToName,
  107. $shipToStreet,
  108. $shipToCity,
  109. $shipToState,
  110. $shipToCountryCode,
  111. $shipToZip,
  112. $shipToStreet2,
  113. $phoneNum
  114. ) {
  115. // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
  116. $nvpstr = "&PAYMENTREQUEST_0_AMT=".$paymentAmount;
  117. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_PAYMENTACTION=".$paymentType;
  118. $nvpstr = $nvpstr."&RETURNURL=".$returnURL;
  119. $nvpstr = $nvpstr."&CANCELURL=".$cancelURL;
  120. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_CURRENCYCODE=".$currencyCodeType;
  121. $nvpstr = $nvpstr."&ADDROVERRIDE=1";
  122. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTONAME=".$shipToName;
  123. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOSTREET=".$shipToStreet;
  124. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOSTREET2=".$shipToStreet2;
  125. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOCITY=".$shipToCity;
  126. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOSTATE=".$shipToState;
  127. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=".$shipToCountryCode;
  128. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOZIP=".$shipToZip;
  129. $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOPHONENUM=".$phoneNum;
  130. $_SESSION["currencyCodeType"] = $currencyCodeType;
  131. $_SESSION["PaymentType"] = $paymentType;
  132. /**
  133. * Make the API call to PayPal
  134. * If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
  135. * If an error occured, show the resulting errors.
  136. */
  137. $resArray = hash_call("SetExpressCheckout", $nvpstr);
  138. $ack = strtoupper($resArray["ACK"]);
  139. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  140. $token = urldecode($resArray["TOKEN"]);
  141. $_SESSION['TOKEN'] = $token;
  142. }
  143. return $resArray;
  144. }
  145. /**
  146. * Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
  147. *
  148. * Inputs:
  149. * None
  150. * Returns:
  151. * The NVP Collection object of the GetExpressCheckoutDetails Call Response.
  152. */
  153. function GetShippingDetails($token)
  154. {
  155. /**
  156. * At this point, the buyer has completed authorizing the payment
  157. * at PayPal. The function will call PayPal to obtain the details
  158. * of the authorization, including any shipping information of the
  159. * buyer. Remember, the authorization is not a completed transaction
  160. * at this state - the buyer still needs an additional step to finalize
  161. * the transaction.
  162. *
  163. * Build a second API request to PayPal, using the token as the
  164. * ID to get the details on the payment authorization
  165. */
  166. $nvpstr = "&TOKEN=".$token;
  167. /**
  168. * Make the API call and store the results in an array.
  169. * If the call was a success, show the authorization details, and provide
  170. * an action to complete the payment.
  171. * If failed, show the error.
  172. */
  173. $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
  174. $ack = strtoupper($resArray["ACK"]);
  175. if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
  176. $_SESSION['payer_id'] = $resArray['PAYERID'];
  177. }
  178. return $resArray;
  179. }
  180. /**
  181. * Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
  182. * Inputs:
  183. * sBNCode: The BN code used by PayPal to track the transactions from a given shopping cart.
  184. * Returns:
  185. * The NVP Collection object of the GetExpressCheckoutDetails Call Response.
  186. */
  187. function ConfirmPayment($FinalPaymentAmt)
  188. {
  189. /**
  190. * Gather the information to make the final call to
  191. * finalize the PayPal payment. The variable nvpstr
  192. * holds the name value pairs.
  193. */
  194. //Format the other parameters that were stored in the session from the previous calls
  195. $token = urlencode($_SESSION['TOKEN']);
  196. $paymentType = urlencode($_SESSION['PaymentType']);
  197. $currencyCodeType = urlencode($_SESSION['currencyCodeType']);
  198. $payerID = urlencode($_SESSION['payer_id']);
  199. $serverName = urlencode($_SERVER['SERVER_NAME']);
  200. $nvpstr =
  201. '&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTREQUEST_0_PAYMENTACTION='.$paymentType.'&PAYMENTREQUEST_0_AMT='
  202. .$FinalPaymentAmt;
  203. $nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE='.$currencyCodeType.'&IPADDRESS='.$serverName;
  204. $nvpstr = '&'.http_build_query([
  205. 'TOKEN' => $token,
  206. 'PAYERID' => $payerID,
  207. 'PAYMENTACTION' => $paymentType,
  208. 'PAYMENTREQUEST_0_AMT' => $FinalPaymentAmt,
  209. 'PAYMENTREQUEST_0_CURRENCYCODE' => $currencyCodeType,
  210. 'IPADDRESS' => $serverName,
  211. 'paymentactionspecified' => 'true',
  212. ]);
  213. /**
  214. * Make the call to PayPal to finalize payment
  215. * If an error occured, show the resulting errors.
  216. */
  217. $resArray = hash_call("DoExpressCheckoutPayment", $nvpstr);
  218. /**
  219. * Display the API response back to the browser.
  220. * If the response from PayPal was a success, display the response parameters
  221. * If the response was an error, display the errors received using APIError.php.
  222. */
  223. $ack = strtoupper($resArray["ACK"]);
  224. return $resArray;
  225. }
  226. /**
  227. * Purpose: This function makes a DoDirectPayment API call
  228. * Inputs:
  229. * paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
  230. * paymentAmount: total value of the shopping cart
  231. * currencyCode: currency code value the PayPal API
  232. * firstName: first name as it appears on credit card
  233. * lastName: last name as it appears on credit card
  234. * street: buyer's street address line as it appears on credit card
  235. * city: buyer's city
  236. * state: buyer's state
  237. * countryCode: buyer's country code
  238. * zip: buyer's zip
  239. * creditCardType: buyer's credit card type (i.e. Visa, MasterCard ... )
  240. * creditCardNumber: buyers credit card number without any spaces, dashes or any other characters
  241. * expDate: credit card expiration date
  242. * cvv2: Card Verification Value
  243. * Returns:
  244. * The NVP Collection object of the DoDirectPayment Call Response.
  245. */
  246. function DirectPayment(
  247. $paymentType,
  248. $paymentAmount,
  249. $creditCardType,
  250. $creditCardNumber,
  251. $expDate,
  252. $cvv2,
  253. $firstName,
  254. $lastName,
  255. $street,
  256. $city,
  257. $state,
  258. $zip,
  259. $countryCode,
  260. $currencyCode
  261. ) {
  262. //Construct the parameter string that describes DoDirectPayment
  263. $nvpstr = "&AMT=".$paymentAmount;
  264. $nvpstr = $nvpstr."&CURRENCYCODE=".$currencyCode;
  265. $nvpstr = $nvpstr."&PAYMENTACTION=".$paymentType;
  266. $nvpstr = $nvpstr."&CREDITCARDTYPE=".$creditCardType;
  267. $nvpstr = $nvpstr."&ACCT=".$creditCardNumber;
  268. $nvpstr = $nvpstr."&EXPDATE=".$expDate;
  269. $nvpstr = $nvpstr."&CVV2=".$cvv2;
  270. $nvpstr = $nvpstr."&FIRSTNAME=".$firstName;
  271. $nvpstr = $nvpstr."&LASTNAME=".$lastName;
  272. $nvpstr = $nvpstr."&STREET=".$street;
  273. $nvpstr = $nvpstr."&CITY=".$city;
  274. $nvpstr = $nvpstr."&STATE=".$state;
  275. $nvpstr = $nvpstr."&COUNTRYCODE=".$countryCode;
  276. $nvpstr = $nvpstr."&IPADDRESS=".$_SERVER['REMOTE_ADDR'];
  277. $resArray = hash_call("DoDirectPayment", $nvpstr);
  278. return $resArray;
  279. }
  280. /**
  281. * Purpose: This function makes a MassPay API call
  282. * Inputs:
  283. * Beneficiarie: Array that contains the Beneficiearie paypal account and the payout amount
  284. * Currency Code: The currency Iso code
  285. * Returns:
  286. * The NVP Collection object of the MassPay Call Response.
  287. */
  288. function MassPayment(array $beneficiaries, $currencyCode)
  289. {
  290. $nvpstr = "&RECEIVERTYPE=EmailAddress";
  291. $nvpstr .= "&CURRENCYCODE=".$currencyCode;
  292. $index = 0;
  293. foreach ($beneficiaries as $beneficiary) {
  294. $nvpstr .= "&L_EMAIL".$index."=".$beneficiary['paypal_account'];
  295. $nvpstr .= "&L_AMT".$index."=".$beneficiary['commission'];
  296. $index++;
  297. }
  298. $resArray = hash_call("MassPay", $nvpstr);
  299. return $resArray;
  300. }
  301. /**
  302. * hash_call: Function to perform the API call to PayPal using API signature.
  303. *
  304. * @methodName is name of API method.
  305. * @nvpStr is nvp string.
  306. * returns an associtive array containing the response from the server.
  307. */
  308. function hash_call($methodName, $nvpStr)
  309. {
  310. //declaring of global variables
  311. global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
  312. global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  313. global $sBNCode;
  314. //setting the curl parameters.
  315. $ch = curl_init();
  316. curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
  317. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  318. //turning off the server and peer verification(TrustManager Concept).
  319. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  320. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  321. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  322. curl_setopt($ch, CURLOPT_POST, 1);
  323. //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
  324. //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
  325. if ($USE_PROXY) {
  326. curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
  327. }
  328. //NVPRequest for submitting to server
  329. $nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($version).
  330. "&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName).
  331. "&SIGNATURE=".urlencode($API_Signature).$nvpStr."&BUTTONSOURCE=".urlencode($sBNCode);
  332. //setting the nvpreq as POST FIELD to curl
  333. curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
  334. //getting response from server
  335. $response = curl_exec($ch);
  336. //converting NVPResponse to an Associative Array
  337. $nvpResArray = deformatNVP($response);
  338. $nvpReqArray = deformatNVP($nvpreq);
  339. $_SESSION['nvpReqArray'] = $nvpReqArray;
  340. if (curl_errno($ch)) {
  341. // moving to display page to display curl errors
  342. $_SESSION['curl_error_no'] = curl_errno($ch);
  343. $_SESSION['curl_error_msg'] = curl_error($ch);
  344. //Execute the Error handling module to display errors.
  345. } else {
  346. //closing the curl
  347. curl_close($ch);
  348. }
  349. return $nvpResArray;
  350. }
  351. /**
  352. * Purpose: Redirects to PayPal.com site.
  353. * Inputs: NVP string.
  354. */
  355. function RedirectToPayPal($token)
  356. {
  357. global $PAYPAL_URL;
  358. // Redirect to paypal.com here
  359. $payPalURL = $PAYPAL_URL.$token;
  360. header("Location: ".$payPalURL);
  361. exit;
  362. }
  363. /**
  364. * This function will take NVPString and convert it to an Associative Array and it will decode the response.
  365. * It is usefull to search for a particular key and displaying arrays.
  366. *
  367. * @nvpstr is NVPString.
  368. * @nvpArray is Associative Array.
  369. */
  370. function deformatNVP($nvpstr)
  371. {
  372. $intial = 0;
  373. $nvpArray = [];
  374. while (strlen($nvpstr)) {
  375. //postion of Key
  376. $keypos = strpos($nvpstr, '=');
  377. //position of value
  378. $valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr);
  379. /*getting the Key and Value values and storing in a Associative Array*/
  380. $keyval = substr($nvpstr, $intial, $keypos);
  381. $valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
  382. //decoding the respose
  383. $nvpArray[urldecode($keyval)] = urldecode($valval);
  384. $nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
  385. }
  386. return $nvpArray;
  387. }