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';
245 //LCD if recurring, collect additional data and set some values
246 if (!empty($params['is_recur'])) {
247 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
248 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
249 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
250 $args['L_PAYMENTTYPE0'] = 'Any';
253 // Allow further manipulation of the arguments via custom hooks ..
254 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
256 $result = $this->invokeAPI($args);
258 if (is_a($result, 'CRM_Core_Error')) {
259 throw new PaymentProcessorException($result->message
);
264 return $result['token'];
268 * Get any details that may be available to the payment processor due to an approval process having happened.
270 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
273 * @param array $storedDetails
276 * @throws \Civi\Payment\Exception\PaymentProcessorException
278 public function getPreApprovalDetails($storedDetails) {
279 return empty($storedDetails['token']) ?
[] : $this->getExpressCheckoutDetails($storedDetails['token']);
283 * Get details from paypal.
285 * Check PayPal documentation for more information
287 * @param string $token
288 * The key associated with this transaction.
291 * the result in an nice formatted array (or an error object)
292 * @throws \Civi\Payment\Exception\PaymentProcessorException
294 public function getExpressCheckoutDetails($token) {
297 $this->initialize($args, 'GetExpressCheckoutDetails');
298 $args['token'] = $token;
300 $args['method'] = 'GetExpressCheckoutDetails';
302 $result = $this->invokeAPI($args);
304 if (is_a($result, 'CRM_Core_Error')) {
305 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
311 'payer_status' => 'payerstatus',
312 'payer_id' => 'payerid',
313 'first_name' => 'firstname',
314 'middle_name' => 'middlename',
315 'last_name' => 'lastname',
316 'street_address' => 'shiptostreet',
317 'supplemental_address_1' => 'shiptostreet2',
318 'city' => 'shiptocity',
319 'postal_code' => 'shiptozip',
320 'state_province' => 'shiptostate',
321 'country' => 'shiptocountrycode',
323 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
327 * Do the express checkout at paypal.
329 * Check PayPal documentation for more information
331 * @param array $params
334 * The result in an nice formatted array.
336 * @throws \Civi\Payment\Exception\PaymentProcessorException
338 public function doExpressCheckout(&$params) {
339 if (!empty($params['is_recur'])) {
340 return $this->createRecurringPayments($params);
344 $this->initialize($args, 'DoExpressCheckoutPayment');
345 $args['token'] = $params['token'];
346 $args['paymentAction'] = 'Sale';
347 $args['amt'] = $params['amount'];
348 $args['currencyCode'] = $params['currencyID'];
349 $args['payerID'] = $params['payer_id'];
350 $args['invnum'] = $params['invoiceID'];
351 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
352 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
353 $args['desc'] = $params['description'];
355 // add CiviCRM BN code
356 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
358 $result = $this->invokeAPI($args);
360 if (is_a($result, 'CRM_Core_Error')) {
361 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
365 $params['trxn_id'] = $result['transactionid'];
366 $params['gross_amount'] = $result['amt'];
367 $params['fee_amount'] = $result['feeamt'];
368 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
369 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
370 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
372 $params['payment_status'] = $result['paymentstatus'];
373 $params['pending_reason'] = $result['pendingreason'];
374 if (!empty($params['is_recur'])) {
375 // See comment block.
376 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
379 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
385 * Create recurring payments.
387 * Use a pre-authorisation token to activate a recurring payment profile
388 * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
390 * @param array $params
395 public function createRecurringPayments(&$params) {
397 $this->initialize($args, 'CreateRecurringPaymentsProfile');
399 $start_time = strtotime(date('m/d/Y'));
400 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
402 $args['token'] = $params['token'];
403 $args['paymentAction'] = 'Sale';
404 $args['amt'] = $params['amount'];
405 $args['currencyCode'] = $params['currencyID'];
406 $args['payerID'] = $params['payer_id'];
407 $args['invnum'] = $params['invoiceID'];
408 $args['profilestartdate'] = $start_date;
409 $args['method'] = 'CreateRecurringPaymentsProfile';
410 $args['billingfrequency'] = $params['frequency_interval'];
411 $args['billingperiod'] = ucwords($params['frequency_unit']);
412 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
413 $args['totalbillingcycles'] = CRM_Utils_Array
::value('installments', $params);
414 $args['version'] = '56.0';
415 $args['profilereference'] = "i={$params['invoiceID']}" .
417 "&c={$params['contactID']}" .
418 "&r={$params['contributionRecurID']}" .
419 "&b={$params['contributionID']}" .
420 "&p={$params['contributionPageID']}";
422 // add CiviCRM BN code
423 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
425 $result = $this->invokeAPI($args);
427 if (is_a($result, 'CRM_Core_Error')) {
431 /* Success - result looks like"
433 * 'profileid' => 'I-CP1U0PLG91R2',
434 * 'profilestatus' => 'ActiveProfile',
435 * 'timestamp' => '2018-05-07T03:55:52Z',
436 * 'correlationid' => 'e717999e9bf62',
437 * 'ack' => 'Success',
438 * 'version' => '56.0',
439 * 'build' => '39949200',)
441 $params['trxn_id'] = $result['profileid'];
442 $params['payment_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
453 public function initialize(&$args, $method) {
454 $args['user'] = $this->_paymentProcessor
['user_name'];
455 $args['pwd'] = $this->_paymentProcessor
['password'];
456 $args['version'] = 3.0;
457 $args['signature'] = $this->_paymentProcessor
['signature'];
458 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
459 $args['method'] = $method;
463 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
465 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
468 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
469 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
470 * doTransferCheckout would not traditionally come back.
472 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
475 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
476 * return Error objects
478 * @param array $params
480 * @param string $component
485 * @throws \Civi\Payment\Exception\PaymentProcessorException
487 public function doPayment(&$params, $component = 'contribute') {
488 if ($this->isPayPalType($this::PAYPAL_EXPRESS
) ||
($this->isPayPalType($this::PAYPAL_PRO
) && !empty($params['token']))) {
489 $this->_component
= $component;
490 return $this->doExpressCheckout($params);
493 return parent
::doPayment($params, $component);
497 * This function collects all the information from a web/api form and invokes
498 * the relevant payment processor specific functions to perform the transaction
500 * @param array $params
501 * Assoc array of input parameters for this transaction.
503 * @param string $component
505 * the result in an nice formatted array (or an error object)
506 * @throws \Civi\Payment\Exception\PaymentProcessorException
508 public function doDirectPayment(&$params, $component = 'contribute') {
511 $this->initialize($args, 'DoDirectPayment');
513 $args['paymentAction'] = 'Sale';
514 $args['amt'] = $this->getAmount($params);
515 $args['currencyCode'] = $this->getCurrency($params);
516 $args['invnum'] = $params['invoiceID'];
517 $args['ipaddress'] = $params['ip_address'];
518 $args['creditCardType'] = $params['credit_card_type'];
519 $args['acct'] = $params['credit_card_number'];
520 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
521 $args['cvv2'] = $params['cvv2'];
522 $args['firstName'] = $params['first_name'];
523 $args['lastName'] = $params['last_name'];
524 $args['email'] = CRM_Utils_Array
::value('email', $params);
525 $args['street'] = $params['street_address'];
526 $args['city'] = $params['city'];
527 $args['state'] = $params['state_province'];
528 $args['countryCode'] = $params['country'];
529 $args['zip'] = $params['postal_code'];
530 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
531 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
533 // add CiviCRM BN code
534 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
536 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
537 $start_time = strtotime(date('m/d/Y'));
538 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
540 $args['PaymentAction'] = 'Sale';
541 $args['billingperiod'] = ucwords($params['frequency_unit']);
542 $args['billingfrequency'] = $params['frequency_interval'];
543 $args['method'] = "CreateRecurringPaymentsProfile";
544 $args['profilestartdate'] = $start_date;
546 $params['description'] . ": " .
547 $params['amount'] . " Per " .
548 $params['frequency_interval'] . " " .
549 $params['frequency_unit'];
550 $args['amt'] = $this->getAmount($params);
551 $args['totalbillingcycles'] = CRM_Utils_Array
::value('installments', $params);
552 $args['version'] = 56.0;
553 $args['PROFILEREFERENCE'] = "" .
554 "i=" . $params['invoiceID'] . "&m=" . $component .
555 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
556 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
559 // Allow further manipulation of the arguments via custom hooks ..
560 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
562 $result = $this->invokeAPI($args);
565 if (is_a($result, 'CRM_Core_Error')) {
569 $params['recurr_profile_id'] = NULL;
571 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
572 $params['recurr_profile_id'] = $result['profileid'];
577 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
578 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
579 $params = array_merge($params, $this->doQuery($params));
584 * Query payment processor for details about a transaction.
586 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
588 * @param array $params
589 * Array of parameters containing one of:
590 * - trxn_id Id of an individual transaction.
591 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
594 * Extra parameters retrieved.
595 * Any parameters retrievable through this should be documented in the function comments at
596 * CRM_Core_Payment::doQuery. Currently
597 * - fee_amount Amount of fee paid
599 * @throws \Civi\Payment\Exception\PaymentProcessorException
601 public function doQuery($params) {
602 //CRM-18140 - trxn_id not returned for recurring paypal transaction
603 if (!empty($params['is_recur'])) {
606 elseif (empty($params['trxn_id'])) {
607 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
610 'TRANSACTIONID' => $params['trxn_id'],
612 $this->initialize($args, 'GetTransactionDetails');
613 $result = $this->invokeAPI($args);
615 'fee_amount' => $result['feeamt'],
616 'net_amount' => $params['gross_amount'] - $result['feeamt'],
621 * This function checks to see if we have the right config values.
623 * @return null|string
624 * the error message if any
625 * @throws \Civi\Payment\Exception\PaymentProcessorException
627 public function checkConfig() {
630 if (!$this->isPayPalType($this::PAYPAL_STANDARD
)) {
631 if (empty($this->_paymentProcessor
['signature'])) {
632 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
635 if (empty($this->_paymentProcessor
['password'])) {
636 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
639 if (empty($this->_paymentProcessor
['user_name'])) {
640 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
643 if (!empty($error)) {
644 return implode('<p>', $error);
652 * @return null|string
653 * @throws \Civi\Payment\Exception\PaymentProcessorException
655 public function cancelSubscriptionURL() {
656 if ($this->isPayPalType($this::PAYPAL_STANDARD
)) {
657 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
665 * Check whether a method is present ( & supported ) by the payment processor object.
667 * @param string $method
668 * Method to check for.
671 * @throws \Civi\Payment\Exception\PaymentProcessorException
673 public function isSupported($method) {
674 if (!$this->isPayPalType($this::PAYPAL_PRO
)) {
675 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
676 // by standard or express.
679 return parent
::isSupported($method);
683 * Paypal express replaces the submit button with it's own.
686 * Should the form button by suppressed?
687 * @throws \Civi\Payment\Exception\PaymentProcessorException
689 public function isSuppressSubmitButtons() {
690 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
697 * @param string $message
698 * @param array $params
700 * @return array|bool|object
701 * @throws \Civi\Payment\Exception\PaymentProcessorException
703 public function cancelSubscription(&$message = '', $params = []) {
704 if ($this->isPayPalType($this::PAYPAL_PRO
) ||
$this->isPayPalType($this::PAYPAL_EXPRESS
)) {
706 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
708 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
709 $args['ACTION'] = 'Cancel';
710 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
712 $result = $this->invokeAPI($args);
713 if (is_a($result, 'CRM_Core_Error')) {
716 $message = "{$result['ack']}: profileid={$result['profileid']}";
723 * Process incoming notification.
725 * @throws \CRM_Core_Exception
726 * @throws \CiviCRM_API3_Exception
728 public static function handlePaymentNotification() {
729 $params = array_merge($_GET, $_REQUEST);
730 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
731 $lastParam = array_pop($q);
732 if (is_numeric($lastParam)) {
733 $params['processor_id'] = $lastParam;
735 $result = civicrm_api3('PaymentProcessor', 'get', [
737 'id' => $params['processor_id'],
738 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
740 if (!$result['count']) {
741 throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
744 $paymentProcessorType = CRM_Utils_Array
::value('api.PaymentProcessorType.getvalue', $result['values'][0]);
745 switch ($paymentProcessorType) {
747 // "PayPal - Website Payments Pro"
748 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
751 case 'PayPal_Standard':
752 // "PayPal - Website Payments Standard"
753 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
757 // If we don't have PayPal Standard or PayPal Pro, something's wrong.
758 // Log an error and exit.
759 throw new CRM_Core_Exception("The processor_id value '{$params['processor_id']}' is for a processor of type '{$paymentProcessorType}', which is invalid in this context.");
766 * @param string $message
767 * @param array $params
769 * @return array|bool|object
770 * @throws \Civi\Payment\Exception\PaymentProcessorException
772 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
773 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
774 $config = CRM_Core_Config
::singleton();
776 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
778 $args['PROFILEID'] = $params['subscriptionId'];
779 $args['AMT'] = $this->getAmount($params);
780 $args['CURRENCYCODE'] = $config->defaultCurrency
;
781 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
782 $args['ACCT'] = $params['credit_card_number'];
783 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
784 $args['CVV2'] = $params['cvv2'];
786 $args['FIRSTNAME'] = $params['first_name'];
787 $args['LASTNAME'] = $params['last_name'];
788 $args['STREET'] = $params['street_address'];
789 $args['CITY'] = $params['city'];
790 $args['STATE'] = $params['state_province'];
791 $args['COUNTRYCODE'] = $params['postal_code'];
792 $args['ZIP'] = $params['country'];
794 $result = $this->invokeAPI($args);
795 if (is_a($result, 'CRM_Core_Error')) {
798 $message = "{$result['ack']}: profileid={$result['profileid']}";
805 * @param string $message
806 * @param array $params
808 * @return array|bool|object
809 * @throws \Civi\Payment\Exception\PaymentProcessorException
811 public function changeSubscriptionAmount(&$message = '', $params = []) {
812 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
813 $config = CRM_Core_Config
::singleton();
815 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
817 $args['PROFILEID'] = $params['subscriptionId'];
818 $args['AMT'] = $this->getAmount($params);
819 $args['CURRENCYCODE'] = $config->defaultCurrency
;
820 $args['BILLINGFREQUENCY'] = $params['installments'];
822 $result = $this->invokeAPI($args);
823 CRM_Core_Error
::debug_var('$result', $result);
824 if (is_a($result, 'CRM_Core_Error')) {
827 $message = "{$result['ack']}: profileid={$result['profileid']}";
834 * Function to action pre-approval if supported
836 * @param array $params
837 * Parameters from the form
840 * - pre_approval_parameters (this will be stored on the calling form & available later)
841 * - redirect_url (if set the browser will be redirected to this.
842 * @throws \Civi\Payment\Exception\PaymentProcessorException
844 public function doPreApproval(&$params) {
845 if (!$this->isPaypalExpress($params)) {
848 $this->_component
= $params['component'];
849 $token = $this->setExpressCheckOut($params);
851 'pre_approval_parameters' => ['token' => $token],
852 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
857 * @param array $params
858 * @param string $component
862 public function doTransferCheckout(&$params, $component = 'contribute') {
864 $notifyParameters = ['module' => $component];
865 $notifyParameterMap = [
866 'contactID' => 'contactID',
867 'contributionID' => 'contributionID',
868 'eventID' => 'eventID',
869 'participantID' => 'participantID',
870 'membershipID' => 'membershipID',
871 'related_contact' => 'relatedContactID',
872 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
873 'accountingCode' => 'accountingCode',
874 'contributionRecurID' => 'contributionRecurID',
875 'contributionPageID' => 'contributionPageID',
877 foreach ($notifyParameterMap as $paramsName => $notifyName) {
878 if (!empty($params[$paramsName])) {
879 $notifyParameters[$notifyName] = $params[$paramsName];
882 $notifyURL = $this->getNotifyUrl();
884 $config = CRM_Core_Config
::singleton();
885 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
886 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
888 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
889 if (!empty($params['is_recur'])) {
890 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
893 $cancelURL = CRM_Utils_System
::url(
900 'business' => $this->_paymentProcessor
['user_name'],
901 'notify_url' => $notifyURL,
902 'item_name' => $this->getPaymentDescription($params, 127),
904 'undefined_quantity' => 0,
905 'cancel_return' => $cancelURL,
908 'return' => $this->getReturnSuccessUrl($params['qfKey']),
910 'currency_code' => $params['currencyID'],
911 'invoice' => $params['invoiceID'],
912 'lc' => substr($config->lcMessages
, -2),
913 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
914 'custom' => json_encode($notifyParameters),
915 'bn' => 'CiviCRM_SP',
918 // add name and address if available, CRM-3130
920 'first_name' => 'first_name',
921 'last_name' => 'last_name',
922 'street_address' => 'address1',
923 'country' => 'country',
924 'preferred_language' => 'lc',
926 'state_province' => 'state',
927 'postal_code' => 'zip',
931 foreach (array_keys($params) as $p) {
932 // get the base name without the location type suffixed to it
933 $parts = explode('-', $p);
934 $name = count($parts) > 1 ?
$parts[0] : $p;
935 if (isset($otherVars[$name])) {
936 $value = $params[$p];
938 if ($name == 'state_province') {
939 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
942 if ($name == 'country') {
943 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
944 $value = $countryName;
946 // ensure value is not an array
948 if (!is_array($value)) {
949 $paypalParams[$otherVars[$name]] = $value;
955 // if recurring donations, add a few more items
956 if (!empty($params['is_recur'])) {
957 if (!$params['contributionRecurID']) {
958 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
962 'cmd' => '_xclick-subscriptions',
963 'a3' => $this->getAmount($params),
964 'p3' => $params['frequency_interval'],
965 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
968 'srt' => CRM_Utils_Array
::value('installments', $params),
976 'amount' => $params['amount'],
980 // Allow further manipulation of the arguments via custom hooks ..
981 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
984 foreach ($paypalParams as $key => $value) {
985 if ($value === NULL) {
989 $value = urlencode($value);
990 if ($key == 'return' ||
991 $key == 'cancel_return' ||
994 $value = str_replace('%2F', '/', $value);
996 $uri .= "&{$key}={$value}";
999 $uri = substr($uri, 1);
1000 $url = $this->_paymentProcessor
['url_site'];
1001 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
1002 $paypalURL = "{$url}{$sub}?$uri";
1004 CRM_Utils_System
::redirect($paypalURL);
1008 * Hash_call: Function to perform the API call to PayPal using API signature.
1010 * @methodName is name of API method.
1011 * @nvpStr is nvp string.
1012 * returns an associative array containing the response from the server.
1014 * @param array $args
1017 * @return array|object
1018 * @throws \Exception
1020 public function invokeAPI($args, $url = NULL) {
1022 if ($url === NULL) {
1023 if (empty($this->_paymentProcessor
['url_api'])) {
1024 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
1027 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
1031 foreach ($args as $n => $v) {
1032 $p[] = "$n=" . urlencode($v);
1035 //NVPRequest for submitting to server
1036 $nvpreq = implode('&', $p);
1038 if (!function_exists('curl_init')) {
1039 CRM_Core_Error
::fatal("curl functions NOT available.");
1042 //setting the curl parameters.
1044 curl_setopt($ch, CURLOPT_URL
, $url);
1045 curl_setopt($ch, CURLOPT_VERBOSE
, 0);
1047 //turning off the server and peer verification(TrustManager Concept).
1048 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
1049 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, Civi
::settings()->get('verifySSL') ?
2 : 0);
1051 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
1052 curl_setopt($ch, CURLOPT_POST
, 1);
1054 //setting the nvpreq as POST FIELD to curl
1055 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
1057 //getting response from server
1058 $response = curl_exec($ch);
1060 //converting NVPResponse to an Associative Array
1061 $result = self
::deformat($response);
1063 if (curl_errno($ch)) {
1064 $e = CRM_Core_Error
::singleton();
1065 $e->push(curl_errno($ch),
1075 $outcome = strtolower(CRM_Utils_Array
::value('ack', $result));
1077 if ($outcome != 'success' && $outcome != 'successwithwarning') {
1078 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1085 * This function will take NVPString and convert it to an Associative Array.
1087 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1089 * @param string $str
1093 public static function deformat($str) {
1096 while (strlen($str)) {
1098 $keyPos = strpos($str, '=');
1100 // position of value
1101 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1103 /*getting the Key and Value values and storing in a Associative Array*/
1105 $key = substr($str, 0, $keyPos);
1106 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1108 //decoding the respose
1109 $result[strtolower(urldecode($key))] = urldecode($val);
1110 $str = substr($str, $valPos +
1, strlen($str));
1117 * Get array of fields that should be displayed on the payment form.
1120 * @throws \Civi\Payment\Exception\PaymentProcessorException
1122 public function getPaymentFormFields() {
1123 if ($this->isPayPalType($this::PAYPAL_PRO
)) {
1124 return $this->getCreditCardFormFields();
1132 * Map the paypal params to CiviCRM params using a field map.
1134 * @param array $fieldMap
1135 * @param array $paypalParams
1139 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1141 foreach ($fieldMap as $civicrmField => $paypalField) {
1142 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;
1148 * Is this being processed by payment express.
1150 * Either because it is payment express or because is pro with paypal express in use.
1152 * @param array $params
1155 * @throws \Civi\Payment\Exception\PaymentProcessorException
1157 protected function isPaypalExpress($params) {
1158 if ($this->isPayPalType($this::PAYPAL_EXPRESS
)) {
1162 // This would occur postProcess.
1163 if (!empty($params['token'])) {
1166 if (isset($params['button']) && stristr($params['button'], 'express')) {
1170 // The contribution form passes a 'button' but the event form might still set one of these fields.
1171 // @todo more standardisation & get paypal fully out of the form layer.
1172 $possibleExpressFields = [
1173 '_qf_Register_upload_express_x',
1174 '_qf_Payment_upload_express_x',
1176 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {