3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 use Civi\Payment\Exception\PaymentProcessorException
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
23 class CRM_Core_Payment_PayPalImpl
extends CRM_Core_Payment
{
24 const CHARSET
= 'iso-8859-1';
26 const PAYPAL_PRO
= 'PayPal';
27 const PAYPAL_STANDARD
= 'PayPal_Standard';
28 const PAYPAL_EXPRESS
= 'PayPal_Express';
30 protected $_mode = NULL;
36 * The mode of operation: live or test.
38 * @param CRM_Core_Payment $paymentProcessor
40 * @return \CRM_Core_Payment_PayPalImpl
41 * @throws \Civi\Payment\Exception\PaymentProcessorException
43 public function __construct($mode, &$paymentProcessor) {
45 $this->_paymentProcessor
= $paymentProcessor;
49 * @var GuzzleHttp\Client
51 protected $guzzleClient;
54 * @return \GuzzleHttp\Client
56 public function getGuzzleClient(): \GuzzleHttp\Client
{
57 return $this->guzzleClient ??
new \GuzzleHttp\
Client();
61 * @param \GuzzleHttp\Client $guzzleClient
63 public function setGuzzleClient(\GuzzleHttp\Client
$guzzleClient) {
64 $this->guzzleClient
= $guzzleClient;
68 * Helper function to check which payment processor type is being used.
73 * @throws \Civi\Payment\Exception\PaymentProcessorException
75 public function isPayPalType($typeName) {
76 // 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
77 if (empty($this->_paymentProcessor
['payment_processor_type_id']) && empty($this->_paymentProcessor
['payment_processor_type'])) {
78 // We need one of them to be set!
79 throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
81 if (empty($this->_paymentProcessor
['payment_processor_type_id']) && !empty($this->_paymentProcessor
['payment_processor_type'])) {
82 // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not.
83 $this->_paymentProcessor
['payment_processor_type_id']
84 = CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor
['payment_processor_type']);
86 if ((int) $this->_paymentProcessor
['payment_processor_type_id'] ===
87 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) {
94 * Are back office payments supported.
96 * E.g paypal standard won't permit you to enter a credit card associated
97 * with someone else's login.
100 * @throws \Civi\Payment\Exception\PaymentProcessorException
102 protected function supportsBackOffice() {
103 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
110 * Does this processor support pre-approval.
112 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
114 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
115 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
116 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
119 * @throws \Civi\Payment\Exception\PaymentProcessorException
121 protected function supportsPreApproval() {
122 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
$this->isPayPalType($this::PAYPAL_PRO
)) {
129 * Opportunity for the payment processor to override the entire form build.
131 * @param CRM_Core_Form $form
134 * Should form building stop at this point?
135 * @throws \Civi\Payment\Exception\PaymentProcessorException
137 public function buildForm(&$form) {
138 if ($this->supportsPreApproval()) {
139 $this->addPaypalExpressCode($form);
140 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
141 CRM_Core_Region
::instance('billing-block-post')->add([
142 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
143 'name' => 'paypal_express',
146 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
147 CRM_Core_Region
::instance('billing-block-pre')->add([
148 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
156 * Billing mode button is basically synonymous with paypal express.
158 * This is probably a good example of 'odds & sods' code we
159 * need to find a way for the payment processor to assign.
161 * A tricky aspect is that the payment processor may need to set the order
163 * @param CRM_Core_Form $form
165 protected function addPaypalExpressCode(&$form) {
166 // @todo use $this->isBackOffice() instead, test.
167 if (empty($form->isBackOffice
)) {
170 * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment',
171 * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name
172 * and then clicking on express button it redirect to confirm screen rather than PayPal Express form
175 if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName
) {
176 $form->_expressButtonName
= '_qf_' . $form->_formName
. '_upload_express';
179 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
181 $form->assign('expressButtonName', $form->_expressButtonName
);
182 $form->add('xbutton', $form->_expressButtonName
, ts('Pay using PayPal'), [
184 'formnovalidate' => 'formnovalidate',
185 'class' => 'crm-form-submit',
187 CRM_Core_Resources
::singleton()->addStyle('
188 button#' . $form->_expressButtonName
. '{
189 background-image: url(' . $this->_paymentProcessor
['url_button'] . ');
191 background-repeat: no-repeat;
192 background-color: transparent;
193 background-position: center;
202 * Can recurring contributions be set against pledges.
204 * In practice all processors that use the baseIPN function to finish transactions or
205 * call the completetransaction api support this by looking up previous contributions in the
206 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
207 * adding the new payment to the pledge.
209 * However, only enabling for processors it has been tested against.
213 protected function supportsRecurContributionsForPledges() {
218 * Default payment instrument validation.
220 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
221 * Not a static function, because I need to check for payment_type.
223 * @param array $values
224 * @param array $errors
226 * @throws \Civi\Payment\Exception\PaymentProcessorException
228 public function validatePaymentInstrument($values, &$errors) {
229 if ($this->isPayPalType($this::PAYPAL_PRO
) && !$this->isPaypalExpress($values)) {
230 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
231 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
236 * Express checkout code.
238 * Check PayPal documentation for more information
240 * @param array $params
241 * Assoc array of input parameters for this transaction.
244 * the result in an nice formatted array (or an error object)
245 * @throws \Civi\Payment\Exception\PaymentProcessorException
247 protected function setExpressCheckOut(&$params) {
250 $this->initialize($args, 'SetExpressCheckout');
252 $args['paymentAction'] = 'Sale';
253 $args['amt'] = $params['amount'];
254 $args['currencyCode'] = $params['currencyID'];
255 $args['desc'] = $params['description'] ??
NULL;
256 $args['invnum'] = $params['invoiceID'];
257 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
258 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
259 $args['version'] = '56.0';
260 $args['SOLUTIONTYPE'] = 'Sole';
262 //LCD if recurring, collect additional data and set some values
263 if (!empty($params['is_recur'])) {
264 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
265 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
266 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
267 $args['L_PAYMENTTYPE0'] = 'Any';
270 // Allow further manipulation of the arguments via custom hooks ..
271 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
273 $result = $this->invokeAPI($args);
277 return $result['token'];
281 * Get any details that may be available to the payment processor due to an approval process having happened.
283 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
286 * @param array $storedDetails
289 * @throws \Civi\Payment\Exception\PaymentProcessorException
291 public function getPreApprovalDetails($storedDetails) {
292 return empty($storedDetails['token']) ?
[] : $this->getExpressCheckoutDetails($storedDetails['token']);
296 * Get details from paypal.
298 * Check PayPal documentation for more information
300 * @param string $token
301 * The key associated with this transaction.
304 * the result in an nice formatted array (or an error object)
305 * @throws \Civi\Payment\Exception\PaymentProcessorException
307 public function getExpressCheckoutDetails($token) {
310 $this->initialize($args, 'GetExpressCheckoutDetails');
311 $args['token'] = $token;
313 $args['method'] = 'GetExpressCheckoutDetails';
315 $result = $this->invokeAPI($args);
320 'payer_status' => 'payerstatus',
321 'payer_id' => 'payerid',
322 'billing_first_name' => 'firstname',
323 'billing_middle_name' => 'middlename',
324 'billing_last_name' => 'lastname',
325 'street_address' => 'shiptostreet',
326 'supplemental_address_1' => 'shiptostreet2',
327 'city' => 'shiptocity',
328 'postal_code' => 'shiptozip',
329 'state_province' => 'shiptostate',
330 'country' => 'shiptocountrycode',
332 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
336 * Do the express checkout at paypal.
338 * Check PayPal documentation for more information
340 * @param array $params
343 * The result in an nice formatted array.
345 * @throws \Civi\Payment\Exception\PaymentProcessorException
347 public function doExpressCheckout(&$params) {
348 if (!empty($params['is_recur'])) {
349 return $this->createRecurringPayments($params);
353 $this->initialize($args, 'DoExpressCheckoutPayment');
354 $args['token'] = $params['token'];
355 $args['paymentAction'] = 'Sale';
356 $args['amt'] = $params['amount'];
357 $args['currencyCode'] = $params['currencyID'];
358 $args['payerID'] = $params['payer_id'];
359 $args['invnum'] = $params['invoiceID'];
360 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
361 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
362 $args['desc'] = $params['description'];
364 // add CiviCRM BN code
365 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
367 $result = $this->invokeAPI($args);
370 $params['trxn_id'] = $result['transactionid'];
371 $params['fee_amount'] = $result['feeamt'];
372 $params['net_amount'] = $result['settleamt'] ??
NULL;
373 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
374 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
376 $params['payment_status'] = $result['paymentstatus'];
377 $params['pending_reason'] = $result['pendingreason'];
378 if (!empty($params['is_recur'])) {
379 // See comment block.
380 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
383 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
389 * Create recurring payments.
391 * Use a pre-authorisation token to activate a recurring payment profile
392 * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
394 * @param array $params
399 public function createRecurringPayments(&$params) {
401 $this->initialize($args, 'CreateRecurringPaymentsProfile');
403 $start_time = strtotime(date('m/d/Y'));
404 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
406 $args['token'] = $params['token'];
407 $args['paymentAction'] = 'Sale';
408 $args['amt'] = $params['amount'];
409 $args['currencyCode'] = $params['currencyID'];
410 $args['payerID'] = $params['payer_id'];
411 $args['invnum'] = $params['invoiceID'];
412 $args['profilestartdate'] = $start_date;
413 $args['method'] = 'CreateRecurringPaymentsProfile';
414 $args['billingfrequency'] = $params['frequency_interval'];
415 $args['billingperiod'] = ucwords($params['frequency_unit']);
416 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
417 $args['totalbillingcycles'] = $params['installments'] ??
NULL;
418 $args['version'] = '56.0';
419 $args['profilereference'] = "i={$params['invoiceID']}" .
421 "&c={$params['contactID']}" .
422 "&r={$params['contributionRecurID']}" .
423 "&b={$params['contributionID']}" .
424 "&p={$params['contributionPageID']}";
426 // add CiviCRM BN code
427 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
429 $result = $this->invokeAPI($args);
431 /* Success - result looks like"
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',)
441 $params['trxn_id'] = $result['profileid'];
442 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
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'] = $this->_paymentProcessor
['subject'] ??
NULL;
459 $args['method'] = $method;
463 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
465 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
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.
472 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
475 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
476 * return Error objects
478 * @param array $params
480 * @param string $component
485 * @throws \Civi\Payment\Exception\PaymentProcessorException
487 public function doPayment(&$params, $component = 'contribute') {
488 $this->_component
= $component;
489 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
($this->isPayPalType($this::PAYPAL_PRO
) && !empty($params['token']))) {
490 return $this->doExpressCheckout($params);
494 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
496 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
497 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
498 // have an example of that at the mome.
499 if ($params['amount'] == 0) {
500 $result['payment_status_id'] = array_search('Completed', $statuses);
501 $result['payment_status'] = 'Completed';
505 if ($this->_paymentProcessor
['billing_mode'] == 4) {
506 $this->doPaymentRedirectToPayPal($params, $component);
507 // redirect calls CiviExit() so execution is stopped
510 $result = $this->doPaymentPayPalButton($params, $component);
511 if (is_array($result) && !isset($result['payment_status_id'])) {
512 if (!empty($params['is_recur'])) {
513 // See comment block.
514 $result['payment_status_id'] = array_search('Pending', $statuses);
515 $result['payment_status'] = 'Pending';
518 $result['payment_status_id'] = array_search('Completed', $statuses);
519 $result['payment_status'] = 'Completed';
523 if (is_a($result, 'CRM_Core_Error')) {
524 CRM_Core_Error
::deprecatedFunctionWarning('payment processors should throw exceptions rather than return errors');
525 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
531 * Temporary function to catch transition to doPaymentPayPalButton()
534 public function doDirectPayment(&$params) {
535 CRM_Core_Error
::deprecatedFunctionWarning('doPayment');
536 return $this->doPaymentPayPalButton($params);
540 * This function collects all the information from a web/api form and invokes
541 * the relevant payment processor specific functions to perform the transaction
543 * @param array $params
544 * Assoc array of input parameters for this transaction.
546 * @param string $component
548 * the result in an nice formatted array (or an error object)
549 * @throws \Civi\Payment\Exception\PaymentProcessorException
551 public function doPaymentPayPalButton(&$params, $component = 'contribute') {
554 $this->initialize($args, 'DoDirectPayment');
556 $args['paymentAction'] = 'Sale';
557 $args['amt'] = $this->getAmount($params);
558 $args['currencyCode'] = $this->getCurrency($params);
559 $args['invnum'] = $params['invoiceID'];
560 $args['ipaddress'] = $params['ip_address'];
561 $args['creditCardType'] = $params['credit_card_type'];
562 $args['acct'] = $params['credit_card_number'];
563 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
564 $args['cvv2'] = $params['cvv2'];
565 $args['firstName'] = $params['first_name'];
566 $args['lastName'] = $params['last_name'];
567 $args['email'] = $params['email'] ??
NULL;
568 $args['street'] = $params['street_address'];
569 $args['city'] = $params['city'];
570 $args['state'] = $params['state_province'];
571 $args['countryCode'] = $params['country'];
572 $args['zip'] = $params['postal_code'];
573 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
574 $args['custom'] = $params['accountingCode'] ??
NULL;
576 // add CiviCRM BN code
577 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
579 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
580 $start_time = strtotime(date('m/d/Y'));
581 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
583 $args['PaymentAction'] = 'Sale';
584 $args['billingperiod'] = ucwords($params['frequency_unit']);
585 $args['billingfrequency'] = $params['frequency_interval'];
586 $args['method'] = "CreateRecurringPaymentsProfile";
587 $args['profilestartdate'] = $start_date;
589 $params['description'] . ": " .
590 $params['amount'] . " Per " .
591 $params['frequency_interval'] . " " .
592 $params['frequency_unit'];
593 $args['amt'] = $this->getAmount($params);
594 $args['totalbillingcycles'] = $params['installments'] ??
NULL;
595 $args['version'] = 56.0;
596 $args['PROFILEREFERENCE'] = "" .
597 "i=" . $params['invoiceID'] . "&m=" . $component .
598 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
599 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
602 // Allow further manipulation of the arguments via custom hooks ..
603 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
605 $result = $this->invokeAPI($args);
607 $params['recurr_profile_id'] = NULL;
609 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
610 $params['recurr_profile_id'] = $result['profileid'];
615 $params['trxn_id'] = $result['transactionid'] ??
NULL;
616 $params['gross_amount'] = $result['amt'] ??
NULL;
617 $params = array_merge($params, $this->doQuery($params));
622 * Query payment processor for details about a transaction.
624 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
626 * @param array $params
627 * Array of parameters containing one of:
628 * - trxn_id Id of an individual transaction.
629 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
632 * Extra parameters retrieved.
633 * Any parameters retrievable through this should be documented in the function comments at
634 * CRM_Core_Payment::doQuery. Currently
635 * - fee_amount Amount of fee paid
637 * @throws \Civi\Payment\Exception\PaymentProcessorException
639 public function doQuery($params) {
640 //CRM-18140 - trxn_id not returned for recurring paypal transaction
641 if (!empty($params['is_recur'])) {
644 elseif (empty($params['trxn_id'])) {
645 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
648 'TRANSACTIONID' => $params['trxn_id'],
650 $this->initialize($args, 'GetTransactionDetails');
651 $result = $this->invokeAPI($args);
653 'fee_amount' => $result['feeamt'],
654 'net_amount' => $params['gross_amount'] - $result['feeamt'],
659 * This function checks to see if we have the right config values.
661 * @return null|string
662 * the error message if any
663 * @throws \Civi\Payment\Exception\PaymentProcessorException
665 public function checkConfig() {
668 if (!$this->isPayPalType($this::PAYPAL_STANDARD
)) {
669 if (empty($this->_paymentProcessor
['signature'])) {
670 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
673 if (empty($this->_paymentProcessor
['password'])) {
674 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
677 if (empty($this->_paymentProcessor
['user_name'])) {
678 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
680 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
681 if (empty($this->_paymentProcessor
['url_site'])) {
682 $error[] = ts('Site URL is not set (eg. https://www.paypal.com/ - https://www.sandbox.paypal.com/)');
686 if (!empty($error)) {
687 return implode('<p>', $error);
695 * Get url for users to manage this recurring contribution for this processor.
697 * @param int $entityID
698 * @param string|null $entity
699 * @param string $action
701 * @return string|null
702 * @throws \CRM_Core_Exception
704 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
705 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
706 if ($action !== 'cancel') {
709 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
711 return parent
::subscriptionURL($entityID, $entity, $action);
715 * Check whether a method is present ( & supported ) by the payment processor object.
717 * @param string $method
718 * Method to check for.
721 * @throws \Civi\Payment\Exception\PaymentProcessorException
723 public function isSupported($method) {
724 if (!$this->isPayPalType($this::PAYPAL_PRO
)) {
725 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
726 // by standard or express.
729 return parent
::isSupported($method);
733 * Paypal express replaces the submit button with it's own.
736 * Should the form button by suppressed?
737 * @throws \Civi\Payment\Exception\PaymentProcessorException
739 public function isSuppressSubmitButtons() {
740 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
747 * @param string $message
748 * @param array $params
751 * @throws \Civi\Payment\Exception\PaymentProcessorException
753 public function cancelSubscription(&$message = '', $params = []) {
754 if ($this->isPayPalType($this::PAYPAL_PRO
) ||
$this->isPayPalType($this::PAYPAL_EXPRESS
)) {
756 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
758 $args['PROFILEID'] = $params['subscriptionId'] ??
NULL;
759 $args['ACTION'] = 'Cancel';
760 $args['NOTE'] = $params['reason'] ??
NULL;
762 $result = $this->invokeAPI($args);
764 $message = "{$result['ack']}: profileid={$result['profileid']}";
771 * Process incoming notification.
773 * @throws \CRM_Core_Exception
774 * @throws \CiviCRM_API3_Exception
776 public function handlePaymentNotification() {
777 $params = array_merge($_GET, $_REQUEST);
778 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
779 $lastParam = array_pop($q);
780 if (is_numeric($lastParam)) {
781 $params['processor_id'] = $lastParam;
783 $result = civicrm_api3('PaymentProcessor', 'get', [
785 'id' => $params['processor_id'],
786 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
788 if (!$result['count']) {
789 throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
792 $paymentProcessorType = $result['values'][0]['api.PaymentProcessorType.getvalue'] ??
NULL;
793 switch ($paymentProcessorType) {
795 // "PayPal - Website Payments Pro"
796 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
799 case 'PayPal_Express':
800 // "PayPal - Express"
801 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
804 case 'PayPal_Standard':
805 // "PayPal - Website Payments Standard"
806 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
810 // If we don't have PayPal Standard or PayPal Pro, something's wrong.
811 // Log an error and exit.
812 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.");
819 * @param string $message
820 * @param array $params
822 * @return array|bool|object
823 * @throws \Civi\Payment\Exception\PaymentProcessorException
825 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
826 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
827 $config = CRM_Core_Config
::singleton();
829 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
831 $args['PROFILEID'] = $params['subscriptionId'];
832 $args['AMT'] = $this->getAmount($params);
833 $args['CURRENCYCODE'] = $config->defaultCurrency
;
834 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
835 $args['ACCT'] = $params['credit_card_number'];
836 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
837 $args['CVV2'] = $params['cvv2'];
839 $args['FIRSTNAME'] = $params['first_name'];
840 $args['LASTNAME'] = $params['last_name'];
841 $args['STREET'] = $params['street_address'];
842 $args['CITY'] = $params['city'];
843 $args['STATE'] = $params['state_province'];
844 $args['COUNTRYCODE'] = $params['postal_code'];
845 $args['ZIP'] = $params['country'];
847 $result = $this->invokeAPI($args);
849 $message = "{$result['ack']}: profileid={$result['profileid']}";
856 * @param string $message
857 * @param array $params
860 * @throws \Civi\Payment\Exception\PaymentProcessorException
862 public function changeSubscriptionAmount(&$message = '', $params = []) {
863 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
864 $config = CRM_Core_Config
::singleton();
866 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
868 $args['PROFILEID'] = $params['subscriptionId'];
869 $args['AMT'] = $this->getAmount($params);
870 $args['CURRENCYCODE'] = $config->defaultCurrency
;
871 $args['BILLINGFREQUENCY'] = $params['installments'];
873 $result = $this->invokeAPI($args);
874 CRM_Core_Error
::debug_var('$result', $result);
876 $message = "{$result['ack']}: profileid={$result['profileid']}";
883 * Function to action pre-approval if supported
885 * @param array $params
886 * Parameters from the form
889 * - pre_approval_parameters (this will be stored on the calling form & available later)
890 * - redirect_url (if set the browser will be redirected to this.
891 * @throws \Civi\Payment\Exception\PaymentProcessorException
893 public function doPreApproval(&$params) {
894 if (!$this->isPaypalExpress($params)) {
897 $this->_component
= $params['component'];
898 $token = $this->setExpressCheckOut($params);
899 $siteUrl = rtrim($this->_paymentProcessor
['url_site'], '/');
901 'pre_approval_parameters' => ['token' => $token],
902 'redirect_url' => $siteUrl . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
907 * Temporary function to catch transition to doPaymentRedirectToPayPal()
910 public function doTransferCheckout(&$params, $component = 'contribute') {
911 CRM_Core_Error
::deprecatedFunctionWarning('doPayment');
912 $this->doPaymentRedirectToPayPal($params);
916 * @param array $params
917 * @param string $component
921 public function doPaymentRedirectToPayPal(&$params, $component = 'contribute') {
922 $notifyParameters = ['module' => $component];
923 $notifyParameterMap = [
924 'contactID' => 'contactID',
925 'contributionID' => 'contributionID',
926 'eventID' => 'eventID',
927 'participantID' => 'participantID',
928 'membershipID' => 'membershipID',
929 'related_contact' => 'relatedContactID',
930 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
931 'accountingCode' => 'accountingCode',
932 'contributionRecurID' => 'contributionRecurID',
933 'contributionPageID' => 'contributionPageID',
935 foreach ($notifyParameterMap as $paramsName => $notifyName) {
936 if (!empty($params[$paramsName])) {
937 $notifyParameters[$notifyName] = $params[$paramsName];
940 $notifyURL = $this->getNotifyUrl();
942 $config = CRM_Core_Config
::singleton();
943 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
944 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
946 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
947 if (!empty($params['is_recur'])) {
948 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
951 $cancelURL = CRM_Utils_System
::url(
958 'business' => $this->_paymentProcessor
['user_name'],
959 'notify_url' => $notifyURL,
960 'item_name' => $this->getPaymentDescription($params, 127),
962 'undefined_quantity' => 0,
963 'cancel_return' => $cancelURL,
966 'return' => $this->getReturnSuccessUrl($params['qfKey']),
968 'currency_code' => $params['currencyID'],
969 'invoice' => $params['invoiceID'],
970 'lc' => substr($config->lcMessages
, -2),
971 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
972 'custom' => json_encode($notifyParameters),
973 'bn' => 'CiviCRM_SP',
976 // add name and address if available, CRM-3130
978 'first_name' => 'first_name',
979 'last_name' => 'last_name',
980 'street_address' => 'address1',
981 'country' => 'country',
982 'preferred_language' => 'lc',
984 'state_province' => 'state',
985 'postal_code' => 'zip',
989 foreach (array_keys($params) as $p) {
990 // get the base name without the location type suffixed to it
991 $parts = explode('-', $p);
992 $name = count($parts) > 1 ?
$parts[0] : $p;
993 if (isset($otherVars[$name])) {
994 $value = $params[$p];
996 if ($name == 'state_province') {
997 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
1000 if ($name == 'country') {
1001 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
1002 $value = $countryName;
1004 // ensure value is not an array
1006 if (!is_array($value)) {
1007 $paypalParams[$otherVars[$name]] = $value;
1013 // if recurring donations, add a few more items
1014 if (!empty($params['is_recur'])) {
1015 if (!$params['contributionRecurID']) {
1016 throw new CRM_Core_Exception(ts('Recurring contribution, but no database id'));
1020 'cmd' => '_xclick-subscriptions',
1021 'a3' => $this->getAmount($params),
1022 'p3' => $params['frequency_interval'],
1023 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
1026 'srt' => $params['installments'] ??
NULL,
1034 'amount' => $params['amount'],
1038 // Allow further manipulation of the arguments via custom hooks ..
1039 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
1042 * PayPal urlencodes the IPN Notify URL. For sites not using Clean URLs (or
1043 * using Shortcodes in WordPress) this results in "%2F" becoming "%252F" and
1044 * therefore incomplete transactions. We need to prevent that.
1045 * @see https://lab.civicrm.org/dev/core/-/issues/1931
1047 $paypalParams['notify_url'] = rawurldecode($paypalParams['notify_url']);
1050 foreach ($paypalParams as $key => $value) {
1051 if ($value === NULL) {
1055 $value = urlencode($value);
1056 if ($key == 'return' ||
1057 $key == 'cancel_return' ||
1058 $key == 'notify_url'
1060 $value = str_replace('%2F', '/', $value);
1062 $uri .= "&{$key}={$value}";
1065 $uri = substr($uri, 1);
1066 $url = $this->_paymentProcessor
['url_site'];
1067 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
1068 $paypalURL = "{$url}{$sub}?$uri";
1070 // Allow each CMS to do a pre-flight check before redirecting to PayPal.
1071 CRM_Core_Config
::singleton()->userSystem
->prePostRedirect();
1072 CRM_Utils_System
::redirect($paypalURL);
1076 * Hash_call: Function to perform the API call to PayPal using API signature.
1078 * @methodName is name of API method.
1079 * @nvpStr is nvp string.
1080 * returns an associative array containing the response from the server.
1082 * @param array $args
1084 * @return array|object
1085 * @throws \Civi\Payment\Exception\PaymentProcessorException
1087 public function invokeAPI($args) {
1089 if (empty($this->_paymentProcessor
['url_api'])) {
1090 throw new PaymentProcessorException(ts('Please set the API URL. Please refer to the documentation for more details'));
1093 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
1096 foreach ($args as $n => $v) {
1097 $p[] = "$n=" . urlencode($v);
1100 //NVPRequest for submitting to server
1101 $nvpreq = implode('&', $p);
1103 if (!function_exists('curl_init')) {
1104 throw new PaymentProcessorException('curl functions NOT available.');
1107 $response = (string) $this->getGuzzleClient()->post($url, [
1110 CURLOPT_RETURNTRANSFER
=> TRUE,
1111 CURLOPT_SSL_VERIFYPEER
=> Civi
::settings()->get('verifySSL'),
1115 $result = self
::deformat($response);
1117 $outcome = strtolower($result['ack'] ??
'');
1119 if ($outcome !== 'success' && $outcome !== 'successwithwarning') {
1120 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1127 * This function will take NVPString and convert it to an Associative Array.
1129 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1131 * @param string $str
1135 public static function deformat($str) {
1138 while (strlen($str)) {
1140 $keyPos = strpos($str, '=');
1142 // position of value
1143 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1145 /*getting the Key and Value values and storing in a Associative Array*/
1147 $key = substr($str, 0, $keyPos);
1148 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1150 //decoding the respose
1151 $result[strtolower(urldecode($key))] = urldecode($val);
1152 $str = substr($str, $valPos +
1, strlen($str));
1159 * Get array of fields that should be displayed on the payment form.
1162 * @throws \Civi\Payment\Exception\PaymentProcessorException
1164 public function getPaymentFormFields() {
1165 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
1166 return $this->getCreditCardFormFields();
1174 * Map the paypal params to CiviCRM params using a field map.
1176 * @param array $fieldMap
1177 * @param array $paypalParams
1181 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1183 foreach ($fieldMap as $civicrmField => $paypalField) {
1184 $params[$civicrmField] = $paypalParams[$paypalField] ??
NULL;
1190 * Is this being processed by payment express.
1192 * Either because it is payment express or because is pro with paypal express in use.
1194 * @param array $params
1197 * @throws \Civi\Payment\Exception\PaymentProcessorException
1199 protected function isPaypalExpress($params) {
1200 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
1203 // This would occur postProcess.
1204 if (!empty($params['token'])) {
1207 if (isset($params['button']) && stristr($params['button'], 'express')) {
1211 // The contribution form passes a 'button' but the event form might still set one of these fields.
1212 // @todo more standardisation & get paypal fully out of the form layer.
1213 $possibleExpressFields = [
1214 // @todo - we think these top 2 are likely not required & it's still here
1215 // on a precautionary basis.
1216 // see https://github.com/civicrm/civicrm-core/pull/18680
1217 '_qf_Register_upload_express_x',
1218 '_qf_Payment_upload_express_x',
1219 '_qf_Register_upload_express',
1220 '_qf_Payment_upload_express',
1221 '_qf_Main_upload_express',
1223 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {