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