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;
47 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
48 $this->_processorName
= ts('PayPal Standard');
50 elseif ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
51 $this->_processorName
= ts('PayPal Express');
53 elseif ($this->isPayPalType($this::PAYPAL_PRO
)) {
54 $this->_processorName
= ts('PayPal Pro');
57 throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
62 * Helper function to check which payment processor type is being used.
67 * @throws \Civi\Payment\Exception\PaymentProcessorException
69 public function isPayPalType($typeName) {
70 // Historically payment_processor_type may have been set to the name of the processor but newer versions of CiviCRM use the id set in payment_processor_type_id
71 if (empty($this->_paymentProcessor
['payment_processor_type_id']) && empty($this->_paymentProcessor
['payment_processor_type'])) {
72 // We need one of them to be set!
73 throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
75 if (empty($this->_paymentProcessor
['payment_processor_type_id']) && !empty($this->_paymentProcessor
['payment_processor_type'])) {
76 // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not.
77 $this->_paymentProcessor
['payment_processor_type_id']
78 = CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor
['payment_processor_type']);
80 if ((int) $this->_paymentProcessor
['payment_processor_type_id'] ===
81 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) {
88 * Are back office payments supported.
90 * E.g paypal standard won't permit you to enter a credit card associated
91 * with someone else's login.
94 * @throws \Civi\Payment\Exception\PaymentProcessorException
96 protected function supportsBackOffice() {
97 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
104 * Does this processor support pre-approval.
106 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
108 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
109 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
110 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
113 * @throws \Civi\Payment\Exception\PaymentProcessorException
115 protected function supportsPreApproval() {
116 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
$this->isPayPalType($this::PAYPAL_PRO
)) {
123 * Opportunity for the payment processor to override the entire form build.
125 * @param CRM_Core_Form $form
128 * Should form building stop at this point?
129 * @throws \Civi\Payment\Exception\PaymentProcessorException
131 public function buildForm(&$form) {
132 if ($this->supportsPreApproval()) {
133 $this->addPaypalExpressCode($form);
134 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
135 CRM_Core_Region
::instance('billing-block-post')->add([
136 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
137 'name' => 'paypal_express',
140 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
141 CRM_Core_Region
::instance('billing-block-pre')->add([
142 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
150 * Billing mode button is basically synonymous with paypal express.
152 * This is probably a good example of 'odds & sods' code we
153 * need to find a way for the payment processor to assign.
155 * A tricky aspect is that the payment processor may need to set the order
157 * @param CRM_Core_Form $form
159 protected function addPaypalExpressCode(&$form) {
160 // @todo use $this->isBackOffice() instead, test.
161 if (empty($form->isBackOffice
)) {
164 * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment',
165 * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name
166 * and then clicking on express button it redirect to confirm screen rather than PayPal Express form
169 if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName
) {
170 $form->_expressButtonName
= '_qf_' . $form->_formName
. '_upload_express';
173 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
175 $form->assign('expressButtonName', $form->_expressButtonName
);
178 $form->_expressButtonName
,
179 $this->_paymentProcessor
['url_button'],
180 ['class' => 'crm-form-submit']
186 * Can recurring contributions be set against pledges.
188 * In practice all processors that use the baseIPN function to finish transactions or
189 * call the completetransaction api support this by looking up previous contributions in the
190 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
191 * adding the new payment to the pledge.
193 * However, only enabling for processors it has been tested against.
197 protected function supportsRecurContributionsForPledges() {
202 * Default payment instrument validation.
204 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
205 * Not a static function, because I need to check for payment_type.
207 * @param array $values
208 * @param array $errors
210 * @throws \Civi\Payment\Exception\PaymentProcessorException
212 public function validatePaymentInstrument($values, &$errors) {
213 if ($this->isPayPalType($this::PAYPAL_PRO
) && !$this->isPaypalExpress($values)) {
214 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
215 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
220 * Express checkout code.
222 * Check PayPal documentation for more information
224 * @param array $params
225 * Assoc array of input parameters for this transaction.
228 * the result in an nice formatted array (or an error object)
229 * @throws \Civi\Payment\Exception\PaymentProcessorException
231 protected function setExpressCheckOut(&$params) {
234 $this->initialize($args, 'SetExpressCheckout');
236 $args['paymentAction'] = 'Sale';
237 $args['amt'] = $params['amount'];
238 $args['currencyCode'] = $params['currencyID'];
239 $args['desc'] = CRM_Utils_Array
::value('description', $params);
240 $args['invnum'] = $params['invoiceID'];
241 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
242 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
243 $args['version'] = '56.0';
244 $args['SOLUTIONTYPE'] = 'Sole';
246 //LCD if recurring, collect additional data and set some values
247 if (!empty($params['is_recur'])) {
248 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
249 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
250 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
251 $args['L_PAYMENTTYPE0'] = 'Any';
254 // Allow further manipulation of the arguments via custom hooks ..
255 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
257 $result = $this->invokeAPI($args);
261 return $result['token'];
265 * Get any details that may be available to the payment processor due to an approval process having happened.
267 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
270 * @param array $storedDetails
273 * @throws \Civi\Payment\Exception\PaymentProcessorException
275 public function getPreApprovalDetails($storedDetails) {
276 return empty($storedDetails['token']) ?
[] : $this->getExpressCheckoutDetails($storedDetails['token']);
280 * Get details from paypal.
282 * Check PayPal documentation for more information
284 * @param string $token
285 * The key associated with this transaction.
288 * the result in an nice formatted array (or an error object)
289 * @throws \Civi\Payment\Exception\PaymentProcessorException
291 public function getExpressCheckoutDetails($token) {
294 $this->initialize($args, 'GetExpressCheckoutDetails');
295 $args['token'] = $token;
297 $args['method'] = 'GetExpressCheckoutDetails';
299 $result = $this->invokeAPI($args);
304 'payer_status' => 'payerstatus',
305 'payer_id' => 'payerid',
306 'first_name' => 'firstname',
307 'middle_name' => 'middlename',
308 'last_name' => 'lastname',
309 'street_address' => 'shiptostreet',
310 'supplemental_address_1' => 'shiptostreet2',
311 'city' => 'shiptocity',
312 'postal_code' => 'shiptozip',
313 'state_province' => 'shiptostate',
314 'country' => 'shiptocountrycode',
316 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
320 * Do the express checkout at paypal.
322 * Check PayPal documentation for more information
324 * @param array $params
327 * The result in an nice formatted array.
329 * @throws \Civi\Payment\Exception\PaymentProcessorException
331 public function doExpressCheckout(&$params) {
332 if (!empty($params['is_recur'])) {
333 return $this->createRecurringPayments($params);
337 $this->initialize($args, 'DoExpressCheckoutPayment');
338 $args['token'] = $params['token'];
339 $args['paymentAction'] = 'Sale';
340 $args['amt'] = $params['amount'];
341 $args['currencyCode'] = $params['currencyID'];
342 $args['payerID'] = $params['payer_id'];
343 $args['invnum'] = $params['invoiceID'];
344 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
345 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
346 $args['desc'] = $params['description'];
348 // add CiviCRM BN code
349 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
351 $result = $this->invokeAPI($args);
354 $params['trxn_id'] = $result['transactionid'];
355 $params['gross_amount'] = $result['amt'];
356 $params['fee_amount'] = $result['feeamt'];
357 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
358 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
359 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
361 $params['payment_status'] = $result['paymentstatus'];
362 $params['pending_reason'] = $result['pendingreason'];
363 if (!empty($params['is_recur'])) {
364 // See comment block.
365 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
368 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
374 * Create recurring payments.
376 * Use a pre-authorisation token to activate a recurring payment profile
377 * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
379 * @param array $params
384 public function createRecurringPayments(&$params) {
386 $this->initialize($args, 'CreateRecurringPaymentsProfile');
388 $start_time = strtotime(date('m/d/Y'));
389 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
391 $args['token'] = $params['token'];
392 $args['paymentAction'] = 'Sale';
393 $args['amt'] = $params['amount'];
394 $args['currencyCode'] = $params['currencyID'];
395 $args['payerID'] = $params['payer_id'];
396 $args['invnum'] = $params['invoiceID'];
397 $args['profilestartdate'] = $start_date;
398 $args['method'] = 'CreateRecurringPaymentsProfile';
399 $args['billingfrequency'] = $params['frequency_interval'];
400 $args['billingperiod'] = ucwords($params['frequency_unit']);
401 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
402 $args['totalbillingcycles'] = CRM_Utils_Array
::value('installments', $params);
403 $args['version'] = '56.0';
404 $args['profilereference'] = "i={$params['invoiceID']}" .
406 "&c={$params['contactID']}" .
407 "&r={$params['contributionRecurID']}" .
408 "&b={$params['contributionID']}" .
409 "&p={$params['contributionPageID']}";
411 // add CiviCRM BN code
412 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
414 $result = $this->invokeAPI($args);
416 /* Success - result looks like"
418 * 'profileid' => 'I-CP1U0PLG91R2',
419 * 'profilestatus' => 'ActiveProfile',
420 * 'timestamp' => '2018-05-07T03:55:52Z',
421 * 'correlationid' => 'e717999e9bf62',
422 * 'ack' => 'Success',
423 * 'version' => '56.0',
424 * 'build' => '39949200',)
426 $params['trxn_id'] = $result['profileid'];
427 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
438 public function initialize(&$args, $method) {
439 $args['user'] = $this->_paymentProcessor
['user_name'];
440 $args['pwd'] = $this->_paymentProcessor
['password'];
441 $args['version'] = 3.0;
442 $args['signature'] = $this->_paymentProcessor
['signature'];
443 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
444 $args['method'] = $method;
448 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
450 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
453 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
454 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
455 * doTransferCheckout would not traditionally come back.
457 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
460 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
461 * return Error objects
463 * @param array $params
465 * @param string $component
470 * @throws \Civi\Payment\Exception\PaymentProcessorException
472 public function doPayment(&$params, $component = 'contribute') {
473 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
($this->isPayPalType($this::PAYPAL_PRO
) && !empty($params['token']))) {
474 $this->_component
= $component;
475 return $this->doExpressCheckout($params);
478 return parent
::doPayment($params, $component);
482 * This function collects all the information from a web/api form and invokes
483 * the relevant payment processor specific functions to perform the transaction
485 * @param array $params
486 * Assoc array of input parameters for this transaction.
488 * @param string $component
490 * the result in an nice formatted array (or an error object)
491 * @throws \Civi\Payment\Exception\PaymentProcessorException
493 public function doDirectPayment(&$params, $component = 'contribute') {
496 $this->initialize($args, 'DoDirectPayment');
498 $args['paymentAction'] = 'Sale';
499 $args['amt'] = $this->getAmount($params);
500 $args['currencyCode'] = $this->getCurrency($params);
501 $args['invnum'] = $params['invoiceID'];
502 $args['ipaddress'] = $params['ip_address'];
503 $args['creditCardType'] = $params['credit_card_type'];
504 $args['acct'] = $params['credit_card_number'];
505 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
506 $args['cvv2'] = $params['cvv2'];
507 $args['firstName'] = $params['first_name'];
508 $args['lastName'] = $params['last_name'];
509 $args['email'] = CRM_Utils_Array
::value('email', $params);
510 $args['street'] = $params['street_address'];
511 $args['city'] = $params['city'];
512 $args['state'] = $params['state_province'];
513 $args['countryCode'] = $params['country'];
514 $args['zip'] = $params['postal_code'];
515 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
516 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
518 // add CiviCRM BN code
519 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
521 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
522 $start_time = strtotime(date('m/d/Y'));
523 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
525 $args['PaymentAction'] = 'Sale';
526 $args['billingperiod'] = ucwords($params['frequency_unit']);
527 $args['billingfrequency'] = $params['frequency_interval'];
528 $args['method'] = "CreateRecurringPaymentsProfile";
529 $args['profilestartdate'] = $start_date;
531 $params['description'] . ": " .
532 $params['amount'] . " Per " .
533 $params['frequency_interval'] . " " .
534 $params['frequency_unit'];
535 $args['amt'] = $this->getAmount($params);
536 $args['totalbillingcycles'] = CRM_Utils_Array
::value('installments', $params);
537 $args['version'] = 56.0;
538 $args['PROFILEREFERENCE'] = "" .
539 "i=" . $params['invoiceID'] . "&m=" . $component .
540 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
541 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
544 // Allow further manipulation of the arguments via custom hooks ..
545 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
547 $result = $this->invokeAPI($args);
549 $params['recurr_profile_id'] = NULL;
551 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
552 $params['recurr_profile_id'] = $result['profileid'];
557 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
558 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
559 $params = array_merge($params, $this->doQuery($params));
564 * Query payment processor for details about a transaction.
566 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
568 * @param array $params
569 * Array of parameters containing one of:
570 * - trxn_id Id of an individual transaction.
571 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
574 * Extra parameters retrieved.
575 * Any parameters retrievable through this should be documented in the function comments at
576 * CRM_Core_Payment::doQuery. Currently
577 * - fee_amount Amount of fee paid
579 * @throws \Civi\Payment\Exception\PaymentProcessorException
581 public function doQuery($params) {
582 //CRM-18140 - trxn_id not returned for recurring paypal transaction
583 if (!empty($params['is_recur'])) {
586 elseif (empty($params['trxn_id'])) {
587 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
590 'TRANSACTIONID' => $params['trxn_id'],
592 $this->initialize($args, 'GetTransactionDetails');
593 $result = $this->invokeAPI($args);
595 'fee_amount' => $result['feeamt'],
596 'net_amount' => $params['gross_amount'] - $result['feeamt'],
601 * This function checks to see if we have the right config values.
603 * @return null|string
604 * the error message if any
605 * @throws \Civi\Payment\Exception\PaymentProcessorException
607 public function checkConfig() {
610 if (!$this->isPayPalType($this::PAYPAL_STANDARD
)) {
611 if (empty($this->_paymentProcessor
['signature'])) {
612 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
615 if (empty($this->_paymentProcessor
['password'])) {
616 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
619 if (empty($this->_paymentProcessor
['user_name'])) {
620 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
623 if (!empty($error)) {
624 return implode('<p>', $error);
632 * @return null|string
633 * @throws \Civi\Payment\Exception\PaymentProcessorException
635 public function cancelSubscriptionURL() {
636 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
637 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
645 * Check whether a method is present ( & supported ) by the payment processor object.
647 * @param string $method
648 * Method to check for.
651 * @throws \Civi\Payment\Exception\PaymentProcessorException
653 public function isSupported($method) {
654 if (!$this->isPayPalType($this::PAYPAL_PRO
)) {
655 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
656 // by standard or express.
659 return parent
::isSupported($method);
663 * Paypal express replaces the submit button with it's own.
666 * Should the form button by suppressed?
667 * @throws \Civi\Payment\Exception\PaymentProcessorException
669 public function isSuppressSubmitButtons() {
670 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
677 * @param string $message
678 * @param array $params
681 * @throws \Civi\Payment\Exception\PaymentProcessorException
683 public function cancelSubscription(&$message = '', $params = []) {
684 if ($this->isPayPalType($this::PAYPAL_PRO
) ||
$this->isPayPalType($this::PAYPAL_EXPRESS
)) {
686 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
688 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
689 $args['ACTION'] = 'Cancel';
690 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
692 $result = $this->invokeAPI($args);
694 $message = "{$result['ack']}: profileid={$result['profileid']}";
701 * Process incoming notification.
703 * @throws \CRM_Core_Exception
704 * @throws \CiviCRM_API3_Exception
706 public static function handlePaymentNotification() {
707 $params = array_merge($_GET, $_REQUEST);
708 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
709 $lastParam = array_pop($q);
710 if (is_numeric($lastParam)) {
711 $params['processor_id'] = $lastParam;
713 $result = civicrm_api3('PaymentProcessor', 'get', [
715 'id' => $params['processor_id'],
716 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
718 if (!$result['count']) {
719 throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
722 $paymentProcessorType = CRM_Utils_Array
::value('api.PaymentProcessorType.getvalue', $result['values'][0]);
723 switch ($paymentProcessorType) {
725 // "PayPal - Website Payments Pro"
726 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
729 case 'PayPal_Standard':
730 // "PayPal - Website Payments Standard"
731 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
735 // If we don't have PayPal Standard or PayPal Pro, something's wrong.
736 // Log an error and exit.
737 throw new CRM_Core_Exception("The processor_id value '{$params['processor_id']}' is for a processor of type '{$paymentProcessorType}', which is invalid in this context.");
744 * @param string $message
745 * @param array $params
747 * @return array|bool|object
748 * @throws \Civi\Payment\Exception\PaymentProcessorException
750 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
751 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
752 $config = CRM_Core_Config
::singleton();
754 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
756 $args['PROFILEID'] = $params['subscriptionId'];
757 $args['AMT'] = $this->getAmount($params);
758 $args['CURRENCYCODE'] = $config->defaultCurrency
;
759 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
760 $args['ACCT'] = $params['credit_card_number'];
761 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
762 $args['CVV2'] = $params['cvv2'];
764 $args['FIRSTNAME'] = $params['first_name'];
765 $args['LASTNAME'] = $params['last_name'];
766 $args['STREET'] = $params['street_address'];
767 $args['CITY'] = $params['city'];
768 $args['STATE'] = $params['state_province'];
769 $args['COUNTRYCODE'] = $params['postal_code'];
770 $args['ZIP'] = $params['country'];
772 $result = $this->invokeAPI($args);
774 $message = "{$result['ack']}: profileid={$result['profileid']}";
781 * @param string $message
782 * @param array $params
785 * @throws \Civi\Payment\Exception\PaymentProcessorException
787 public function changeSubscriptionAmount(&$message = '', $params = []) {
788 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
789 $config = CRM_Core_Config
::singleton();
791 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
793 $args['PROFILEID'] = $params['subscriptionId'];
794 $args['AMT'] = $this->getAmount($params);
795 $args['CURRENCYCODE'] = $config->defaultCurrency
;
796 $args['BILLINGFREQUENCY'] = $params['installments'];
798 $result = $this->invokeAPI($args);
799 CRM_Core_Error
::debug_var('$result', $result);
801 $message = "{$result['ack']}: profileid={$result['profileid']}";
808 * Function to action pre-approval if supported
810 * @param array $params
811 * Parameters from the form
814 * - pre_approval_parameters (this will be stored on the calling form & available later)
815 * - redirect_url (if set the browser will be redirected to this.
816 * @throws \Civi\Payment\Exception\PaymentProcessorException
818 public function doPreApproval(&$params) {
819 if (!$this->isPaypalExpress($params)) {
822 $this->_component
= $params['component'];
823 $token = $this->setExpressCheckOut($params);
825 'pre_approval_parameters' => ['token' => $token],
826 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
831 * @param array $params
832 * @param string $component
836 public function doTransferCheckout(&$params, $component = 'contribute') {
838 $notifyParameters = ['module' => $component];
839 $notifyParameterMap = [
840 'contactID' => 'contactID',
841 'contributionID' => 'contributionID',
842 'eventID' => 'eventID',
843 'participantID' => 'participantID',
844 'membershipID' => 'membershipID',
845 'related_contact' => 'relatedContactID',
846 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
847 'accountingCode' => 'accountingCode',
848 'contributionRecurID' => 'contributionRecurID',
849 'contributionPageID' => 'contributionPageID',
851 foreach ($notifyParameterMap as $paramsName => $notifyName) {
852 if (!empty($params[$paramsName])) {
853 $notifyParameters[$notifyName] = $params[$paramsName];
856 $notifyURL = $this->getNotifyUrl();
858 $config = CRM_Core_Config
::singleton();
859 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
860 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
862 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
863 if (!empty($params['is_recur'])) {
864 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
867 $cancelURL = CRM_Utils_System
::url(
874 'business' => $this->_paymentProcessor
['user_name'],
875 'notify_url' => $notifyURL,
876 'item_name' => $this->getPaymentDescription($params, 127),
878 'undefined_quantity' => 0,
879 'cancel_return' => $cancelURL,
882 'return' => $this->getReturnSuccessUrl($params['qfKey']),
884 'currency_code' => $params['currencyID'],
885 'invoice' => $params['invoiceID'],
886 'lc' => substr($config->lcMessages
, -2),
887 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
888 'custom' => json_encode($notifyParameters),
889 'bn' => 'CiviCRM_SP',
892 // add name and address if available, CRM-3130
894 'first_name' => 'first_name',
895 'last_name' => 'last_name',
896 'street_address' => 'address1',
897 'country' => 'country',
898 'preferred_language' => 'lc',
900 'state_province' => 'state',
901 'postal_code' => 'zip',
905 foreach (array_keys($params) as $p) {
906 // get the base name without the location type suffixed to it
907 $parts = explode('-', $p);
908 $name = count($parts) > 1 ?
$parts[0] : $p;
909 if (isset($otherVars[$name])) {
910 $value = $params[$p];
912 if ($name == 'state_province') {
913 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
916 if ($name == 'country') {
917 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
918 $value = $countryName;
920 // ensure value is not an array
922 if (!is_array($value)) {
923 $paypalParams[$otherVars[$name]] = $value;
929 // if recurring donations, add a few more items
930 if (!empty($params['is_recur'])) {
931 if (!$params['contributionRecurID']) {
932 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
936 'cmd' => '_xclick-subscriptions',
937 'a3' => $this->getAmount($params),
938 'p3' => $params['frequency_interval'],
939 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
942 'srt' => CRM_Utils_Array
::value('installments', $params),
950 'amount' => $params['amount'],
954 // Allow further manipulation of the arguments via custom hooks ..
955 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
958 foreach ($paypalParams as $key => $value) {
959 if ($value === NULL) {
963 $value = urlencode($value);
964 if ($key == 'return' ||
965 $key == 'cancel_return' ||
968 $value = str_replace('%2F', '/', $value);
970 $uri .= "&{$key}={$value}";
973 $uri = substr($uri, 1);
974 $url = $this->_paymentProcessor
['url_site'];
975 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
976 $paypalURL = "{$url}{$sub}?$uri";
978 CRM_Utils_System
::redirect($paypalURL);
982 * Hash_call: Function to perform the API call to PayPal using API signature.
984 * @methodName is name of API method.
985 * @nvpStr is nvp string.
986 * returns an associative array containing the response from the server.
990 * @return array|object
991 * @throws \Civi\Payment\Exception\PaymentProcessorException
993 public function invokeAPI($args) {
995 if (empty($this->_paymentProcessor
['url_api'])) {
996 throw new PaymentProcessorException(ts('Please set the API URL. Please refer to the documentation for more details'));
999 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
1002 foreach ($args as $n => $v) {
1003 $p[] = "$n=" . urlencode($v);
1006 //NVPRequest for submitting to server
1007 $nvpreq = implode('&', $p);
1009 if (!function_exists('curl_init')) {
1010 throw new PaymentProcessorException('curl functions NOT available.');
1013 //setting the curl parameters.
1015 curl_setopt($ch, CURLOPT_URL
, $url);
1016 curl_setopt($ch, CURLOPT_VERBOSE
, 0);
1018 //turning off the server and peer verification(TrustManager Concept).
1019 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
1020 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, Civi
::settings()->get('verifySSL') ?
2 : 0);
1022 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
1023 curl_setopt($ch, CURLOPT_POST
, 1);
1025 //setting the nvpreq as POST FIELD to curl
1026 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
1028 //getting response from server
1029 $response = curl_exec($ch);
1031 //converting NVPResponse to an Associative Array
1032 $result = self
::deformat($response);
1034 if (curl_errno($ch)) {
1035 throw new PaymentProcessorException(ts('Network error') . ' ' . curl_error($ch) . curl_errno($ch), curl_errno($ch));
1039 $outcome = strtolower(CRM_Utils_Array
::value('ack', $result));
1041 if ($outcome != 'success' && $outcome != 'successwithwarning') {
1042 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1049 * This function will take NVPString and convert it to an Associative Array.
1051 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1053 * @param string $str
1057 public static function deformat($str) {
1060 while (strlen($str)) {
1062 $keyPos = strpos($str, '=');
1064 // position of value
1065 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1067 /*getting the Key and Value values and storing in a Associative Array*/
1069 $key = substr($str, 0, $keyPos);
1070 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1072 //decoding the respose
1073 $result[strtolower(urldecode($key))] = urldecode($val);
1074 $str = substr($str, $valPos +
1, strlen($str));
1081 * Get array of fields that should be displayed on the payment form.
1084 * @throws \Civi\Payment\Exception\PaymentProcessorException
1086 public function getPaymentFormFields() {
1087 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
1088 return $this->getCreditCardFormFields();
1096 * Map the paypal params to CiviCRM params using a field map.
1098 * @param array $fieldMap
1099 * @param array $paypalParams
1103 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1105 foreach ($fieldMap as $civicrmField => $paypalField) {
1106 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;
1112 * Is this being processed by payment express.
1114 * Either because it is payment express or because is pro with paypal express in use.
1116 * @param array $params
1119 * @throws \Civi\Payment\Exception\PaymentProcessorException
1121 protected function isPaypalExpress($params) {
1122 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
1126 // This would occur postProcess.
1127 if (!empty($params['token'])) {
1130 if (isset($params['button']) && stristr($params['button'], 'express')) {
1134 // The contribution form passes a 'button' but the event form might still set one of these fields.
1135 // @todo more standardisation & get paypal fully out of the form layer.
1136 $possibleExpressFields = [
1137 '_qf_Register_upload_express_x',
1138 '_qf_Payment_upload_express_x',
1140 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {