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