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