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
);
163 $form->add('xbutton', $form->_expressButtonName
, ts('Pay using PayPal'), [
165 'formnovalidate' => 'formnovalidate',
166 'class' => 'crm-form-submit',
168 CRM_Core_Resources
::singleton()->addStyle('
169 button#' . $form->_expressButtonName
. '{
170 background-image: url(' . $this->_paymentProcessor
['url_button'] . ');
172 background-repeat: no-repeat;
173 background-color: transparent;
174 background-position: center;
183 * Can recurring contributions be set against pledges.
185 * In practice all processors that use the baseIPN function to finish transactions or
186 * call the completetransaction api support this by looking up previous contributions in the
187 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
188 * adding the new payment to the pledge.
190 * However, only enabling for processors it has been tested against.
194 protected function supportsRecurContributionsForPledges() {
199 * Default payment instrument validation.
201 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
202 * Not a static function, because I need to check for payment_type.
204 * @param array $values
205 * @param array $errors
207 * @throws \Civi\Payment\Exception\PaymentProcessorException
209 public function validatePaymentInstrument($values, &$errors) {
210 if ($this->isPayPalType($this::PAYPAL_PRO
) && !$this->isPaypalExpress($values)) {
211 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
212 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
217 * Express checkout code.
219 * Check PayPal documentation for more information
221 * @param array $params
222 * Assoc array of input parameters for this transaction.
225 * the result in an nice formatted array (or an error object)
226 * @throws \Civi\Payment\Exception\PaymentProcessorException
228 protected function setExpressCheckOut(&$params) {
231 $this->initialize($args, 'SetExpressCheckout');
233 $args['paymentAction'] = 'Sale';
234 $args['amt'] = $params['amount'];
235 $args['currencyCode'] = $params['currencyID'];
236 $args['desc'] = $params['description'] ??
NULL;
237 $args['invnum'] = $params['invoiceID'];
238 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
239 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
240 $args['version'] = '56.0';
241 $args['SOLUTIONTYPE'] = 'Sole';
243 //LCD if recurring, collect additional data and set some values
244 if (!empty($params['is_recur'])) {
245 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
246 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
247 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
248 $args['L_PAYMENTTYPE0'] = 'Any';
251 // Allow further manipulation of the arguments via custom hooks ..
252 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
254 $result = $this->invokeAPI($args);
258 return $result['token'];
262 * Get any details that may be available to the payment processor due to an approval process having happened.
264 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
267 * @param array $storedDetails
270 * @throws \Civi\Payment\Exception\PaymentProcessorException
272 public function getPreApprovalDetails($storedDetails) {
273 return empty($storedDetails['token']) ?
[] : $this->getExpressCheckoutDetails($storedDetails['token']);
277 * Get details from paypal.
279 * Check PayPal documentation for more information
281 * @param string $token
282 * The key associated with this transaction.
285 * the result in an nice formatted array (or an error object)
286 * @throws \Civi\Payment\Exception\PaymentProcessorException
288 public function getExpressCheckoutDetails($token) {
291 $this->initialize($args, 'GetExpressCheckoutDetails');
292 $args['token'] = $token;
294 $args['method'] = 'GetExpressCheckoutDetails';
296 $result = $this->invokeAPI($args);
301 'payer_status' => 'payerstatus',
302 'payer_id' => 'payerid',
303 'billing_first_name' => 'firstname',
304 'billing_middle_name' => 'middlename',
305 'billing_last_name' => 'lastname',
306 'street_address' => 'shiptostreet',
307 'supplemental_address_1' => 'shiptostreet2',
308 'city' => 'shiptocity',
309 'postal_code' => 'shiptozip',
310 'state_province' => 'shiptostate',
311 'country' => 'shiptocountrycode',
313 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
317 * Do the express checkout at paypal.
319 * Check PayPal documentation for more information
321 * @param array $params
324 * The result in an nice formatted array.
326 * @throws \Civi\Payment\Exception\PaymentProcessorException
328 public function doExpressCheckout(&$params) {
329 if (!empty($params['is_recur'])) {
330 return $this->createRecurringPayments($params);
334 $this->initialize($args, 'DoExpressCheckoutPayment');
335 $args['token'] = $params['token'];
336 $args['paymentAction'] = 'Sale';
337 $args['amt'] = $params['amount'];
338 $args['currencyCode'] = $params['currencyID'];
339 $args['payerID'] = $params['payer_id'];
340 $args['invnum'] = $params['invoiceID'];
341 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
342 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
343 $args['desc'] = $params['description'];
345 // add CiviCRM BN code
346 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
348 $result = $this->invokeAPI($args);
351 $params['trxn_id'] = $result['transactionid'];
352 $params['fee_amount'] = $result['feeamt'];
353 $params['net_amount'] = $result['settleamt'] ??
NULL;
354 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
355 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
357 $params['payment_status'] = $result['paymentstatus'];
358 $params['pending_reason'] = $result['pendingreason'];
359 if (!empty($params['is_recur'])) {
360 // See comment block.
361 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
364 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
370 * Create recurring payments.
372 * Use a pre-authorisation token to activate a recurring payment profile
373 * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
375 * @param array $params
380 public function createRecurringPayments(&$params) {
382 $this->initialize($args, 'CreateRecurringPaymentsProfile');
384 $start_time = strtotime(date('m/d/Y'));
385 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
387 $args['token'] = $params['token'];
388 $args['paymentAction'] = 'Sale';
389 $args['amt'] = $params['amount'];
390 $args['currencyCode'] = $params['currencyID'];
391 $args['payerID'] = $params['payer_id'];
392 $args['invnum'] = $params['invoiceID'];
393 $args['profilestartdate'] = $start_date;
394 $args['method'] = 'CreateRecurringPaymentsProfile';
395 $args['billingfrequency'] = $params['frequency_interval'];
396 $args['billingperiod'] = ucwords($params['frequency_unit']);
397 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
398 $args['totalbillingcycles'] = $params['installments'] ??
NULL;
399 $args['version'] = '56.0';
400 $args['profilereference'] = "i={$params['invoiceID']}" .
402 "&c={$params['contactID']}" .
403 "&r={$params['contributionRecurID']}" .
404 "&b={$params['contributionID']}" .
405 "&p={$params['contributionPageID']}";
407 // add CiviCRM BN code
408 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
410 $result = $this->invokeAPI($args);
412 /* Success - result looks like"
414 * 'profileid' => 'I-CP1U0PLG91R2',
415 * 'profilestatus' => 'ActiveProfile',
416 * 'timestamp' => '2018-05-07T03:55:52Z',
417 * 'correlationid' => 'e717999e9bf62',
418 * 'ack' => 'Success',
419 * 'version' => '56.0',
420 * 'build' => '39949200',)
422 $params['trxn_id'] = $result['profileid'];
423 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
434 public function initialize(&$args, $method) {
435 $args['user'] = $this->_paymentProcessor
['user_name'];
436 $args['pwd'] = $this->_paymentProcessor
['password'];
437 $args['version'] = 3.0;
438 $args['signature'] = $this->_paymentProcessor
['signature'];
439 $args['subject'] = $this->_paymentProcessor
['subject'] ??
NULL;
440 $args['method'] = $method;
444 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
446 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
449 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
450 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
451 * doTransferCheckout would not traditionally come back.
453 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
456 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
457 * return Error objects
459 * @param array $params
461 * @param string $component
466 * @throws \Civi\Payment\Exception\PaymentProcessorException
468 public function doPayment(&$params, $component = 'contribute') {
469 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
($this->isPayPalType($this::PAYPAL_PRO
) && !empty($params['token']))) {
470 $this->_component
= $component;
471 return $this->doExpressCheckout($params);
474 return parent
::doPayment($params, $component);
478 * This function collects all the information from a web/api form and invokes
479 * the relevant payment processor specific functions to perform the transaction
481 * @param array $params
482 * Assoc array of input parameters for this transaction.
484 * @param string $component
486 * the result in an nice formatted array (or an error object)
487 * @throws \Civi\Payment\Exception\PaymentProcessorException
489 public function doDirectPayment(&$params, $component = 'contribute') {
492 $this->initialize($args, 'DoDirectPayment');
494 $args['paymentAction'] = 'Sale';
495 $args['amt'] = $this->getAmount($params);
496 $args['currencyCode'] = $this->getCurrency($params);
497 $args['invnum'] = $params['invoiceID'];
498 $args['ipaddress'] = $params['ip_address'];
499 $args['creditCardType'] = $params['credit_card_type'];
500 $args['acct'] = $params['credit_card_number'];
501 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
502 $args['cvv2'] = $params['cvv2'];
503 $args['firstName'] = $params['first_name'];
504 $args['lastName'] = $params['last_name'];
505 $args['email'] = $params['email'] ??
NULL;
506 $args['street'] = $params['street_address'];
507 $args['city'] = $params['city'];
508 $args['state'] = $params['state_province'];
509 $args['countryCode'] = $params['country'];
510 $args['zip'] = $params['postal_code'];
511 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
512 $args['custom'] = $params['accountingCode'] ??
NULL;
514 // add CiviCRM BN code
515 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
517 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
518 $start_time = strtotime(date('m/d/Y'));
519 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
521 $args['PaymentAction'] = 'Sale';
522 $args['billingperiod'] = ucwords($params['frequency_unit']);
523 $args['billingfrequency'] = $params['frequency_interval'];
524 $args['method'] = "CreateRecurringPaymentsProfile";
525 $args['profilestartdate'] = $start_date;
527 $params['description'] . ": " .
528 $params['amount'] . " Per " .
529 $params['frequency_interval'] . " " .
530 $params['frequency_unit'];
531 $args['amt'] = $this->getAmount($params);
532 $args['totalbillingcycles'] = $params['installments'] ??
NULL;
533 $args['version'] = 56.0;
534 $args['PROFILEREFERENCE'] = "" .
535 "i=" . $params['invoiceID'] . "&m=" . $component .
536 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
537 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
540 // Allow further manipulation of the arguments via custom hooks ..
541 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
543 $result = $this->invokeAPI($args);
545 $params['recurr_profile_id'] = NULL;
547 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
548 $params['recurr_profile_id'] = $result['profileid'];
553 $params['trxn_id'] = $result['transactionid'] ??
NULL;
554 $params['gross_amount'] = $result['amt'] ??
NULL;
555 $params = array_merge($params, $this->doQuery($params));
560 * Query payment processor for details about a transaction.
562 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
564 * @param array $params
565 * Array of parameters containing one of:
566 * - trxn_id Id of an individual transaction.
567 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
570 * Extra parameters retrieved.
571 * Any parameters retrievable through this should be documented in the function comments at
572 * CRM_Core_Payment::doQuery. Currently
573 * - fee_amount Amount of fee paid
575 * @throws \Civi\Payment\Exception\PaymentProcessorException
577 public function doQuery($params) {
578 //CRM-18140 - trxn_id not returned for recurring paypal transaction
579 if (!empty($params['is_recur'])) {
582 elseif (empty($params['trxn_id'])) {
583 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
586 'TRANSACTIONID' => $params['trxn_id'],
588 $this->initialize($args, 'GetTransactionDetails');
589 $result = $this->invokeAPI($args);
591 'fee_amount' => $result['feeamt'],
592 'net_amount' => $params['gross_amount'] - $result['feeamt'],
597 * This function checks to see if we have the right config values.
599 * @return null|string
600 * the error message if any
601 * @throws \Civi\Payment\Exception\PaymentProcessorException
603 public function checkConfig() {
606 if (!$this->isPayPalType($this::PAYPAL_STANDARD
)) {
607 if (empty($this->_paymentProcessor
['signature'])) {
608 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
611 if (empty($this->_paymentProcessor
['password'])) {
612 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
615 if (empty($this->_paymentProcessor
['user_name'])) {
616 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
619 if (!empty($error)) {
620 return implode('<p>', $error);
628 * @return null|string
629 * @throws \Civi\Payment\Exception\PaymentProcessorException
631 public function cancelSubscriptionURL() {
632 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
633 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
641 * Check whether a method is present ( & supported ) by the payment processor object.
643 * @param string $method
644 * Method to check for.
647 * @throws \Civi\Payment\Exception\PaymentProcessorException
649 public function isSupported($method) {
650 if (!$this->isPayPalType($this::PAYPAL_PRO
)) {
651 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
652 // by standard or express.
655 return parent
::isSupported($method);
659 * Paypal express replaces the submit button with it's own.
662 * Should the form button by suppressed?
663 * @throws \Civi\Payment\Exception\PaymentProcessorException
665 public function isSuppressSubmitButtons() {
666 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
673 * @param string $message
674 * @param array $params
677 * @throws \Civi\Payment\Exception\PaymentProcessorException
679 public function cancelSubscription(&$message = '', $params = []) {
680 if ($this->isPayPalType($this::PAYPAL_PRO
) ||
$this->isPayPalType($this::PAYPAL_EXPRESS
)) {
682 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
684 $args['PROFILEID'] = $params['subscriptionId'] ??
NULL;
685 $args['ACTION'] = 'Cancel';
686 $args['NOTE'] = $params['reason'] ??
NULL;
688 $result = $this->invokeAPI($args);
690 $message = "{$result['ack']}: profileid={$result['profileid']}";
697 * Process incoming notification.
699 * @throws \CRM_Core_Exception
700 * @throws \CiviCRM_API3_Exception
702 public function handlePaymentNotification() {
703 $params = array_merge($_GET, $_REQUEST);
704 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
705 $lastParam = array_pop($q);
706 if (is_numeric($lastParam)) {
707 $params['processor_id'] = $lastParam;
709 $result = civicrm_api3('PaymentProcessor', 'get', [
711 'id' => $params['processor_id'],
712 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
714 if (!$result['count']) {
715 throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
718 $paymentProcessorType = $result['values'][0]['api.PaymentProcessorType.getvalue'] ??
NULL;
719 switch ($paymentProcessorType) {
721 // "PayPal - Website Payments Pro"
722 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
725 case 'PayPal_Standard':
726 // "PayPal - Website Payments Standard"
727 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
731 // If we don't have PayPal Standard or PayPal Pro, something's wrong.
732 // Log an error and exit.
733 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.");
740 * @param string $message
741 * @param array $params
743 * @return array|bool|object
744 * @throws \Civi\Payment\Exception\PaymentProcessorException
746 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
747 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
748 $config = CRM_Core_Config
::singleton();
750 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
752 $args['PROFILEID'] = $params['subscriptionId'];
753 $args['AMT'] = $this->getAmount($params);
754 $args['CURRENCYCODE'] = $config->defaultCurrency
;
755 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
756 $args['ACCT'] = $params['credit_card_number'];
757 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
758 $args['CVV2'] = $params['cvv2'];
760 $args['FIRSTNAME'] = $params['first_name'];
761 $args['LASTNAME'] = $params['last_name'];
762 $args['STREET'] = $params['street_address'];
763 $args['CITY'] = $params['city'];
764 $args['STATE'] = $params['state_province'];
765 $args['COUNTRYCODE'] = $params['postal_code'];
766 $args['ZIP'] = $params['country'];
768 $result = $this->invokeAPI($args);
770 $message = "{$result['ack']}: profileid={$result['profileid']}";
777 * @param string $message
778 * @param array $params
781 * @throws \Civi\Payment\Exception\PaymentProcessorException
783 public function changeSubscriptionAmount(&$message = '', $params = []) {
784 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
785 $config = CRM_Core_Config
::singleton();
787 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
789 $args['PROFILEID'] = $params['subscriptionId'];
790 $args['AMT'] = $this->getAmount($params);
791 $args['CURRENCYCODE'] = $config->defaultCurrency
;
792 $args['BILLINGFREQUENCY'] = $params['installments'];
794 $result = $this->invokeAPI($args);
795 CRM_Core_Error
::debug_var('$result', $result);
797 $message = "{$result['ack']}: profileid={$result['profileid']}";
804 * Function to action pre-approval if supported
806 * @param array $params
807 * Parameters from the form
810 * - pre_approval_parameters (this will be stored on the calling form & available later)
811 * - redirect_url (if set the browser will be redirected to this.
812 * @throws \Civi\Payment\Exception\PaymentProcessorException
814 public function doPreApproval(&$params) {
815 if (!$this->isPaypalExpress($params)) {
818 $this->_component
= $params['component'];
819 $token = $this->setExpressCheckOut($params);
821 'pre_approval_parameters' => ['token' => $token],
822 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
827 * @param array $params
828 * @param string $component
832 public function doTransferCheckout(&$params, $component = 'contribute') {
834 $notifyParameters = ['module' => $component];
835 $notifyParameterMap = [
836 'contactID' => 'contactID',
837 'contributionID' => 'contributionID',
838 'eventID' => 'eventID',
839 'participantID' => 'participantID',
840 'membershipID' => 'membershipID',
841 'related_contact' => 'relatedContactID',
842 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
843 'accountingCode' => 'accountingCode',
844 'contributionRecurID' => 'contributionRecurID',
845 'contributionPageID' => 'contributionPageID',
847 foreach ($notifyParameterMap as $paramsName => $notifyName) {
848 if (!empty($params[$paramsName])) {
849 $notifyParameters[$notifyName] = $params[$paramsName];
852 $notifyURL = $this->getNotifyUrl();
854 $config = CRM_Core_Config
::singleton();
855 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
856 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
858 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
859 if (!empty($params['is_recur'])) {
860 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
863 $cancelURL = CRM_Utils_System
::url(
870 'business' => $this->_paymentProcessor
['user_name'],
871 'notify_url' => $notifyURL,
872 'item_name' => $this->getPaymentDescription($params, 127),
874 'undefined_quantity' => 0,
875 'cancel_return' => $cancelURL,
878 'return' => $this->getReturnSuccessUrl($params['qfKey']),
880 'currency_code' => $params['currencyID'],
881 'invoice' => $params['invoiceID'],
882 'lc' => substr($config->lcMessages
, -2),
883 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
884 'custom' => json_encode($notifyParameters),
885 'bn' => 'CiviCRM_SP',
888 // add name and address if available, CRM-3130
890 'first_name' => 'first_name',
891 'last_name' => 'last_name',
892 'street_address' => 'address1',
893 'country' => 'country',
894 'preferred_language' => 'lc',
896 'state_province' => 'state',
897 'postal_code' => 'zip',
901 foreach (array_keys($params) as $p) {
902 // get the base name without the location type suffixed to it
903 $parts = explode('-', $p);
904 $name = count($parts) > 1 ?
$parts[0] : $p;
905 if (isset($otherVars[$name])) {
906 $value = $params[$p];
908 if ($name == 'state_province') {
909 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
912 if ($name == 'country') {
913 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
914 $value = $countryName;
916 // ensure value is not an array
918 if (!is_array($value)) {
919 $paypalParams[$otherVars[$name]] = $value;
925 // if recurring donations, add a few more items
926 if (!empty($params['is_recur'])) {
927 if (!$params['contributionRecurID']) {
928 throw new CRM_Core_Exception(ts('Recurring contribution, but no database id'));
932 'cmd' => '_xclick-subscriptions',
933 'a3' => $this->getAmount($params),
934 'p3' => $params['frequency_interval'],
935 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
938 'srt' => $params['installments'] ??
NULL,
946 'amount' => $params['amount'],
950 // Allow further manipulation of the arguments via custom hooks ..
951 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
954 foreach ($paypalParams as $key => $value) {
955 if ($value === NULL) {
959 $value = urlencode($value);
960 if ($key == 'return' ||
961 $key == 'cancel_return' ||
964 $value = str_replace('%2F', '/', $value);
966 $uri .= "&{$key}={$value}";
969 $uri = substr($uri, 1);
970 $url = $this->_paymentProcessor
['url_site'];
971 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
972 $paypalURL = "{$url}{$sub}?$uri";
974 // Allow each CMS to do a pre-flight check before redirecting to PayPal.
975 CRM_Core_Config
::singleton()->userSystem
->prePostRedirect();
977 CRM_Utils_System
::redirect($paypalURL);
981 * Hash_call: Function to perform the API call to PayPal using API signature.
983 * @methodName is name of API method.
984 * @nvpStr is nvp string.
985 * returns an associative array containing the response from the server.
989 * @return array|object
990 * @throws \Civi\Payment\Exception\PaymentProcessorException
992 public function invokeAPI($args) {
994 if (empty($this->_paymentProcessor
['url_api'])) {
995 throw new PaymentProcessorException(ts('Please set the API URL. Please refer to the documentation for more details'));
998 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
1001 foreach ($args as $n => $v) {
1002 $p[] = "$n=" . urlencode($v);
1005 //NVPRequest for submitting to server
1006 $nvpreq = implode('&', $p);
1008 if (!function_exists('curl_init')) {
1009 throw new PaymentProcessorException('curl functions NOT available.');
1012 //setting the curl parameters.
1014 curl_setopt($ch, CURLOPT_URL
, $url);
1015 curl_setopt($ch, CURLOPT_VERBOSE
, 0);
1017 //turning off the server and peer verification(TrustManager Concept).
1018 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
1019 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, Civi
::settings()->get('verifySSL') ?
2 : 0);
1021 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
1022 curl_setopt($ch, CURLOPT_POST
, 1);
1024 //setting the nvpreq as POST FIELD to curl
1025 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
1027 //getting response from server
1028 $response = curl_exec($ch);
1030 //converting NVPResponse to an Associative Array
1031 $result = self
::deformat($response);
1033 if (curl_errno($ch)) {
1034 throw new PaymentProcessorException(ts('Network error') . ' ' . curl_error($ch) . curl_errno($ch), curl_errno($ch));
1038 $outcome = strtolower(CRM_Utils_Array
::value('ack', $result));
1040 if ($outcome != 'success' && $outcome != 'successwithwarning') {
1041 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1048 * This function will take NVPString and convert it to an Associative Array.
1050 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1052 * @param string $str
1056 public static function deformat($str) {
1059 while (strlen($str)) {
1061 $keyPos = strpos($str, '=');
1063 // position of value
1064 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1066 /*getting the Key and Value values and storing in a Associative Array*/
1068 $key = substr($str, 0, $keyPos);
1069 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1071 //decoding the respose
1072 $result[strtolower(urldecode($key))] = urldecode($val);
1073 $str = substr($str, $valPos +
1, strlen($str));
1080 * Get array of fields that should be displayed on the payment form.
1083 * @throws \Civi\Payment\Exception\PaymentProcessorException
1085 public function getPaymentFormFields() {
1086 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
1087 return $this->getCreditCardFormFields();
1095 * Map the paypal params to CiviCRM params using a field map.
1097 * @param array $fieldMap
1098 * @param array $paypalParams
1102 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1104 foreach ($fieldMap as $civicrmField => $paypalField) {
1105 $params[$civicrmField] = $paypalParams[$paypalField] ??
NULL;
1111 * Is this being processed by payment express.
1113 * Either because it is payment express or because is pro with paypal express in use.
1115 * @param array $params
1118 * @throws \Civi\Payment\Exception\PaymentProcessorException
1120 protected function isPaypalExpress($params) {
1121 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
1124 // This would occur postProcess.
1125 if (!empty($params['token'])) {
1128 if (isset($params['button']) && stristr($params['button'], 'express')) {
1132 // The contribution form passes a 'button' but the event form might still set one of these fields.
1133 // @todo more standardisation & get paypal fully out of the form layer.
1134 $possibleExpressFields = [
1135 '_qf_Register_upload_express_x',
1136 '_qf_Payment_upload_express_x',
1137 '_qf_Main_upload_express',
1139 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {