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