Merge pull request #8328 from mlutfy/master-crm18524
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\Exception\PaymentProcessorException;
29
30 /**
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2016
34 */
35
36 /**
37 * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
38 */
39 class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment {
40 const CHARSET = 'iso-8859-1';
41
42 protected $_mode = NULL;
43
44 /**
45 * Constructor.
46 *
47 * @param string $mode
48 * The mode of operation: live or test.
49 *
50 * @param CRM_Core_Payment $paymentProcessor
51 *
52 * @return \CRM_Core_Payment_PayPalImpl
53 */
54 public function __construct($mode, &$paymentProcessor) {
55 $this->_mode = $mode;
56 $this->_paymentProcessor = $paymentProcessor;
57 $this->_processorName = ts('PayPal Pro');
58 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
59
60 if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
61 $this->_processorName = ts('PayPal Standard');
62 return;
63 }
64 elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) {
65 $this->_processorName = ts('PayPal Express');
66 }
67
68 }
69
70 /**
71 * Are back office payments supported.
72 *
73 * E.g paypal standard won't permit you to enter a credit card associated
74 * with someone else's login.
75 *
76 * @return bool
77 */
78 protected function supportsBackOffice() {
79 if ($this->_processorName == ts('PayPal Pro')) {
80 return TRUE;
81 }
82 return FALSE;
83 }
84
85 /**
86 * Does this processor support pre-approval.
87 *
88 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
89 *
90 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
91 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
92 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
93 *
94 * @return bool
95 */
96 protected function supportsPreApproval() {
97 if ($this->_processorName == ts('PayPal Express') || $this->_processorName == ts('PayPal Pro')) {
98 return TRUE;
99 }
100 return FALSE;
101 }
102
103 /**
104 * Opportunity for the payment processor to override the entire form build.
105 *
106 * @param CRM_Core_Form $form
107 *
108 * @return bool
109 * Should form building stop at this point?
110 */
111 public function buildForm(&$form) {
112 if ($this->_processorName == 'PayPal Express' || $this->_processorName == 'PayPal Pro') {
113 $this->addPaypalExpressCode($form);
114 if ($this->_processorName == 'PayPal Express') {
115 CRM_Core_Region::instance('billing-block-post')->add(array(
116 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
117 'name' => 'paypal_express',
118 ));
119 }
120 if ($this->_processorName == 'PayPal Pro') {
121 CRM_Core_Region::instance('billing-block-pre')->add(array(
122 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
123 ));
124 }
125 }
126 return FALSE;
127 }
128
129 /**
130 * Billing mode button is basically synonymous with paypal express.
131 *
132 * This is probably a good example of 'odds & sods' code we
133 * need to find a way for the payment processor to assign.
134 *
135 * A tricky aspect is that the payment processor may need to set the order
136 *
137 * @param CRM_Core_Form $form
138 */
139 protected function addPaypalExpressCode(&$form) {
140 if (empty($form->isBackOffice)) {
141 $form->_expressButtonName = $form->getButtonName('upload', 'express');
142 $form->assign('expressButtonName', $form->_expressButtonName);
143 $form->add(
144 'image',
145 $form->_expressButtonName,
146 $this->_paymentProcessor['url_button'],
147 array('class' => 'crm-form-submit')
148 );
149 }
150 }
151
152 /**
153 * Can recurring contributions be set against pledges.
154 *
155 * In practice all processors that use the baseIPN function to finish transactions or
156 * call the completetransaction api support this by looking up previous contributions in the
157 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
158 * adding the new payment to the pledge.
159 *
160 * However, only enabling for processors it has been tested against.
161 *
162 * @return bool
163 */
164 protected function supportsRecurContributionsForPledges() {
165 return TRUE;
166 }
167
168 /**
169 * Default payment instrument validation.
170 *
171 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
172 * Not a static function, because I need to check for payment_type.
173 *
174 * @param array $values
175 * @param array $errors
176 */
177 public function validatePaymentInstrument($values, &$errors) {
178 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) {
179 CRM_Core_Payment_Form::validateCreditCard($values, $errors);
180 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
181 }
182 }
183
184 /**
185 * Express checkout code.
186 *
187 * Check PayPal documentation for more information
188 *
189 * @param array $params
190 * Assoc array of input parameters for this transaction.
191 *
192 * @return array
193 * the result in an nice formatted array (or an error object)
194 */
195 protected function setExpressCheckOut(&$params) {
196 $args = array();
197
198 $this->initialize($args, 'SetExpressCheckout');
199
200 $args['paymentAction'] = 'Sale';
201 $args['amt'] = $params['amount'];
202 $args['currencyCode'] = $params['currencyID'];
203 $args['desc'] = CRM_Utils_Array::value('description', $params);
204 $args['invnum'] = $params['invoiceID'];
205 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
206 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
207 $args['version'] = '56.0';
208
209 //LCD if recurring, collect additional data and set some values
210 if (!empty($params['is_recur'])) {
211 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
212 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
213 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
214 $args['L_PAYMENTTYPE0'] = 'Any';
215 }
216
217 // Allow further manipulation of the arguments via custom hooks ..
218 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
219
220 $result = $this->invokeAPI($args);
221
222 if (is_a($result, 'CRM_Core_Error')) {
223 throw new PaymentProcessorException($result->message);
224 }
225
226 /* Success */
227
228 return $result['token'];
229 }
230
231 /**
232 * Get any details that may be available to the payment processor due to an approval process having happened.
233 *
234 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
235 * result.
236 *
237 * @param array $storedDetails
238 *
239 * @return array
240 */
241 public function getPreApprovalDetails($storedDetails) {
242 return empty($storedDetails['token']) ? array() : $this->getExpressCheckoutDetails($storedDetails['token']);
243 }
244
245 /**
246 * Get details from paypal.
247 *
248 * Check PayPal documentation for more information
249 *
250 * @param string $token
251 * The key associated with this transaction.
252 *
253 * @return array
254 * the result in an nice formatted array (or an error object)
255 */
256 public function getExpressCheckoutDetails($token) {
257 $args = array();
258
259 $this->initialize($args, 'GetExpressCheckoutDetails');
260 $args['token'] = $token;
261 // LCD
262 $args['method'] = 'GetExpressCheckoutDetails';
263
264 $result = $this->invokeAPI($args);
265
266 if (is_a($result, 'CRM_Core_Error')) {
267 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
268 }
269
270 /* Success */
271 $fieldMap = array(
272 'token' => 'token',
273 'payer_status' => 'payerstatus',
274 'payer_id' => 'payerid',
275 'first_name' => 'firstname',
276 'middle_name' => 'middlename',
277 'last_name' => 'lastname',
278 'street_address' => 'shiptostreet',
279 'supplemental_address_1' => 'shiptostreet2',
280 'city' => 'shiptocity',
281 'postal_code' => 'shiptozip',
282 'state_province' => 'shiptostate',
283 'country' => 'shiptocountrycode',
284 );
285 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
286 }
287
288 /**
289 * Do the express checkout at paypal.
290 *
291 * Check PayPal documentation for more information
292 *
293 * @param array $params
294 *
295 * @return array
296 * The result in an nice formatted array.
297 *
298 * @throws \Civi\Payment\Exception\PaymentProcessorException
299 */
300 public function doExpressCheckout(&$params) {
301 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
302 if (!empty($params['is_recur'])) {
303 return $this->createRecurringPayments($params);
304 }
305 $args = array();
306
307 $this->initialize($args, 'DoExpressCheckoutPayment');
308 $args['token'] = $params['token'];
309 $args['paymentAction'] = 'Sale';
310 $args['amt'] = $params['amount'];
311 $args['currencyCode'] = $params['currencyID'];
312 $args['payerID'] = $params['payer_id'];
313 $args['invnum'] = $params['invoiceID'];
314 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
315 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
316 $args['desc'] = $params['description'];
317
318 // add CiviCRM BN code
319 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
320
321 $result = $this->invokeAPI($args);
322
323 if (is_a($result, 'CRM_Core_Error')) {
324 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
325 }
326
327 /* Success */
328
329 $params['trxn_id'] = $result['transactionid'];
330 $params['gross_amount'] = $result['amt'];
331 $params['fee_amount'] = $result['feeamt'];
332 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
333 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
334 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
335 }
336 $params['payment_status'] = $result['paymentstatus'];
337 $params['pending_reason'] = $result['pendingreason'];
338 if (!empty($params['is_recur'])) {
339 // See comment block.
340 $result['payment_status_id'] = array_search('Pending', $statuses);
341 }
342 else {
343 $result['payment_status_id'] = array_search('Completed', $statuses);
344 }
345 return $params;
346 }
347
348 /**
349 * Create recurring payments.
350 *
351 * @param array $params
352 *
353 * @return mixed
354 */
355 public function createRecurringPayments(&$params) {
356 $args = array();
357 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
358 $this->initialize($args, 'CreateRecurringPaymentsProfile');
359
360 $start_time = strtotime(date('m/d/Y'));
361 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
362
363 $args['token'] = $params['token'];
364 $args['paymentAction'] = 'Sale';
365 $args['amt'] = $params['amount'];
366 $args['currencyCode'] = $params['currencyID'];
367 $args['payerID'] = $params['payer_id'];
368 $args['invnum'] = $params['invoiceID'];
369 $args['returnURL'] = $params['returnURL'];
370 $args['cancelURL'] = $params['cancelURL'];
371 $args['profilestartdate'] = $start_date;
372 $args['method'] = 'CreateRecurringPaymentsProfile';
373 $args['billingfrequency'] = $params['frequency_interval'];
374 $args['billingperiod'] = ucwords($params['frequency_unit']);
375 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
376 //$args['desc'] = 'Recurring Contribution';
377 $args['totalbillingcycles'] = $params['installments'];
378 $args['version'] = '56.0';
379 $args['profilereference'] = "i={$params['invoiceID']}" .
380 "&m=" .
381 "&c={$params['contactID']}" .
382 "&r={$params['contributionRecurID']}" .
383 "&b={$params['contributionID']}" .
384 "&p={$params['contributionPageID']}";
385
386 // add CiviCRM BN code
387 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
388
389 $result = $this->invokeAPI($args);
390
391 if (is_a($result, 'CRM_Core_Error')) {
392 return $result;
393 }
394
395 /* Success */
396 $params['trxn_id'] = $result['transactionid'];
397 $params['gross_amount'] = $result['amt'];
398 $params['fee_amount'] = $result['feeamt'];
399 $params['net_amount'] = $result['settleamt'];
400 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
401 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
402 }
403 $params['payment_status'] = $result['paymentstatus'];
404 $params['pending_reason'] = $result['pendingreason'];
405
406 return $params;
407 }
408
409 /**
410 * Initialise.
411 *
412 * @param $args
413 * @param $method
414 */
415 public function initialize(&$args, $method) {
416 $args['user'] = $this->_paymentProcessor['user_name'];
417 $args['pwd'] = $this->_paymentProcessor['password'];
418 $args['version'] = 3.0;
419 $args['signature'] = $this->_paymentProcessor['signature'];
420 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
421 $args['method'] = $method;
422 }
423
424 /**
425 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
426 *
427 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
428 * more agnostic.
429 *
430 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
431 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
432 * doTransferCheckout would not traditionally come back.
433 *
434 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
435 * to be Pending.
436 *
437 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
438 * return Error objects
439 *
440 * @param array $params
441 *
442 * @param string $component
443 *
444 * @return array
445 * Result array
446 *
447 * @throws \Civi\Payment\Exception\PaymentProcessorException
448 */
449 public function doPayment(&$params, $component = 'contribute') {
450 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express'
451 || ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !empty($params['token']))
452 ) {
453 $this->_component = $component;
454 return $this->doExpressCheckout($params);
455
456 }
457 return parent::doPayment($params, $component);
458 }
459
460 /**
461 * This function collects all the information from a web/api form and invokes
462 * the relevant payment processor specific functions to perform the transaction
463 *
464 * @param array $params
465 * Assoc array of input parameters for this transaction.
466 *
467 * @param string $component
468 * @return array
469 * the result in an nice formatted array (or an error object)
470 */
471 public function doDirectPayment(&$params, $component = 'contribute') {
472 $args = array();
473
474 $this->initialize($args, 'DoDirectPayment');
475
476 $args['paymentAction'] = 'Sale';
477 $args['amt'] = $params['amount'];
478 $args['currencyCode'] = $params['currencyID'];
479 $args['invnum'] = $params['invoiceID'];
480 $args['ipaddress'] = $params['ip_address'];
481 $args['creditCardType'] = $params['credit_card_type'];
482 $args['acct'] = $params['credit_card_number'];
483 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
484 $args['cvv2'] = $params['cvv2'];
485 $args['firstName'] = $params['first_name'];
486 $args['lastName'] = $params['last_name'];
487 $args['email'] = CRM_Utils_Array::value('email', $params);
488 $args['street'] = $params['street_address'];
489 $args['city'] = $params['city'];
490 $args['state'] = $params['state_province'];
491 $args['countryCode'] = $params['country'];
492 $args['zip'] = $params['postal_code'];
493 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
494 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
495
496 // add CiviCRM BN code
497 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
498
499 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
500 $start_time = strtotime(date('m/d/Y'));
501 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
502
503 $args['PaymentAction'] = 'Sale';
504 $args['billingperiod'] = ucwords($params['frequency_unit']);
505 $args['billingfrequency'] = $params['frequency_interval'];
506 $args['method'] = "CreateRecurringPaymentsProfile";
507 $args['profilestartdate'] = $start_date;
508 $args['desc'] = "" .
509 $params['description'] . ": " .
510 $params['amount'] . " Per " .
511 $params['frequency_interval'] . " " .
512 $params['frequency_unit'];
513 $args['amt'] = $params['amount'];
514 $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
515 $args['version'] = 56.0;
516 $args['PROFILEREFERENCE'] = "" .
517 "i=" . $params['invoiceID'] . "&m=" . $component .
518 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
519 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
520 }
521
522 // Allow further manipulation of the arguments via custom hooks ..
523 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
524
525 $result = $this->invokeAPI($args);
526
527 //WAG
528 if (is_a($result, 'CRM_Core_Error')) {
529 return $result;
530 }
531
532 $params['recurr_profile_id'] = NULL;
533
534 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
535 $params['recurr_profile_id'] = $result['profileid'];
536 }
537
538 /* Success */
539
540 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
541 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
542 $params = array_merge($params, $this->doQuery($params));
543 return $params;
544 }
545
546 /**
547 * Query payment processor for details about a transaction.
548 *
549 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
550 *
551 * @param array $params
552 * Array of parameters containing one of:
553 * - trxn_id Id of an individual transaction.
554 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
555 *
556 * @return array
557 * Extra parameters retrieved.
558 * Any parameters retrievable through this should be documented in the function comments at
559 * CRM_Core_Payment::doQuery. Currently
560 * - fee_amount Amount of fee paid
561 *
562 * @throws \Civi\Payment\Exception\PaymentProcessorException
563 */
564 public function doQuery($params) {
565 //CRM-18140 - trxn_id not returned for recurring paypal transaction
566 if (!empty($params['is_recur'])) {
567 return array();
568 }
569 elseif (empty($params['trxn_id'])) {
570 throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
571 }
572 $args = array(
573 'TRANSACTIONID' => $params['trxn_id'],
574 );
575 $this->initialize($args, 'GetTransactionDetails');
576 $result = $this->invokeAPI($args);
577 return array(
578 'fee_amount' => $result['feeamt'],
579 'net_amount' => $params['gross_amount'] - $result['feeamt'],
580 );
581 }
582
583 /**
584 * This function checks to see if we have the right config values.
585 *
586 * @return string
587 * the error message if any
588 */
589 public function checkConfig() {
590 $error = array();
591 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
592
593 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
594 if (empty($this->_paymentProcessor['signature'])) {
595 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
596 }
597
598 if (empty($this->_paymentProcessor['password'])) {
599 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
600 }
601 }
602 if (empty($this->_paymentProcessor['user_name'])) {
603 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
604 }
605
606 if (!empty($error)) {
607 return implode('<p>', $error);
608 }
609 else {
610 return NULL;
611 }
612 }
613
614 /**
615 * @return null|string
616 */
617 public function cancelSubscriptionURL() {
618 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
619 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
620 }
621 else {
622 return NULL;
623 }
624 }
625
626 /**
627 * Check whether a method is present ( & supported ) by the payment processor object.
628 *
629 * @param string $method
630 * Method to check for.
631 *
632 * @return bool
633 */
634 public function isSupported($method) {
635 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
636 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
637 // by standard or express.
638 return FALSE;
639 }
640 return parent::isSupported($method);
641 }
642
643 /**
644 * Paypal express replaces the submit button with it's own.
645 *
646 * @return bool
647 * Should the form button by suppressed?
648 */
649 public function isSuppressSubmitButtons() {
650 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
651 return TRUE;
652 }
653 return FALSE;
654 }
655
656 /**
657 * @param string $message
658 * @param array $params
659 *
660 * @return array|bool|object
661 */
662 public function cancelSubscription(&$message = '', $params = array()) {
663 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
664 $args = array();
665 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
666
667 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
668 $args['ACTION'] = 'Cancel';
669 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
670
671 $result = $this->invokeAPI($args);
672 if (is_a($result, 'CRM_Core_Error')) {
673 return $result;
674 }
675 $message = "{$result['ack']}: profileid={$result['profileid']}";
676 return TRUE;
677 }
678 return FALSE;
679 }
680
681 /**
682 * Process incoming notification.
683 *
684 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
685 * for paypal standard as the goal must be to separate the 2.
686 *
687 * We don't need to handle paypal standard using this path as there has never been any historic support
688 * for paypal standard to call civicrm/payment/ipn as a path.
689 */
690 static public function handlePaymentNotification() {
691 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
692 $paypalIPN->main();
693 }
694
695 /**
696 * @param string $message
697 * @param array $params
698 *
699 * @return array|bool|object
700 */
701 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
702 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
703 $config = CRM_Core_Config::singleton();
704 $args = array();
705 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
706
707 $args['PROFILEID'] = $params['subscriptionId'];
708 $args['AMT'] = $params['amount'];
709 $args['CURRENCYCODE'] = $config->defaultCurrency;
710 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
711 $args['ACCT'] = $params['credit_card_number'];
712 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
713 $args['CVV2'] = $params['cvv2'];
714
715 $args['FIRSTNAME'] = $params['first_name'];
716 $args['LASTNAME'] = $params['last_name'];
717 $args['STREET'] = $params['street_address'];
718 $args['CITY'] = $params['city'];
719 $args['STATE'] = $params['state_province'];
720 $args['COUNTRYCODE'] = $params['postal_code'];
721 $args['ZIP'] = $params['country'];
722
723 $result = $this->invokeAPI($args);
724 if (is_a($result, 'CRM_Core_Error')) {
725 return $result;
726 }
727 $message = "{$result['ack']}: profileid={$result['profileid']}";
728 return TRUE;
729 }
730 return FALSE;
731 }
732
733 /**
734 * @param string $message
735 * @param array $params
736 *
737 * @return array|bool|object
738 */
739 public function changeSubscriptionAmount(&$message = '', $params = array()) {
740 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
741 $config = CRM_Core_Config::singleton();
742 $args = array();
743 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
744
745 $args['PROFILEID'] = $params['subscriptionId'];
746 $args['AMT'] = $params['amount'];
747 $args['CURRENCYCODE'] = $config->defaultCurrency;
748 $args['BILLINGFREQUENCY'] = $params['installments'];
749
750 $result = $this->invokeAPI($args);
751 CRM_Core_Error::debug_var('$result', $result);
752 if (is_a($result, 'CRM_Core_Error')) {
753 return $result;
754 }
755 $message = "{$result['ack']}: profileid={$result['profileid']}";
756 return TRUE;
757 }
758 return FALSE;
759 }
760
761 /**
762 * Function to action pre-approval if supported
763 *
764 * @param array $params
765 * Parameters from the form
766 *
767 * @return array
768 * - pre_approval_parameters (this will be stored on the calling form & available later)
769 * - redirect_url (if set the browser will be redirected to this.
770 */
771 public function doPreApproval(&$params) {
772 if (!$this->isPaypalExpress($params)) {
773 return array();
774 }
775 $this->_component = $params['component'];
776 $token = $this->setExpressCheckOut($params);
777 return array(
778 'pre_approval_parameters' => array('token' => $token),
779 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
780 );
781 }
782
783 /**
784 * @param array $params
785 * @param string $component
786 *
787 * @throws Exception
788 */
789 public function doTransferCheckout(&$params, $component = 'contribute') {
790 $config = CRM_Core_Config::singleton();
791
792 if ($component != 'contribute' && $component != 'event') {
793 CRM_Core_Error::fatal(ts('Component is invalid'));
794 }
795
796 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
797
798 if ($component == 'event') {
799 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
800 }
801 else {
802 $membershipID = CRM_Utils_Array::value('membershipID', $params);
803 if ($membershipID) {
804 $notifyURL .= "&membershipID=$membershipID";
805 }
806 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
807 if ($relatedContactID) {
808 $notifyURL .= "&relatedContactID=$relatedContactID";
809
810 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
811 if ($onBehalfDupeAlert) {
812 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
813 }
814 }
815 }
816
817 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
818 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
819 $returnURL = CRM_Utils_System::url($url,
820 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
821 TRUE, NULL, FALSE
822 );
823
824 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
825 if (!empty($params['is_recur'])) {
826 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
827 }
828
829 $cancelURL = CRM_Utils_System::url(
830 $url,
831 $cancelUrlString,
832 TRUE, NULL, FALSE
833 );
834
835 // ensure that the returnURL is absolute.
836 if (substr($returnURL, 0, 4) != 'http') {
837 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
838 CRM_Core_Error::fatal(ts('Sending a relative URL to PayPalIPN is erroneous. Please make your resource URL (in <a href="%1">Administer &raquo; System Settings &raquo; Resource URLs</a> ) complete.', array(1 => $fixUrl)));
839 }
840
841 $paypalParams = array(
842 'business' => $this->_paymentProcessor['user_name'],
843 'notify_url' => $notifyURL,
844 'item_name' => $this->getPaymentDescription($params),
845 'quantity' => 1,
846 'undefined_quantity' => 0,
847 'cancel_return' => $cancelURL,
848 'no_note' => 1,
849 'no_shipping' => 1,
850 'return' => $returnURL,
851 'rm' => 2,
852 'currency_code' => $params['currencyID'],
853 'invoice' => $params['invoiceID'],
854 'lc' => substr($config->lcMessages, -2),
855 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
856 'custom' => CRM_Utils_Array::value('accountingCode', $params),
857 'bn' => 'CiviCRM_SP',
858 );
859
860 // add name and address if available, CRM-3130
861 $otherVars = array(
862 'first_name' => 'first_name',
863 'last_name' => 'last_name',
864 'street_address' => 'address1',
865 'country' => 'country',
866 'preferred_language' => 'lc',
867 'city' => 'city',
868 'state_province' => 'state',
869 'postal_code' => 'zip',
870 'email' => 'email',
871 );
872
873 foreach (array_keys($params) as $p) {
874 // get the base name without the location type suffixed to it
875 $parts = explode('-', $p);
876 $name = count($parts) > 1 ? $parts[0] : $p;
877 if (isset($otherVars[$name])) {
878 $value = $params[$p];
879 if ($value) {
880 if ($name == 'state_province') {
881 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
882 $value = $stateName;
883 }
884 if ($name == 'country') {
885 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
886 $value = $countryName;
887 }
888 // ensure value is not an array
889 // CRM-4174
890 if (!is_array($value)) {
891 $paypalParams[$otherVars[$name]] = $value;
892 }
893 }
894 }
895 }
896
897 // if recurring donations, add a few more items
898 if (!empty($params['is_recur'])) {
899 if ($params['contributionRecurID']) {
900 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
901 $paypalParams['notify_url'] = $notifyURL;
902 }
903 else {
904 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
905 }
906
907 $paypalParams += array(
908 'cmd' => '_xclick-subscriptions',
909 'a3' => $params['amount'],
910 'p3' => $params['frequency_interval'],
911 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
912 'src' => 1,
913 'sra' => 1,
914 'srt' => CRM_Utils_Array::value('installments', $params),
915 'no_note' => 1,
916 'modify' => 0,
917 );
918 }
919 else {
920 $paypalParams += array(
921 'cmd' => '_xclick',
922 'amount' => $params['amount'],
923 );
924 }
925
926 // Allow further manipulation of the arguments via custom hooks ..
927 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
928
929 $uri = '';
930 foreach ($paypalParams as $key => $value) {
931 if ($value === NULL) {
932 continue;
933 }
934
935 $value = urlencode($value);
936 if ($key == 'return' ||
937 $key == 'cancel_return' ||
938 $key == 'notify_url'
939 ) {
940 $value = str_replace('%2F', '/', $value);
941 }
942 $uri .= "&{$key}={$value}";
943 }
944
945 $uri = substr($uri, 1);
946 $url = $this->_paymentProcessor['url_site'];
947 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
948 $paypalURL = "{$url}{$sub}?$uri";
949
950 CRM_Utils_System::redirect($paypalURL);
951 }
952
953 /**
954 * Hash_call: Function to perform the API call to PayPal using API signature.
955 *
956 * @methodName is name of API method.
957 * @nvpStr is nvp string.
958 * returns an associative array containing the response from the server.
959 *
960 * @param array $args
961 * @param null $url
962 *
963 * @return array|object
964 * @throws \Exception
965 */
966 public function invokeAPI($args, $url = NULL) {
967
968 if ($url === NULL) {
969 if (empty($this->_paymentProcessor['url_api'])) {
970 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
971 }
972
973 $url = $this->_paymentProcessor['url_api'] . 'nvp';
974 }
975
976 if (!function_exists('curl_init')) {
977 CRM_Core_Error::fatal("curl functions NOT available.");
978 }
979
980 //setting the curl parameters.
981 $ch = curl_init();
982 curl_setopt($ch, CURLOPT_URL, $url);
983 curl_setopt($ch, CURLOPT_VERBOSE, 0);
984
985 //turning off the server and peer verification(TrustManager Concept).
986 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
987 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
988
989 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
990 curl_setopt($ch, CURLOPT_POST, 1);
991
992 $p = array();
993 foreach ($args as $n => $v) {
994 $p[] = "$n=" . urlencode($v);
995 }
996
997 //NVPRequest for submitting to server
998 $nvpreq = implode('&', $p);
999
1000 //setting the nvpreq as POST FIELD to curl
1001 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
1002
1003 //getting response from server
1004 $response = curl_exec($ch);
1005
1006 //converting NVPResponse to an Associative Array
1007 $result = self::deformat($response);
1008
1009 if (curl_errno($ch)) {
1010 $e = CRM_Core_Error::singleton();
1011 $e->push(curl_errno($ch),
1012 0, NULL,
1013 curl_error($ch)
1014 );
1015 return $e;
1016 }
1017 else {
1018 curl_close($ch);
1019 }
1020
1021 if (strtolower($result['ack']) != 'success' &&
1022 strtolower($result['ack']) != 'successwithwarning'
1023 ) {
1024 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1025 $e = CRM_Core_Error::singleton();
1026 $e->push($result['l_errorcode0'],
1027 0, NULL,
1028 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1029 );
1030 return $e;
1031 }
1032
1033 return $result;
1034 }
1035
1036 /**
1037 * This function will take NVPString and convert it to an Associative Array.
1038 *
1039 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1040 *
1041 * @param string $str
1042 *
1043 * @return array
1044 */
1045 public static function deformat($str) {
1046 $result = array();
1047
1048 while (strlen($str)) {
1049 // position of key
1050 $keyPos = strpos($str, '=');
1051
1052 // position of value
1053 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
1054
1055 /*getting the Key and Value values and storing in a Associative Array*/
1056
1057 $key = substr($str, 0, $keyPos);
1058 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
1059
1060 //decoding the respose
1061 $result[strtolower(urldecode($key))] = urldecode($val);
1062 $str = substr($str, $valPos + 1, strlen($str));
1063 }
1064
1065 return $result;
1066 }
1067
1068 /**
1069 * Get array of fields that should be displayed on the payment form.
1070 *
1071 * @return array
1072 * @throws CiviCRM_API3_Exception
1073 */
1074 public function getPaymentFormFields() {
1075 if ($this->_processorName == ts('PayPal Pro')) {
1076 return $this->getCreditCardFormFields();
1077 }
1078 else {
1079 return array();
1080 }
1081 }
1082
1083 /**
1084 * Map the paypal params to CiviCRM params using a field map.
1085 *
1086 * @param array $fieldMap
1087 * @param array $paypalParams
1088 *
1089 * @return array
1090 */
1091 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1092 $params = array();
1093 foreach ($fieldMap as $civicrmField => $paypalField) {
1094 $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
1095 }
1096 return $params;
1097 }
1098
1099 /**
1100 * Is this being processed by payment express.
1101 *
1102 * Either because it is payment express or because is pro with paypal express in use.
1103 *
1104 * @param array $params
1105 *
1106 * @return bool
1107 */
1108 protected function isPaypalExpress($params) {
1109 if ($this->_processorName == ts('PayPal Express')) {
1110 return TRUE;
1111 }
1112
1113 // This would occur postProcess.
1114 if (!empty($params['token'])) {
1115 return TRUE;
1116 }
1117 if (isset($params['button']) && stristr($params['button'], 'express')) {
1118 return TRUE;
1119 }
1120
1121 // The contribution form passes a 'button' but the event form might still set one of these fields.
1122 // @todo more standardisation & get paypal fully out of the form layer.
1123 $possibleExpressFields = array(
1124 '_qf_Register_upload_express_x',
1125 '_qf_Payment_upload_express_x',
1126 );
1127 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {
1128 return TRUE;
1129 }
1130 return FALSE;
1131 }
1132
1133 }