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 * Helper function to check which payment processor type is being used.
54 * @throws \Civi\Payment\Exception\PaymentProcessorException
56 public function isPayPalType($typeName) {
57 // Historically payment_processor_type may have been set to the name of the processor but newer versions of CiviCRM use the id set in payment_processor_type_id
58 if (empty($this->_paymentProcessor
['payment_processor_type_id']) && empty($this->_paymentProcessor
['payment_processor_type'])) {
59 // We need one of them to be set!
60 throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
62 if (empty($this->_paymentProcessor
['payment_processor_type_id']) && !empty($this->_paymentProcessor
['payment_processor_type'])) {
63 // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not.
64 $this->_paymentProcessor
['payment_processor_type_id']
65 = CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor
['payment_processor_type']);
67 if ((int) $this->_paymentProcessor
['payment_processor_type_id'] ===
68 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) {
75 * Are back office payments supported.
77 * E.g paypal standard won't permit you to enter a credit card associated
78 * with someone else's login.
81 * @throws \Civi\Payment\Exception\PaymentProcessorException
83 protected function supportsBackOffice() {
84 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
91 * Does this processor support pre-approval.
93 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
95 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
96 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
97 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
100 * @throws \Civi\Payment\Exception\PaymentProcessorException
102 protected function supportsPreApproval() {
103 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
$this->isPayPalType($this::PAYPAL_PRO
)) {
110 * Opportunity for the payment processor to override the entire form build.
112 * @param CRM_Core_Form $form
115 * Should form building stop at this point?
116 * @throws \Civi\Payment\Exception\PaymentProcessorException
118 public function buildForm(&$form) {
119 if ($this->supportsPreApproval()) {
120 $this->addPaypalExpressCode($form);
121 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
122 CRM_Core_Region
::instance('billing-block-post')->add([
123 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
124 'name' => 'paypal_express',
127 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
128 CRM_Core_Region
::instance('billing-block-pre')->add([
129 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
137 * Billing mode button is basically synonymous with paypal express.
139 * This is probably a good example of 'odds & sods' code we
140 * need to find a way for the payment processor to assign.
142 * A tricky aspect is that the payment processor may need to set the order
144 * @param CRM_Core_Form $form
146 protected function addPaypalExpressCode(&$form) {
147 // @todo use $this->isBackOffice() instead, test.
148 if (empty($form->isBackOffice
)) {
151 * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment',
152 * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name
153 * and then clicking on express button it redirect to confirm screen rather than PayPal Express form
156 if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName
) {
157 $form->_expressButtonName
= '_qf_' . $form->_formName
. '_upload_express';
160 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
162 $form->assign('expressButtonName', $form->_expressButtonName
);
165 $form->_expressButtonName
,
166 $this->_paymentProcessor
['url_button'],
167 ['class' => 'crm-form-submit']
173 * Can recurring contributions be set against pledges.
175 * In practice all processors that use the baseIPN function to finish transactions or
176 * call the completetransaction api support this by looking up previous contributions in the
177 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
178 * adding the new payment to the pledge.
180 * However, only enabling for processors it has been tested against.
184 protected function supportsRecurContributionsForPledges() {
189 * Default payment instrument validation.
191 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
192 * Not a static function, because I need to check for payment_type.
194 * @param array $values
195 * @param array $errors
197 * @throws \Civi\Payment\Exception\PaymentProcessorException
199 public function validatePaymentInstrument($values, &$errors) {
200 if ($this->isPayPalType($this::PAYPAL_PRO
) && !$this->isPaypalExpress($values)) {
201 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
202 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
207 * Express checkout code.
209 * Check PayPal documentation for more information
211 * @param array $params
212 * Assoc array of input parameters for this transaction.
215 * the result in an nice formatted array (or an error object)
216 * @throws \Civi\Payment\Exception\PaymentProcessorException
218 protected function setExpressCheckOut(&$params) {
221 $this->initialize($args, 'SetExpressCheckout');
223 $args['paymentAction'] = 'Sale';
224 $args['amt'] = $params['amount'];
225 $args['currencyCode'] = $params['currencyID'];
226 $args['desc'] = $params['description'] ??
NULL;
227 $args['invnum'] = $params['invoiceID'];
228 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
229 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
230 $args['version'] = '56.0';
231 $args['SOLUTIONTYPE'] = 'Sole';
233 //LCD if recurring, collect additional data and set some values
234 if (!empty($params['is_recur'])) {
235 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
236 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
237 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
238 $args['L_PAYMENTTYPE0'] = 'Any';
241 // Allow further manipulation of the arguments via custom hooks ..
242 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
244 $result = $this->invokeAPI($args);
248 return $result['token'];
252 * Get any details that may be available to the payment processor due to an approval process having happened.
254 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
257 * @param array $storedDetails
260 * @throws \Civi\Payment\Exception\PaymentProcessorException
262 public function getPreApprovalDetails($storedDetails) {
263 return empty($storedDetails['token']) ?
[] : $this->getExpressCheckoutDetails($storedDetails['token']);
267 * Get details from paypal.
269 * Check PayPal documentation for more information
271 * @param string $token
272 * The key associated with this transaction.
275 * the result in an nice formatted array (or an error object)
276 * @throws \Civi\Payment\Exception\PaymentProcessorException
278 public function getExpressCheckoutDetails($token) {
281 $this->initialize($args, 'GetExpressCheckoutDetails');
282 $args['token'] = $token;
284 $args['method'] = 'GetExpressCheckoutDetails';
286 $result = $this->invokeAPI($args);
291 'payer_status' => 'payerstatus',
292 'payer_id' => 'payerid',
293 'billing_first_name' => 'firstname',
294 'billing_middle_name' => 'middlename',
295 'billing_last_name' => 'lastname',
296 'street_address' => 'shiptostreet',
297 'supplemental_address_1' => 'shiptostreet2',
298 'city' => 'shiptocity',
299 'postal_code' => 'shiptozip',
300 'state_province' => 'shiptostate',
301 'country' => 'shiptocountrycode',
303 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
307 * Do the express checkout at paypal.
309 * Check PayPal documentation for more information
311 * @param array $params
314 * The result in an nice formatted array.
316 * @throws \Civi\Payment\Exception\PaymentProcessorException
318 public function doExpressCheckout(&$params) {
319 if (!empty($params['is_recur'])) {
320 return $this->createRecurringPayments($params);
324 $this->initialize($args, 'DoExpressCheckoutPayment');
325 $args['token'] = $params['token'];
326 $args['paymentAction'] = 'Sale';
327 $args['amt'] = $params['amount'];
328 $args['currencyCode'] = $params['currencyID'];
329 $args['payerID'] = $params['payer_id'];
330 $args['invnum'] = $params['invoiceID'];
331 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
332 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
333 $args['desc'] = $params['description'];
335 // add CiviCRM BN code
336 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
338 $result = $this->invokeAPI($args);
341 $params['trxn_id'] = $result['transactionid'];
342 $params['gross_amount'] = $result['amt'];
343 $params['fee_amount'] = $result['feeamt'];
344 $params['net_amount'] = $result['settleamt'] ??
NULL;
345 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
346 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
348 $params['payment_status'] = $result['paymentstatus'];
349 $params['pending_reason'] = $result['pendingreason'];
350 if (!empty($params['is_recur'])) {
351 // See comment block.
352 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
355 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
361 * Create recurring payments.
363 * Use a pre-authorisation token to activate a recurring payment profile
364 * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
366 * @param array $params
371 public function createRecurringPayments(&$params) {
373 $this->initialize($args, 'CreateRecurringPaymentsProfile');
375 $start_time = strtotime(date('m/d/Y'));
376 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
378 $args['token'] = $params['token'];
379 $args['paymentAction'] = 'Sale';
380 $args['amt'] = $params['amount'];
381 $args['currencyCode'] = $params['currencyID'];
382 $args['payerID'] = $params['payer_id'];
383 $args['invnum'] = $params['invoiceID'];
384 $args['profilestartdate'] = $start_date;
385 $args['method'] = 'CreateRecurringPaymentsProfile';
386 $args['billingfrequency'] = $params['frequency_interval'];
387 $args['billingperiod'] = ucwords($params['frequency_unit']);
388 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
389 $args['totalbillingcycles'] = $params['installments'] ??
NULL;
390 $args['version'] = '56.0';
391 $args['profilereference'] = "i={$params['invoiceID']}" .
393 "&c={$params['contactID']}" .
394 "&r={$params['contributionRecurID']}" .
395 "&b={$params['contributionID']}" .
396 "&p={$params['contributionPageID']}";
398 // add CiviCRM BN code
399 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
401 $result = $this->invokeAPI($args);
403 /* Success - result looks like"
405 * 'profileid' => 'I-CP1U0PLG91R2',
406 * 'profilestatus' => 'ActiveProfile',
407 * 'timestamp' => '2018-05-07T03:55:52Z',
408 * 'correlationid' => 'e717999e9bf62',
409 * 'ack' => 'Success',
410 * 'version' => '56.0',
411 * 'build' => '39949200',)
413 $params['trxn_id'] = $result['profileid'];
414 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
425 public function initialize(&$args, $method) {
426 $args['user'] = $this->_paymentProcessor
['user_name'];
427 $args['pwd'] = $this->_paymentProcessor
['password'];
428 $args['version'] = 3.0;
429 $args['signature'] = $this->_paymentProcessor
['signature'];
430 $args['subject'] = $this->_paymentProcessor
['subject'] ??
NULL;
431 $args['method'] = $method;
435 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
437 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
440 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
441 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
442 * doTransferCheckout would not traditionally come back.
444 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
447 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
448 * return Error objects
450 * @param array $params
452 * @param string $component
457 * @throws \Civi\Payment\Exception\PaymentProcessorException
459 public function doPayment(&$params, $component = 'contribute') {
460 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
($this->isPayPalType($this::PAYPAL_PRO
) && !empty($params['token']))) {
461 $this->_component
= $component;
462 return $this->doExpressCheckout($params);
465 return parent
::doPayment($params, $component);
469 * This function collects all the information from a web/api form and invokes
470 * the relevant payment processor specific functions to perform the transaction
472 * @param array $params
473 * Assoc array of input parameters for this transaction.
475 * @param string $component
477 * the result in an nice formatted array (or an error object)
478 * @throws \Civi\Payment\Exception\PaymentProcessorException
480 public function doDirectPayment(&$params, $component = 'contribute') {
483 $this->initialize($args, 'DoDirectPayment');
485 $args['paymentAction'] = 'Sale';
486 $args['amt'] = $this->getAmount($params);
487 $args['currencyCode'] = $this->getCurrency($params);
488 $args['invnum'] = $params['invoiceID'];
489 $args['ipaddress'] = $params['ip_address'];
490 $args['creditCardType'] = $params['credit_card_type'];
491 $args['acct'] = $params['credit_card_number'];
492 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
493 $args['cvv2'] = $params['cvv2'];
494 $args['firstName'] = $params['first_name'];
495 $args['lastName'] = $params['last_name'];
496 $args['email'] = $params['email'] ??
NULL;
497 $args['street'] = $params['street_address'];
498 $args['city'] = $params['city'];
499 $args['state'] = $params['state_province'];
500 $args['countryCode'] = $params['country'];
501 $args['zip'] = $params['postal_code'];
502 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
503 $args['custom'] = $params['accountingCode'] ??
NULL;
505 // add CiviCRM BN code
506 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
508 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
509 $start_time = strtotime(date('m/d/Y'));
510 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
512 $args['PaymentAction'] = 'Sale';
513 $args['billingperiod'] = ucwords($params['frequency_unit']);
514 $args['billingfrequency'] = $params['frequency_interval'];
515 $args['method'] = "CreateRecurringPaymentsProfile";
516 $args['profilestartdate'] = $start_date;
518 $params['description'] . ": " .
519 $params['amount'] . " Per " .
520 $params['frequency_interval'] . " " .
521 $params['frequency_unit'];
522 $args['amt'] = $this->getAmount($params);
523 $args['totalbillingcycles'] = $params['installments'] ??
NULL;
524 $args['version'] = 56.0;
525 $args['PROFILEREFERENCE'] = "" .
526 "i=" . $params['invoiceID'] . "&m=" . $component .
527 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
528 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
531 // Allow further manipulation of the arguments via custom hooks ..
532 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
534 $result = $this->invokeAPI($args);
536 $params['recurr_profile_id'] = NULL;
538 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
539 $params['recurr_profile_id'] = $result['profileid'];
544 $params['trxn_id'] = $result['transactionid'] ??
NULL;
545 $params['gross_amount'] = $result['amt'] ??
NULL;
546 $params = array_merge($params, $this->doQuery($params));
551 * Query payment processor for details about a transaction.
553 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
555 * @param array $params
556 * Array of parameters containing one of:
557 * - trxn_id Id of an individual transaction.
558 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
561 * Extra parameters retrieved.
562 * Any parameters retrievable through this should be documented in the function comments at
563 * CRM_Core_Payment::doQuery. Currently
564 * - fee_amount Amount of fee paid
566 * @throws \Civi\Payment\Exception\PaymentProcessorException
568 public function doQuery($params) {
569 //CRM-18140 - trxn_id not returned for recurring paypal transaction
570 if (!empty($params['is_recur'])) {
573 elseif (empty($params['trxn_id'])) {
574 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
577 'TRANSACTIONID' => $params['trxn_id'],
579 $this->initialize($args, 'GetTransactionDetails');
580 $result = $this->invokeAPI($args);
582 'fee_amount' => $result['feeamt'],
583 'net_amount' => $params['gross_amount'] - $result['feeamt'],
588 * This function checks to see if we have the right config values.
590 * @return null|string
591 * the error message if any
592 * @throws \Civi\Payment\Exception\PaymentProcessorException
594 public function checkConfig() {
597 if (!$this->isPayPalType($this::PAYPAL_STANDARD
)) {
598 if (empty($this->_paymentProcessor
['signature'])) {
599 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
602 if (empty($this->_paymentProcessor
['password'])) {
603 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
606 if (empty($this->_paymentProcessor
['user_name'])) {
607 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
610 if (!empty($error)) {
611 return implode('<p>', $error);
619 * @return null|string
620 * @throws \Civi\Payment\Exception\PaymentProcessorException
622 public function cancelSubscriptionURL() {
623 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
624 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
632 * Check whether a method is present ( & supported ) by the payment processor object.
634 * @param string $method
635 * Method to check for.
638 * @throws \Civi\Payment\Exception\PaymentProcessorException
640 public function isSupported($method) {
641 if (!$this->isPayPalType($this::PAYPAL_PRO
)) {
642 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
643 // by standard or express.
646 return parent
::isSupported($method);
650 * Paypal express replaces the submit button with it's own.
653 * Should the form button by suppressed?
654 * @throws \Civi\Payment\Exception\PaymentProcessorException
656 public function isSuppressSubmitButtons() {
657 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
664 * @param string $message
665 * @param array $params
668 * @throws \Civi\Payment\Exception\PaymentProcessorException
670 public function cancelSubscription(&$message = '', $params = []) {
671 if ($this->isPayPalType($this::PAYPAL_PRO
) ||
$this->isPayPalType($this::PAYPAL_EXPRESS
)) {
673 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
675 $args['PROFILEID'] = $params['subscriptionId'] ??
NULL;
676 $args['ACTION'] = 'Cancel';
677 $args['NOTE'] = $params['reason'] ??
NULL;
679 $result = $this->invokeAPI($args);
681 $message = "{$result['ack']}: profileid={$result['profileid']}";
688 * Process incoming notification.
690 * @throws \CRM_Core_Exception
691 * @throws \CiviCRM_API3_Exception
693 public function handlePaymentNotification() {
694 $params = array_merge($_GET, $_REQUEST);
695 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
696 $lastParam = array_pop($q);
697 if (is_numeric($lastParam)) {
698 $params['processor_id'] = $lastParam;
700 $result = civicrm_api3('PaymentProcessor', 'get', [
702 'id' => $params['processor_id'],
703 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
705 if (!$result['count']) {
706 throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
709 $paymentProcessorType = $result['values'][0]['api.PaymentProcessorType.getvalue'] ??
NULL;
710 switch ($paymentProcessorType) {
712 // "PayPal - Website Payments Pro"
713 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
716 case 'PayPal_Standard':
717 // "PayPal - Website Payments Standard"
718 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
722 // If we don't have PayPal Standard or PayPal Pro, something's wrong.
723 // Log an error and exit.
724 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.");
731 * @param string $message
732 * @param array $params
734 * @return array|bool|object
735 * @throws \Civi\Payment\Exception\PaymentProcessorException
737 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
738 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
739 $config = CRM_Core_Config
::singleton();
741 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
743 $args['PROFILEID'] = $params['subscriptionId'];
744 $args['AMT'] = $this->getAmount($params);
745 $args['CURRENCYCODE'] = $config->defaultCurrency
;
746 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
747 $args['ACCT'] = $params['credit_card_number'];
748 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
749 $args['CVV2'] = $params['cvv2'];
751 $args['FIRSTNAME'] = $params['first_name'];
752 $args['LASTNAME'] = $params['last_name'];
753 $args['STREET'] = $params['street_address'];
754 $args['CITY'] = $params['city'];
755 $args['STATE'] = $params['state_province'];
756 $args['COUNTRYCODE'] = $params['postal_code'];
757 $args['ZIP'] = $params['country'];
759 $result = $this->invokeAPI($args);
761 $message = "{$result['ack']}: profileid={$result['profileid']}";
768 * @param string $message
769 * @param array $params
772 * @throws \Civi\Payment\Exception\PaymentProcessorException
774 public function changeSubscriptionAmount(&$message = '', $params = []) {
775 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
776 $config = CRM_Core_Config
::singleton();
778 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
780 $args['PROFILEID'] = $params['subscriptionId'];
781 $args['AMT'] = $this->getAmount($params);
782 $args['CURRENCYCODE'] = $config->defaultCurrency
;
783 $args['BILLINGFREQUENCY'] = $params['installments'];
785 $result = $this->invokeAPI($args);
786 CRM_Core_Error
::debug_var('$result', $result);
788 $message = "{$result['ack']}: profileid={$result['profileid']}";
795 * Function to action pre-approval if supported
797 * @param array $params
798 * Parameters from the form
801 * - pre_approval_parameters (this will be stored on the calling form & available later)
802 * - redirect_url (if set the browser will be redirected to this.
803 * @throws \Civi\Payment\Exception\PaymentProcessorException
805 public function doPreApproval(&$params) {
806 if (!$this->isPaypalExpress($params)) {
809 $this->_component
= $params['component'];
810 $token = $this->setExpressCheckOut($params);
812 'pre_approval_parameters' => ['token' => $token],
813 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
818 * @param array $params
819 * @param string $component
823 public function doTransferCheckout(&$params, $component = 'contribute') {
825 $notifyParameters = ['module' => $component];
826 $notifyParameterMap = [
827 'contactID' => 'contactID',
828 'contributionID' => 'contributionID',
829 'eventID' => 'eventID',
830 'participantID' => 'participantID',
831 'membershipID' => 'membershipID',
832 'related_contact' => 'relatedContactID',
833 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
834 'accountingCode' => 'accountingCode',
835 'contributionRecurID' => 'contributionRecurID',
836 'contributionPageID' => 'contributionPageID',
838 foreach ($notifyParameterMap as $paramsName => $notifyName) {
839 if (!empty($params[$paramsName])) {
840 $notifyParameters[$notifyName] = $params[$paramsName];
843 $notifyURL = $this->getNotifyUrl();
845 $config = CRM_Core_Config
::singleton();
846 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
847 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
849 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
850 if (!empty($params['is_recur'])) {
851 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
854 $cancelURL = CRM_Utils_System
::url(
861 'business' => $this->_paymentProcessor
['user_name'],
862 'notify_url' => $notifyURL,
863 'item_name' => $this->getPaymentDescription($params, 127),
865 'undefined_quantity' => 0,
866 'cancel_return' => $cancelURL,
869 'return' => $this->getReturnSuccessUrl($params['qfKey']),
871 'currency_code' => $params['currencyID'],
872 'invoice' => $params['invoiceID'],
873 'lc' => substr($config->lcMessages
, -2),
874 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
875 'custom' => json_encode($notifyParameters),
876 'bn' => 'CiviCRM_SP',
879 // add name and address if available, CRM-3130
881 'first_name' => 'first_name',
882 'last_name' => 'last_name',
883 'street_address' => 'address1',
884 'country' => 'country',
885 'preferred_language' => 'lc',
887 'state_province' => 'state',
888 'postal_code' => 'zip',
892 foreach (array_keys($params) as $p) {
893 // get the base name without the location type suffixed to it
894 $parts = explode('-', $p);
895 $name = count($parts) > 1 ?
$parts[0] : $p;
896 if (isset($otherVars[$name])) {
897 $value = $params[$p];
899 if ($name == 'state_province') {
900 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
903 if ($name == 'country') {
904 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
905 $value = $countryName;
907 // ensure value is not an array
909 if (!is_array($value)) {
910 $paypalParams[$otherVars[$name]] = $value;
916 // if recurring donations, add a few more items
917 if (!empty($params['is_recur'])) {
918 if (!$params['contributionRecurID']) {
919 throw new CRM_Core_Exception(ts('Recurring contribution, but no database id'));
923 'cmd' => '_xclick-subscriptions',
924 'a3' => $this->getAmount($params),
925 'p3' => $params['frequency_interval'],
926 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
929 'srt' => $params['installments'] ??
NULL,
937 'amount' => $params['amount'],
941 // Allow further manipulation of the arguments via custom hooks ..
942 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
945 foreach ($paypalParams as $key => $value) {
946 if ($value === NULL) {
950 $value = urlencode($value);
951 if ($key == 'return' ||
952 $key == 'cancel_return' ||
955 $value = str_replace('%2F', '/', $value);
957 $uri .= "&{$key}={$value}";
960 $uri = substr($uri, 1);
961 $url = $this->_paymentProcessor
['url_site'];
962 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
963 $paypalURL = "{$url}{$sub}?$uri";
965 CRM_Utils_System
::redirect($paypalURL);
969 * Hash_call: Function to perform the API call to PayPal using API signature.
971 * @methodName is name of API method.
972 * @nvpStr is nvp string.
973 * returns an associative array containing the response from the server.
977 * @return array|object
978 * @throws \Civi\Payment\Exception\PaymentProcessorException
980 public function invokeAPI($args) {
982 if (empty($this->_paymentProcessor
['url_api'])) {
983 throw new PaymentProcessorException(ts('Please set the API URL. Please refer to the documentation for more details'));
986 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
989 foreach ($args as $n => $v) {
990 $p[] = "$n=" . urlencode($v);
993 //NVPRequest for submitting to server
994 $nvpreq = implode('&', $p);
996 if (!function_exists('curl_init')) {
997 throw new PaymentProcessorException('curl functions NOT available.');
1000 //setting the curl parameters.
1002 curl_setopt($ch, CURLOPT_URL
, $url);
1003 curl_setopt($ch, CURLOPT_VERBOSE
, 0);
1005 //turning off the server and peer verification(TrustManager Concept).
1006 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
1007 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, Civi
::settings()->get('verifySSL') ?
2 : 0);
1009 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
1010 curl_setopt($ch, CURLOPT_POST
, 1);
1012 //setting the nvpreq as POST FIELD to curl
1013 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
1015 //getting response from server
1016 $response = curl_exec($ch);
1018 //converting NVPResponse to an Associative Array
1019 $result = self
::deformat($response);
1021 if (curl_errno($ch)) {
1022 throw new PaymentProcessorException(ts('Network error') . ' ' . curl_error($ch) . curl_errno($ch), curl_errno($ch));
1026 $outcome = strtolower(CRM_Utils_Array
::value('ack', $result));
1028 if ($outcome != 'success' && $outcome != 'successwithwarning') {
1029 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1036 * This function will take NVPString and convert it to an Associative Array.
1038 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1040 * @param string $str
1044 public static function deformat($str) {
1047 while (strlen($str)) {
1049 $keyPos = strpos($str, '=');
1051 // position of value
1052 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1054 /*getting the Key and Value values and storing in a Associative Array*/
1056 $key = substr($str, 0, $keyPos);
1057 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1059 //decoding the respose
1060 $result[strtolower(urldecode($key))] = urldecode($val);
1061 $str = substr($str, $valPos +
1, strlen($str));
1068 * Get array of fields that should be displayed on the payment form.
1071 * @throws \Civi\Payment\Exception\PaymentProcessorException
1073 public function getPaymentFormFields() {
1074 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
1075 return $this->getCreditCardFormFields();
1083 * Map the paypal params to CiviCRM params using a field map.
1085 * @param array $fieldMap
1086 * @param array $paypalParams
1090 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1092 foreach ($fieldMap as $civicrmField => $paypalField) {
1093 $params[$civicrmField] = $paypalParams[$paypalField] ??
NULL;
1099 * Is this being processed by payment express.
1101 * Either because it is payment express or because is pro with paypal express in use.
1103 * @param array $params
1106 * @throws \Civi\Payment\Exception\PaymentProcessorException
1108 protected function isPaypalExpress($params) {
1109 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
1113 // This would occur postProcess.
1114 if (!empty($params['token'])) {
1117 if (isset($params['button']) && stristr($params['button'], 'express')) {
1121 // The contribution form passes a 'button' but the event form might still set one of these fields.
1122 // @todo more standardisation & get paypal fully out of the form layer.
1123 $possibleExpressFields = [
1124 '_qf_Register_upload_express_x',
1125 '_qf_Payment_upload_express_x',
1127 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {