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