Merge pull request #15840 from yashodha/participant_edit
[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
245 //LCD if recurring, collect additional data and set some values
246 if (!empty($params['is_recur'])) {
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')) {
259 throw new PaymentProcessorException($result->message);
260 }
261
262 /* Success */
263
264 return $result['token'];
265 }
266
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
276 * @throws \Civi\Payment\Exception\PaymentProcessorException
277 */
278 public function getPreApprovalDetails($storedDetails) {
279 return empty($storedDetails['token']) ? [] : $this->getExpressCheckoutDetails($storedDetails['token']);
280 }
281
282 /**
283 * Get details from paypal.
284 *
285 * Check PayPal documentation for more information
286 *
287 * @param string $token
288 * The key associated with this transaction.
289 *
290 * @return array
291 * the result in an nice formatted array (or an error object)
292 * @throws \Civi\Payment\Exception\PaymentProcessorException
293 */
294 public function getExpressCheckoutDetails($token) {
295 $args = [];
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')) {
305 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
306 }
307
308 /* Success */
309 $fieldMap = [
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',
322 ];
323 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
324 }
325
326 /**
327 * Do the express checkout at paypal.
328 *
329 * Check PayPal documentation for more information
330 *
331 * @param array $params
332 *
333 * @return array
334 * The result in an nice formatted array.
335 *
336 * @throws \Civi\Payment\Exception\PaymentProcessorException
337 */
338 public function doExpressCheckout(&$params) {
339 if (!empty($params['is_recur'])) {
340 return $this->createRecurringPayments($params);
341 }
342 $args = [];
343
344 $this->initialize($args, 'DoExpressCheckoutPayment');
345 $args['token'] = $params['token'];
346 $args['paymentAction'] = 'Sale';
347 $args['amt'] = $params['amount'];
348 $args['currencyCode'] = $params['currencyID'];
349 $args['payerID'] = $params['payer_id'];
350 $args['invnum'] = $params['invoiceID'];
351 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
352 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
353 $args['desc'] = $params['description'];
354
355 // add CiviCRM BN code
356 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
357
358 $result = $this->invokeAPI($args);
359
360 if (is_a($result, 'CRM_Core_Error')) {
361 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
362 }
363
364 /* Success */
365 $params['trxn_id'] = $result['transactionid'];
366 $params['gross_amount'] = $result['amt'];
367 $params['fee_amount'] = $result['feeamt'];
368 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
369 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
370 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
371 }
372 $params['payment_status'] = $result['paymentstatus'];
373 $params['pending_reason'] = $result['pendingreason'];
374 if (!empty($params['is_recur'])) {
375 // See comment block.
376 $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
377 }
378 else {
379 $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
380 }
381 return $params;
382 }
383
384 /**
385 * Create recurring payments.
386 *
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 *
390 * @param array $params
391 *
392 * @return mixed
393 * @throws \Exception
394 */
395 public function createRecurringPayments(&$params) {
396 $args = [];
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'];
403 $args['paymentAction'] = 'Sale';
404 $args['amt'] = $params['amount'];
405 $args['currencyCode'] = $params['currencyID'];
406 $args['payerID'] = $params['payer_id'];
407 $args['invnum'] = $params['invoiceID'];
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'];
413 $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
414 $args['version'] = '56.0';
415 $args['profilereference'] = "i={$params['invoiceID']}" .
416 "&m=" .
417 "&c={$params['contactID']}" .
418 "&r={$params['contributionRecurID']}" .
419 "&b={$params['contributionID']}" .
420 "&p={$params['contributionPageID']}";
421
422 // add CiviCRM BN code
423 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
424
425 $result = $this->invokeAPI($args);
426
427 if (is_a($result, 'CRM_Core_Error')) {
428 return $result;
429 }
430
431 /* Success - result looks like"
432 * array (
433 * 'profileid' => 'I-CP1U0PLG91R2',
434 * 'profilestatus' => 'ActiveProfile',
435 * 'timestamp' => '2018-05-07T03:55:52Z',
436 * 'correlationid' => 'e717999e9bf62',
437 * 'ack' => 'Success',
438 * 'version' => '56.0',
439 * 'build' => '39949200',)
440 */
441 $params['trxn_id'] = $result['profileid'];
442 $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
443
444 return $params;
445 }
446
447 /**
448 * Initialise.
449 *
450 * @param $args
451 * @param $method
452 */
453 public function initialize(&$args, $method) {
454 $args['user'] = $this->_paymentProcessor['user_name'];
455 $args['pwd'] = $this->_paymentProcessor['password'];
456 $args['version'] = 3.0;
457 $args['signature'] = $this->_paymentProcessor['signature'];
458 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
459 $args['method'] = $method;
460 }
461
462 /**
463 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
464 *
465 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
466 * more agnostic.
467 *
468 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
469 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
470 * doTransferCheckout would not traditionally come back.
471 *
472 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
473 * to be Pending.
474 *
475 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
476 * return Error objects
477 *
478 * @param array $params
479 *
480 * @param string $component
481 *
482 * @return array
483 * Result array
484 *
485 * @throws \Civi\Payment\Exception\PaymentProcessorException
486 */
487 public function doPayment(&$params, $component = 'contribute') {
488 if ($this->isPayPalType($this::PAYPAL_EXPRESS) || ($this->isPayPalType($this::PAYPAL_PRO) && !empty($params['token']))) {
489 $this->_component = $component;
490 return $this->doExpressCheckout($params);
491
492 }
493 return parent::doPayment($params, $component);
494 }
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 *
500 * @param array $params
501 * Assoc array of input parameters for this transaction.
502 *
503 * @param string $component
504 * @return array
505 * the result in an nice formatted array (or an error object)
506 * @throws \Civi\Payment\Exception\PaymentProcessorException
507 */
508 public function doDirectPayment(&$params, $component = 'contribute') {
509 $args = [];
510
511 $this->initialize($args, 'DoDirectPayment');
512
513 $args['paymentAction'] = 'Sale';
514 $args['amt'] = $this->getAmount($params);
515 $args['currencyCode'] = $this->getCurrency($params);
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'];
530 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
531 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
532
533 // add CiviCRM BN code
534 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
535
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;
545 $args['desc'] = "" .
546 $params['description'] . ": " .
547 $params['amount'] . " Per " .
548 $params['frequency_interval'] . " " .
549 $params['frequency_unit'];
550 $args['amt'] = $this->getAmount($params);
551 $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
552 $args['version'] = 56.0;
553 $args['PROFILEREFERENCE'] = "" .
554 "i=" . $params['invoiceID'] . "&m=" . $component .
555 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
556 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
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
564 // WAG
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);
579 $params = array_merge($params, $this->doQuery($params));
580 return $params;
581 }
582
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) {
602 //CRM-18140 - trxn_id not returned for recurring paypal transaction
603 if (!empty($params['is_recur'])) {
604 return [];
605 }
606 elseif (empty($params['trxn_id'])) {
607 throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
608 }
609 $args = [
610 'TRANSACTIONID' => $params['trxn_id'],
611 ];
612 $this->initialize($args, 'GetTransactionDetails');
613 $result = $this->invokeAPI($args);
614 return [
615 'fee_amount' => $result['feeamt'],
616 'net_amount' => $params['gross_amount'] - $result['feeamt'],
617 ];
618 }
619
620 /**
621 * This function checks to see if we have the right config values.
622 *
623 * @return null|string
624 * the error message if any
625 * @throws \Civi\Payment\Exception\PaymentProcessorException
626 */
627 public function checkConfig() {
628 $error = [];
629
630 if (!$this->isPayPalType($this::PAYPAL_STANDARD)) {
631 if (empty($this->_paymentProcessor['signature'])) {
632 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
633 }
634
635 if (empty($this->_paymentProcessor['password'])) {
636 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
637 }
638 }
639 if (empty($this->_paymentProcessor['user_name'])) {
640 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
641 }
642
643 if (!empty($error)) {
644 return implode('<p>', $error);
645 }
646 else {
647 return NULL;
648 }
649 }
650
651 /**
652 * @return null|string
653 * @throws \Civi\Payment\Exception\PaymentProcessorException
654 */
655 public function cancelSubscriptionURL() {
656 if ($this->isPayPalType($this::PAYPAL_STANDARD)) {
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
664 /**
665 * Check whether a method is present ( & supported ) by the payment processor object.
666 *
667 * @param string $method
668 * Method to check for.
669 *
670 * @return bool
671 * @throws \Civi\Payment\Exception\PaymentProcessorException
672 */
673 public function isSupported($method) {
674 if (!$this->isPayPalType($this::PAYPAL_PRO)) {
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
682 /**
683 * Paypal express replaces the submit button with it's own.
684 *
685 * @return bool
686 * Should the form button by suppressed?
687 * @throws \Civi\Payment\Exception\PaymentProcessorException
688 */
689 public function isSuppressSubmitButtons() {
690 if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
691 return TRUE;
692 }
693 return FALSE;
694 }
695
696 /**
697 * @param string $message
698 * @param array $params
699 *
700 * @return array|bool|object
701 * @throws \Civi\Payment\Exception\PaymentProcessorException
702 */
703 public function cancelSubscription(&$message = '', $params = []) {
704 if ($this->isPayPalType($this::PAYPAL_PRO) || $this->isPayPalType($this::PAYPAL_EXPRESS)) {
705 $args = [];
706 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
707
708 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
709 $args['ACTION'] = 'Cancel';
710 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
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
722 /**
723 * Process incoming notification.
724 *
725 * @throws \CRM_Core_Exception
726 * @throws \CiviCRM_API3_Exception
727 */
728 public static function handlePaymentNotification() {
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 }
735 $result = civicrm_api3('PaymentProcessor', 'get', [
736 'sequential' => 1,
737 'id' => $params['processor_id'],
738 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
739 ]);
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) {
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.
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.");
760 }
761
762 $paypalIPN->main();
763 }
764
765 /**
766 * @param string $message
767 * @param array $params
768 *
769 * @return array|bool|object
770 * @throws \Civi\Payment\Exception\PaymentProcessorException
771 */
772 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
773 if ($this->isPayPalType($this::PAYPAL_PRO)) {
774 $config = CRM_Core_Config::singleton();
775 $args = [];
776 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
777
778 $args['PROFILEID'] = $params['subscriptionId'];
779 $args['AMT'] = $this->getAmount($params);
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
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'];
791 $args['COUNTRYCODE'] = $params['postal_code'];
792 $args['ZIP'] = $params['country'];
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
804 /**
805 * @param string $message
806 * @param array $params
807 *
808 * @return array|bool|object
809 * @throws \Civi\Payment\Exception\PaymentProcessorException
810 */
811 public function changeSubscriptionAmount(&$message = '', $params = []) {
812 if ($this->isPayPalType($this::PAYPAL_PRO)) {
813 $config = CRM_Core_Config::singleton();
814 $args = [];
815 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
816
817 $args['PROFILEID'] = $params['subscriptionId'];
818 $args['AMT'] = $this->getAmount($params);
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
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.
842 * @throws \Civi\Payment\Exception\PaymentProcessorException
843 */
844 public function doPreApproval(&$params) {
845 if (!$this->isPaypalExpress($params)) {
846 return [];
847 }
848 $this->_component = $params['component'];
849 $token = $this->setExpressCheckOut($params);
850 return [
851 'pre_approval_parameters' => ['token' => $token],
852 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
853 ];
854 }
855
856 /**
857 * @param array $params
858 * @param string $component
859 *
860 * @throws Exception
861 */
862 public function doTransferCheckout(&$params, $component = 'contribute') {
863
864 $notifyParameters = ['module' => $component];
865 $notifyParameterMap = [
866 'contactID' => 'contactID',
867 'contributionID' => 'contributionID',
868 'eventID' => 'eventID',
869 'participantID' => 'participantID',
870 'membershipID' => 'membershipID',
871 'related_contact' => 'relatedContactID',
872 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
873 'accountingCode' => 'accountingCode',
874 'contributionRecurID' => 'contributionRecurID',
875 'contributionPageID' => 'contributionPageID',
876 ];
877 foreach ($notifyParameterMap as $paramsName => $notifyName) {
878 if (!empty($params[$paramsName])) {
879 $notifyParameters[$notifyName] = $params[$paramsName];
880 }
881 }
882 $notifyURL = $this->getNotifyUrl();
883
884 $config = CRM_Core_Config::singleton();
885 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
886 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
887
888 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
889 if (!empty($params['is_recur'])) {
890 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
891 }
892
893 $cancelURL = CRM_Utils_System::url(
894 $url,
895 $cancelUrlString,
896 TRUE, NULL, FALSE
897 );
898
899 $paypalParams = [
900 'business' => $this->_paymentProcessor['user_name'],
901 'notify_url' => $notifyURL,
902 'item_name' => $this->getPaymentDescription($params, 127),
903 'quantity' => 1,
904 'undefined_quantity' => 0,
905 'cancel_return' => $cancelURL,
906 'no_note' => 1,
907 'no_shipping' => 1,
908 'return' => $this->getReturnSuccessUrl($params['qfKey']),
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',
914 'custom' => json_encode($notifyParameters),
915 'bn' => 'CiviCRM_SP',
916 ];
917
918 // add name and address if available, CRM-3130
919 $otherVars = [
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',
929 ];
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'])) {
957 if (!$params['contributionRecurID']) {
958 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
959 }
960
961 $paypalParams += [
962 'cmd' => '_xclick-subscriptions',
963 'a3' => $this->getAmount($params),
964 'p3' => $params['frequency_interval'],
965 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
966 'src' => 1,
967 'sra' => 1,
968 'srt' => CRM_Utils_Array::value('installments', $params),
969 'no_note' => 1,
970 'modify' => 0,
971 ];
972 }
973 else {
974 $paypalParams += [
975 'cmd' => '_xclick',
976 'amount' => $params['amount'],
977 ];
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
999 $uri = substr($uri, 1);
1000 $url = $this->_paymentProcessor['url_site'];
1001 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
1002 $paypalURL = "{$url}{$sub}?$uri";
1003
1004 CRM_Utils_System::redirect($paypalURL);
1005 }
1006
1007 /**
1008 * Hash_call: Function to perform the API call to PayPal using API signature.
1009 *
1010 * @methodName is name of API method.
1011 * @nvpStr is nvp string.
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
1019 */
1020 public function invokeAPI($args, $url = NULL) {
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
1030 $p = [];
1031 foreach ($args as $n => $v) {
1032 $p[] = "$n=" . urlencode($v);
1033 }
1034
1035 //NVPRequest for submitting to server
1036 $nvpreq = implode('&', $p);
1037
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);
1045 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1046
1047 //turning off the server and peer verification(TrustManager Concept).
1048 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
1049 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
1050
1051 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1052 curl_setopt($ch, CURLOPT_POST, 1);
1053
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
1075 $outcome = strtolower(CRM_Utils_Array::value('ack', $result));
1076
1077 if ($outcome != 'success' && $outcome != 'successwithwarning') {
1078 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1079 }
1080
1081 return $result;
1082 }
1083
1084 /**
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
1092 */
1093 public static function deformat($str) {
1094 $result = [];
1095
1096 while (strlen($str)) {
1097 // position of key
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 }
1115
1116 /**
1117 * Get array of fields that should be displayed on the payment form.
1118 *
1119 * @return array
1120 * @throws \Civi\Payment\Exception\PaymentProcessorException
1121 */
1122 public function getPaymentFormFields() {
1123 if ($this->isPayPalType($this::PAYPAL_PRO)) {
1124 return $this->getCreditCardFormFields();
1125 }
1126 else {
1127 return [];
1128 }
1129 }
1130
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) {
1140 $params = [];
1141 foreach ($fieldMap as $civicrmField => $paypalField) {
1142 $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
1143 }
1144 return $params;
1145 }
1146
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
1155 * @throws \Civi\Payment\Exception\PaymentProcessorException
1156 */
1157 protected function isPaypalExpress($params) {
1158 if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
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.
1172 $possibleExpressFields = [
1173 '_qf_Register_upload_express_x',
1174 '_qf_Payment_upload_express_x',
1175 ];
1176 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {
1177 return TRUE;
1178 }
1179 return FALSE;
1180 }
1181
1182 }