PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/library/paypal.php

https://github.com/alugo/Goteo
PHP | 667 lines | 494 code | 87 blank | 86 comment | 48 complexity | 090f7673f76c862a8b72d798ddb0d958 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /*
  3. * Copyright (C) 2012 Platoniq y Fundación Fuentes Abiertas (see README for details)
  4. * This file is part of Goteo.
  5. *
  6. * Goteo is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Goteo is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with Goteo. If not, see <http://www.gnu.org/licenses/agpl.txt>.
  18. *
  19. */
  20. namespace Goteo\Library {
  21. use Goteo\Model\Invest,
  22. Goteo\Model\Project,
  23. Goteo\Model\User,
  24. Goteo\Library\Feed,
  25. Goteo\Core\Redirection;
  26. require_once 'library/paypal/adaptivepayments.php'; // SDK paypal para operaciones API (minimizado)
  27. /*
  28. * Clase para usar los adaptive payments de paypal
  29. */
  30. class Paypal {
  31. /**
  32. * @param object invest instancia del aporte: id, usuario, proyecto, cuenta, cantidad
  33. *
  34. * Método para crear un preapproval para un aporte
  35. * va a mandar al usuario a paypal para que confirme
  36. *
  37. * @TODO poner límite máximo de dias a lo que falte para los 40/80 dias para evitar las cancelaciones
  38. */
  39. public static function preapproval($invest, &$errors = array()) {
  40. try {
  41. $project = Project::getMini($invest->project);
  42. /* The returnURL is the location where buyers return when a
  43. payment has been succesfully authorized.
  44. The cancelURL is the location buyers are sent to when they hit the
  45. cancel button during authorization of payment during the PayPal flow */
  46. $URL = (NODE_ID != GOTEO_NODE) ? NODE_URL : SITE_URL;
  47. $returnURL = $URL."/invest/confirmed/".$invest->project."/".$invest->id; // a difundirlo @TODO mensaje gracias si llega desde un preapproval
  48. $cancelURL = $URL."/invest/fail/".$invest->project."/".$invest->id."/?amount=".$invest->amount; // a la página de aportar para intentarlo de nuevo
  49. date_default_timezone_set('UTC');
  50. $currDate = getdate();
  51. $hoy = $currDate['year'].'-'.$currDate['mon'].'-'.$currDate['mday'];
  52. $startDate = strtotime($hoy);
  53. $startDate = date('Y-m-d', mktime(date('h',$startDate),date('i',$startDate),0,date('m',$startDate),date('d',$startDate),date('Y',$startDate)));
  54. $endDate = strtotime($hoy);
  55. $endDate = date('Y-m-d', mktime(0,0,0,date('m',$endDate)+5,date('d',$endDate),date('Y',$endDate)));
  56. // sí, pongo la fecha de caducidad de los preapprovals a 5 meses para tratar incidencias
  57. /* Make the call to PayPal to get the preapproval token
  58. If the API call succeded, then redirect the buyer to PayPal
  59. to begin to authorize payment. If an error occured, show the
  60. resulting errors
  61. */
  62. $preapprovalRequest = new \PreapprovalRequest();
  63. $preapprovalRequest->memo = "Aporte de {$invest->amount} EUR al proyecto: {$project->name}";
  64. $preapprovalRequest->cancelUrl = $cancelURL;
  65. $preapprovalRequest->returnUrl = $returnURL;
  66. $preapprovalRequest->clientDetails = new \ClientDetailsType();
  67. $preapprovalRequest->clientDetails->customerId = $invest->user->id;
  68. $preapprovalRequest->clientDetails->applicationId = PAYPAL_APPLICATION_ID;
  69. $preapprovalRequest->clientDetails->deviceId = PAYPAL_DEVICE_ID;
  70. $preapprovalRequest->clientDetails->ipAddress = $_SERVER['REMOTE_ADDR'];
  71. $preapprovalRequest->currencyCode = "EUR";
  72. $preapprovalRequest->startingDate = $startDate;
  73. $preapprovalRequest->endingDate = $endDate;
  74. $preapprovalRequest->maxNumberOfPayments = 1;
  75. $preapprovalRequest->displayMaxTotalAmount = true;
  76. $preapprovalRequest->feesPayer = 'EACHRECEIVER';
  77. $preapprovalRequest->maxTotalAmountOfAllPayments = $invest->amount;
  78. $preapprovalRequest->requestEnvelope = new \RequestEnvelope();
  79. $preapprovalRequest->requestEnvelope->errorLanguage = "es_ES";
  80. $ap = new \AdaptivePayments();
  81. $response=$ap->Preapproval($preapprovalRequest);
  82. if(strtoupper($ap->isSuccess) == 'FAILURE') {
  83. Invest::setDetail($invest->id, 'paypal-conection-fail', 'Ha fallado la comunicacion con paypal al iniciar el preapproval. Proceso libary/paypal::preapproval');
  84. $errors[] = 'No se ha podido iniciar la comunicación con paypal para procesar la preaprovación del cargo. ' . $ap->getLastError();
  85. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' ap->success = FAILURE.<br /><pre>' . print_r($ap, 1) . '</pre><pre>' . print_r($response, 1) . '</pre>' . $ap->getLastError());
  86. return false;
  87. }
  88. // Guardar el codigo de preaproval en el registro de aporte y mandarlo a paypal
  89. $token = $response->preapprovalKey;
  90. if (!empty($token)) {
  91. Invest::setDetail($invest->id, 'paypal-init', 'Se ha iniciado el preaproval y se redirije al usuario a paypal para aceptarlo. Proceso libary/paypal::preapproval');
  92. $invest->setPreapproval($token);
  93. $payPalURL = PAYPAL_REDIRECT_URL.'_ap-preapproval&preapprovalkey='.$token;
  94. throw new \Goteo\Core\Redirection($payPalURL, Redirection::TEMPORARY);
  95. return true;
  96. } else {
  97. Invest::setDetail($invest->id, 'paypal-init-fail', 'Ha fallado al iniciar el preapproval y no se redirije al usuario a paypal. Proceso libary/paypal::preapproval');
  98. $errors[] = 'No preapproval key obtained. <pre>' . print_r($response, 1) . '</pre>';
  99. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' No preapproval key obtained.<br /><pre>' . print_r($response, 1) . '</pre>');
  100. return false;
  101. }
  102. }
  103. catch(Exception $ex) {
  104. $fault = new \FaultMessage();
  105. $errorData = new \ErrorData();
  106. $errorData->errorId = $ex->getFile() ;
  107. $errorData->message = $ex->getMessage();
  108. $fault->error = $errorData;
  109. Invest::setDetail($invest->id, 'paypal-init-fail', 'Ha fallado al iniciar el preapproval y no se redirije al usuario a paypal. Proceso libary/paypal::preapproval');
  110. $errors[] = 'Error fatal en la comunicación con Paypal, se ha reportado la incidencia. Disculpe las molestias.';
  111. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . '<br /><pre>' . print_r($fault, 1) . '</pre>');
  112. return false;
  113. }
  114. }
  115. /*
  116. * Metodo para ejecutar pago (desde cron)
  117. * Recibe parametro del aporte (id, cuenta, cantidad)
  118. *
  119. * Es un pago encadenado, la comision del 8% a Goteo y el resto al proyecto
  120. *
  121. */
  122. public static function pay($invest, &$errors = array()) {
  123. if ($invest->status == 1) {
  124. $errors[] = 'Este aporte ya está cobrado!';
  125. @mail(\GOTEO_FAIL_MAIL, 'Dobleejecución de preapproval', 'Se intentaba ejecutar un aporte en estado Cobrado. <br /><pre>' . print_r($invest, 1) . '</pre>');
  126. return false;
  127. }
  128. try {
  129. $project = Project::getMini($invest->project);
  130. $userData = User::getMini($invest->user);
  131. // al productor le pasamos el importe del cargo menos el 8% que se queda goteo
  132. $amountPay = $invest->amount - ($invest->amount * 0.08);
  133. // Create request object
  134. $payRequest = new \PayRequest();
  135. $payRequest->memo = "Cargo del aporte de {$invest->amount} EUR del usuario '{$userData->name}' al proyecto '{$project->name}'";
  136. $payRequest->cancelUrl = SITE_URL.'/invest/charge/fail/' . $invest->id;
  137. $payRequest->returnUrl = SITE_URL.'/invest/charge/success/' . $invest->id;
  138. $payRequest->clientDetails = new \ClientDetailsType();
  139. $payRequest->clientDetails->customerId = $invest->user;
  140. $payRequest->clientDetails->applicationId = PAYPAL_APPLICATION_ID;
  141. $payRequest->clientDetails->deviceId = PAYPAL_DEVICE_ID;
  142. $payRequest->clientDetails->ipAddress = PAYPAL_IP_ADDRESS;
  143. $payRequest->currencyCode = 'EUR';
  144. $payRequest->preapprovalKey = $invest->preapproval;
  145. $payRequest->actionType = 'PAY_PRIMARY';
  146. $payRequest->feesPayer = 'EACHRECEIVER';
  147. $payRequest->reverseAllParallelPaymentsOnError = true;
  148. // $payRequest->trackingId = $invest->id;
  149. // SENDER no vale para chained payments (PRIMARYRECEIVER, EACHRECEIVER, SECONDARYONLY)
  150. $payRequest->requestEnvelope = new \RequestEnvelope();
  151. $payRequest->requestEnvelope->errorLanguage = 'es_ES';
  152. // Primary receiver, Goteo Business Account
  153. $receiverP = new \receiver();
  154. $receiverP->email = PAYPAL_BUSINESS_ACCOUNT; // tocar en config para poner en real
  155. $receiverP->amount = $invest->amount;
  156. $receiverP->primary = true;
  157. // Receiver, Projects PayPal Account
  158. $receiver = new \receiver();
  159. $receiver->email = \trim($invest->account);
  160. $receiver->amount = $amountPay;
  161. $receiver->primary = false;
  162. $payRequest->receiverList = array($receiverP, $receiver);
  163. // Create service wrapper object
  164. $ap = new \AdaptivePayments();
  165. // invoke business method on service wrapper passing in appropriate request params
  166. $response = $ap->Pay($payRequest);
  167. // Check response
  168. if(strtoupper($ap->isSuccess) == 'FAILURE') {
  169. $error_txt = '';
  170. $soapFault = $ap->getLastError();
  171. if(is_array($soapFault->error)) {
  172. $errorId = $soapFault->error[0]->errorId;
  173. $errorMsg = $soapFault->error[0]->message;
  174. } else {
  175. $errorId = $soapFault->error->errorId;
  176. $errorMsg = $soapFault->error->message;
  177. }
  178. if (is_array($soapFault->payErrorList->payError)) {
  179. $errorId = $soapFault->payErrorList->payError[0]->error->errorId;
  180. $errorMsg = $soapFault->payErrorList->payError[0]->error->message;
  181. }
  182. // tratamiento de errores
  183. switch ($errorId) {
  184. case '569013': // preapproval cancelado por el usuario desde panel paypal
  185. case '539012': // preapproval no se llegó a autorizar
  186. if ($invest->cancel()) {
  187. $action = 'Aporte cancelado';
  188. // Evento Feed
  189. $log = new Feed();
  190. $log->setTarget($project->id);
  191. $log->populate('Aporte cancelado por preaproval cancelado por el usuario paypal', '/admin/accounts',
  192. \vsprintf('Se ha <span class="red">Cancelado</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s por preapproval cancelado', array(
  193. Feed::item('user', $userData->name, $userData->id),
  194. Feed::item('money', $invest->amount.' &euro;'),
  195. Feed::item('system', $invest->id),
  196. Feed::item('project', $project->name, $project->id),
  197. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  198. )));
  199. $log->doAdmin('system');
  200. $error_txt = $log->title;
  201. unset($log);
  202. }
  203. break;
  204. case '569042': // cuenta del proyecto no confirmada en paypal
  205. // Evento Feed
  206. $log = new Feed();
  207. $log->setTarget($project->id);
  208. $log->populate('Cuenta del proyecto no confirmada en PayPal', '/admin/accounts',
  209. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque la cuenta del proyecto <span class="red">no está confirmada</span> en PayPal', array(
  210. Feed::item('user', $userData->name, $userData->id),
  211. Feed::item('money', $invest->amount.' &euro;'),
  212. Feed::item('system', $invest->id),
  213. Feed::item('project', $project->name, $project->id),
  214. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  215. )));
  216. $log->doAdmin('system');
  217. $error_txt = $log->title;
  218. unset($log);
  219. break;
  220. case '580022': // uno de los mails enviados no es valido
  221. case '589039': // el mail del preaproval no está registrada en paypal
  222. // Evento Feed
  223. $log = new Feed();
  224. $log->setTarget($project->id);
  225. $log->populate('El mail del preaproval no esta registrado en PayPal', '/admin/accounts',
  226. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque el mail del preaproval <span class="red">no está registrado</span> en PayPal', array(
  227. Feed::item('user', $userData->name, $userData->id),
  228. Feed::item('money', $invest->amount.' &euro;'),
  229. Feed::item('system', $invest->id),
  230. Feed::item('project', $project->name, $project->id),
  231. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  232. )));
  233. $log->doAdmin('system');
  234. $error_txt = $log->title;
  235. unset($log);
  236. break;
  237. case '520009': // la cuenta esta restringida por paypal
  238. // Evento Feed
  239. $log = new Feed();
  240. $log->setTarget($project->id);
  241. $log->populate('La cuenta esta restringida por PayPal', '/admin/accounts',
  242. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque la cuenta <span class="red">está restringida</span> por PayPal', array(
  243. Feed::item('user', $userData->name, $userData->id),
  244. Feed::item('money', $invest->amount.' &euro;'),
  245. Feed::item('system', $invest->id),
  246. Feed::item('project', $project->name, $project->id),
  247. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  248. )));
  249. $log->doAdmin('system');
  250. $error_txt = $log->title;
  251. unset($log);
  252. break;
  253. case '579033': // misma cuenta que el proyecto
  254. // Evento Feed
  255. $log = new Feed();
  256. $log->setTarget($project->id);
  257. $log->populate('Se ha usado la misma cuenta que del proyecto', '/admin/accounts',
  258. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque la cuenta <span class="red">es la misma</span> que la del proyecto', array(
  259. Feed::item('user', $userData->name, $userData->id),
  260. Feed::item('money', $invest->amount.' &euro;'),
  261. Feed::item('system', $invest->id),
  262. Feed::item('project', $project->name, $project->id),
  263. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  264. )));
  265. $log->doAdmin('system');
  266. $error_txt = $log->title;
  267. unset($log);
  268. break;
  269. case '579024': // fuera de fechas
  270. // Evento Feed
  271. $log = new Feed();
  272. $log->setTarget($project->id);
  273. $log->populate('Está fuera del rango de fechas', '/admin/accounts',
  274. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque estamos <span class="red">fuera del rango de fechas</span> del preapproval', array(
  275. Feed::item('user', $userData->name, $userData->id),
  276. Feed::item('money', $invest->amount.' &euro;'),
  277. Feed::item('system', $invest->id),
  278. Feed::item('project', $project->name, $project->id),
  279. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  280. )));
  281. $log->doAdmin('system');
  282. $error_txt = $log->title;
  283. unset($log);
  284. break;
  285. case '579031': // The total amount of all payments exceeds the maximum total amount for all payments
  286. // Evento Feed
  287. $log = new Feed();
  288. $log->setTarget($project->id);
  289. $log->populate('Problema con los importes', '/admin/accounts',
  290. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque ha habido <span class="red">algun problema con los importes</span>', array(
  291. Feed::item('user', $userData->name, $userData->id),
  292. Feed::item('money', $invest->amount.' &euro;'),
  293. Feed::item('system', $invest->id),
  294. Feed::item('project', $project->name, $project->id),
  295. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  296. )));
  297. $log->doAdmin('system');
  298. $error_txt = $log->title;
  299. unset($log);
  300. break;
  301. case '520002': // Internal error
  302. // Evento Feed
  303. $log = new Feed();
  304. $log->setTarget($project->id);
  305. $log->populate('Error interno de PayPal', '/admin/accounts',
  306. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s porque ha habido <span class="red">un error interno en PayPal</span>', array(
  307. Feed::item('user', $userData->name, $userData->id),
  308. Feed::item('money', $invest->amount.' &euro;'),
  309. Feed::item('system', $invest->id),
  310. Feed::item('project', $project->name, $project->id),
  311. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  312. )));
  313. $log->doAdmin('system');
  314. $error_txt = $log->title;
  315. unset($log);
  316. break;
  317. default:
  318. if (empty($errorId)) {
  319. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' No es un soap fault pero no es un success.<br /><pre>' . print_r($ap, 1) . '</pre>');
  320. $log = new Feed();
  321. $log->setTarget($project->id);
  322. $log->populate('Error interno de PayPal', '/admin/accounts',
  323. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s <span class="red">NO es soapFault pero no es Success</span>, se ha reportado el error.', array(
  324. Feed::item('user', $userData->name, $userData->id),
  325. Feed::item('money', $invest->amount.' &euro;'),
  326. Feed::item('system', $invest->id),
  327. Feed::item('project', $project->name, $project->id),
  328. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  329. )));
  330. $log->doAdmin('system');
  331. $error_txt = $log->title;
  332. unset($log);
  333. } else {
  334. $log = new Feed();
  335. $log->setTarget($project->id);
  336. $log->populate('Error interno de PayPal', '/admin/accounts',
  337. \vsprintf('Ha <span class="red">fallado al ejecutar</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s <span class="red">'.$action.' '.$errorMsg.' ['.$errorId.']</span>', array(
  338. Feed::item('user', $userData->name, $userData->id),
  339. Feed::item('money', $invest->amount.' &euro;'),
  340. Feed::item('system', $invest->id),
  341. Feed::item('project', $project->name, $project->id),
  342. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  343. )));
  344. $log->doAdmin('system');
  345. $error_txt = $log->title;
  346. unset($log);
  347. }
  348. break;
  349. }
  350. if (empty($errorId)) {
  351. $errors[] = 'NO es soapFault pero no es Success: <pre>' . print_r($ap, 1) . '</pre>';
  352. } elseif (!empty($error_txt)) {
  353. $errors[] = $error_txt;
  354. } else {
  355. $errors[] = "$action $errorMsg [$errorId]";
  356. }
  357. Invest::setIssue($invest->id);
  358. return false;
  359. }
  360. $token = $response->payKey;
  361. if (!empty($token)) {
  362. if ($invest->setPayment($token)) {
  363. if ($response->paymentExecStatus != 'INCOMPLETE') {
  364. Invest::setIssue($invest->id);
  365. $errors[] = "Error de Fuente de crédito.";
  366. return false;
  367. }
  368. $invest->setStatus(1);
  369. return true;
  370. } else {
  371. Invest::setIssue($invest->id);
  372. $errors[] = "Obtenido payKey: $token pero no se ha grabado correctamente (paypal::setPayment) en el registro id: {$invest->id}.";
  373. @mail(\GOTEO_FAIL_MAIL, 'Error al actualizar registro aporte (setPayment)', 'ERROR en ' . __FUNCTION__ . ' Metodo paypal::setPayment ha fallado.<br /><pre>' . print_r($response, 1) . '</pre>');
  374. return false;
  375. }
  376. } else {
  377. Invest::setIssue($invest->id);
  378. $errors[] = 'No ha obtenido Payment Key.';
  379. @mail(\GOTEO_FAIL_MAIL, 'Error en implementacion Paypal API (no payKey)', 'ERROR en ' . __FUNCTION__ . ' No payment key obtained.<br /><pre>' . print_r($response, 1) . '</pre>');
  380. return false;
  381. }
  382. }
  383. catch (Exception $e) {
  384. $fault = new \FaultMessage();
  385. $errorData = new \ErrorData();
  386. $errorData->errorId = $ex->getFile() ;
  387. $errorData->message = $ex->getMessage();
  388. $fault->error = $errorData;
  389. Invest::setIssue($invest->id);
  390. $errors[] = 'No se ha podido inicializar la comunicación con Paypal, se ha reportado la incidencia.';
  391. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' Exception<br /><pre>' . print_r($fault, 1) . '</pre>');
  392. return false;
  393. }
  394. }
  395. /*
  396. * Metodo para ejecutar pago secundario (desde cron/dopay)
  397. * Recibe parametro del aporte (id, cuenta, cantidad)
  398. */
  399. public static function doPay($invest, &$errors = array()) {
  400. try {
  401. $project = Project::getMini($invest->project);
  402. $userData = User::getMini($invest->user);
  403. // Create request object
  404. $payRequest = new \ExecutePaymentRequest();
  405. $payRequest->payKey = $invest->payment;
  406. $payRequest->requestEnvelope = 'SOAP';
  407. // Create service wrapper object
  408. $ap = new \AdaptivePayments();
  409. // invoke business method on service wrapper passing in appropriate request params
  410. $response = $ap->ExecutePayment($payRequest);
  411. // Check response
  412. if(strtoupper($ap->isSuccess) == 'FAILURE') {
  413. $soapFault = $ap->getLastError();
  414. if(is_array($soapFault->error)) {
  415. $errorId = $soapFault->error[0]->errorId;
  416. $errorMsg = $soapFault->error[0]->message;
  417. } else {
  418. $errorId = $soapFault->error->errorId;
  419. $errorMsg = $soapFault->error->message;
  420. }
  421. if (is_array($soapFault->payErrorList->payError)) {
  422. $errorId = $soapFault->payErrorList->payError[0]->error->errorId;
  423. $errorMsg = $soapFault->payErrorList->payError[0]->error->message;
  424. }
  425. // tratamiento de errores
  426. switch ($errorId) {
  427. case '569013': // preapproval cancelado por el usuario desde panel paypal
  428. case '539012': // preapproval no se llegó a autorizar
  429. if ($invest->cancel()) {
  430. $action = 'Aporte cancelado';
  431. // Evento Feed
  432. $log = new Feed();
  433. $log->setTarget($project->id);
  434. $log->populate('Aporte cancelado por preaproval cancelado por el usuario paypal', '/admin/invests',
  435. \vsprintf('Se ha <span class="red">Cancelado</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s por preapproval cancelado', array(
  436. Feed::item('user', $userData->name, $userData->id),
  437. Feed::item('money', $invest->amount.' &euro;'),
  438. Feed::item('system', $invest->id),
  439. Feed::item('project', $project->name, $project->id),
  440. Feed::item('system', date('d/m/Y', strtotime($invest->invested)))
  441. )));
  442. $log->doAdmin('system');
  443. unset($log);
  444. }
  445. break;
  446. }
  447. if (empty($errorId)) {
  448. $errors[] = 'NO es soapFault pero no es Success: <pre>' . print_r($ap, 1) . '</pre>';
  449. @mail(\GOTEO_FAIL_MAIL, 'Error en implementacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' No es un soap fault pero no es un success.<br /><pre>' . print_r($ap, 1) . '</pre>');
  450. } else {
  451. $errors[] = "$action $errorMsg [$errorId]";
  452. }
  453. return false;
  454. }
  455. // verificar el campo paymentExecStatus
  456. if ($response->paymentExecStatus == 'COMPLETED') {
  457. if ($invest->setStatus('3')) {
  458. return true;
  459. } else {
  460. $errors[] = "Obtenido estatus de ejecución {$response->paymentExecStatus} pero no se ha actualizado el registro de aporte id {$invest->id}.";
  461. @mail(\GOTEO_FAIL_MAIL, 'Error al actualizar registro aporte (setStatus)', 'ERROR en ' . __FUNCTION__ . ' Metodo paypal::setStatus ha fallado.<br /><pre>' . print_r($response, 1) . '</pre>');
  462. return false;
  463. }
  464. } else {
  465. $errors[] = 'No se ha completado el pago encadenado, no se ha pagado al proyecto.';
  466. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' aporte id '.$invest->id.'. No payment exec status completed.<br /><pre>' . print_r($response, 1) . '</pre>');
  467. return false;
  468. }
  469. }
  470. catch (Exception $e) {
  471. $fault = new \FaultMessage();
  472. $errorData = new \ErrorData();
  473. $errorData->errorId = $ex->getFile() ;
  474. $errorData->message = $ex->getMessage();
  475. $fault->error = $errorData;
  476. $errors[] = 'No se ha podido inicializar la comunicación con Paypal, se ha reportado la incidencia.';
  477. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . '<br />No se ha podido inicializar la comunicación con Paypal.<br /><pre>' . print_r($fault, 1) . '</pre>');
  478. return false;
  479. }
  480. }
  481. /*
  482. * Llamada a paypal para obtener los detalles de un preapproval
  483. */
  484. public static function preapprovalDetails ($key, &$errors = array()) {
  485. try {
  486. $PDRequest = new \PreapprovalDetailsRequest();
  487. $PDRequest->requestEnvelope = new \RequestEnvelope();
  488. $PDRequest->requestEnvelope->errorLanguage = "es_ES";
  489. $PDRequest->preapprovalKey = $key;
  490. $ap = new \AdaptivePayments();
  491. $response = $ap->PreapprovalDetails($PDRequest);
  492. if(strtoupper($ap->isSuccess) == 'FAILURE') {
  493. $errors[] = 'No preapproval details obtained. <pre>' . print_r($ap->getLastError(), 1) . '</pre>';
  494. return false;
  495. } else {
  496. return $response;
  497. }
  498. }
  499. catch(Exception $ex) {
  500. $fault = new \FaultMessage();
  501. $errorData = new \ErrorData();
  502. $errorData->errorId = $ex->getFile() ;
  503. $errorData->message = $ex->getMessage();
  504. $fault->error = $errorData;
  505. $errors[] = 'Error fatal en la comunicación con Paypal, se ha reportado la incidencia. Disculpe las molestias.';
  506. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . '<br /><pre>' . print_r($fault, 1) . '</pre>');
  507. return false;
  508. }
  509. }
  510. /*
  511. * Llamada a paypal para obtener los detalles de un cargo
  512. */
  513. public static function paymentDetails ($key, &$errors = array()) {
  514. try {
  515. $pdRequest = new \PaymentDetailsRequest();
  516. $pdRequest->payKey = $key;
  517. $rEnvelope = new \RequestEnvelope();
  518. $rEnvelope->errorLanguage = "es_ES";
  519. $pdRequest->requestEnvelope = $rEnvelope;
  520. $ap = new \AdaptivePayments();
  521. $response=$ap->PaymentDetails($pdRequest);
  522. if(strtoupper($ap->isSuccess) == 'FAILURE') {
  523. $errors[] = 'No payment details obtained. <pre>' . print_r($ap->getLastError(), 1) . '</pre>';
  524. return false;
  525. } else {
  526. return $response;
  527. }
  528. }
  529. catch(Exception $ex) {
  530. $fault = new FaultMessage();
  531. $errorData = new ErrorData();
  532. $errorData->errorId = $ex->getFile() ;
  533. $errorData->message = $ex->getMessage();
  534. $fault->error = $errorData;
  535. $errors[] = 'Error fatal en la comunicación con Paypal, se ha reportado la incidencia. Disculpe las molestias.';
  536. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . '<br /><pre>' . print_r($fault, 1) . '</pre>');
  537. return false;
  538. }
  539. }
  540. /*
  541. * Llamada para cancelar un preapproval (si llega a los 40 sin conseguir el mínimo)
  542. * recibe la instancia del aporte
  543. */
  544. public static function cancelPreapproval ($invest, &$errors = array(), $fail = false) {
  545. try {
  546. if (empty($invest->preapproval)) {
  547. $invest->cancel($fail);
  548. return true;
  549. }
  550. $CPRequest = new \CancelPreapprovalRequest();
  551. $CPRequest->requestEnvelope = new \RequestEnvelope();
  552. $CPRequest->requestEnvelope->errorLanguage = "es_ES";
  553. $CPRequest->preapprovalKey = $invest->preapproval;
  554. $ap = new \AdaptivePayments();
  555. $response = $ap->CancelPreapproval($CPRequest);
  556. if(strtoupper($ap->isSuccess) == 'FAILURE') {
  557. Invest::setDetail($invest->id, 'paypal-cancel-fail', 'Ha fallado al cancelar el preapproval. Proceso libary/paypal::cancelPreapproval');
  558. $errors[] = 'Preapproval cancel failed.' . $ap->getLastError();
  559. @mail(\GOTEO_FAIL_MAIL, 'Fallo al cancelar preapproval Paypal API', 'ERROR en ' . __FUNCTION__ . '<br /><pre>' . print_r($ap->getLastError(), 1) . '</pre>');
  560. return false;
  561. } else {
  562. Invest::setDetail($invest->id, 'paypal-cancel', 'El Preapproval se ha cancelado y con ello el aporte. Proceso libary/paypal::cancelPreapproval');
  563. $invest->cancel($fail);
  564. return true;
  565. }
  566. }
  567. catch(Exception $ex) {
  568. $fault = new \FaultMessage();
  569. $errorData = new \ErrorData();
  570. $errorData->errorId = $ex->getFile() ;
  571. $errorData->message = $ex->getMessage();
  572. $fault->error = $errorData;
  573. Invest::setDetail($invest->id, 'paypal-cancel-fail', 'Ha fallado al cancelar el preapproval. Proceso libary/paypal::cancelPreapproval');
  574. $errors[] = 'Error fatal en la comunicación con Paypal, se ha reportado la incidencia. Disculpe las molestias.';
  575. @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . '<br /><pre>' . print_r($fault, 1) . '</pre>');
  576. return false;
  577. }
  578. }
  579. }
  580. }