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