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