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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class contains payment processor related functions.
21 class CRM_Financial_BAO_PaymentProcessor
extends CRM_Financial_DAO_PaymentProcessor
implements \Civi\Test\HookInterface
{
23 * Static holder for the default payment processor
26 public static $_defaultPaymentProcessor = NULL;
29 * Create Payment Processor.
31 * @param array $params
32 * Parameters for Processor entity.
34 * @return CRM_Financial_DAO_PaymentProcessor
36 * @throws \CRM_Core_Exception
37 * @throws \CiviCRM_API3_Exception
39 public static function create(array $params): CRM_Financial_DAO_PaymentProcessor
{
40 // If we are creating a new PaymentProcessor and have not specified the payment instrument to use, get the default from the Payment Processor Type.
41 if (empty($params['id']) && empty($params['payment_instrument_id'])) {
42 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessorType', 'getvalue', [
43 'id' => $params['payment_processor_type_id'],
44 'return' => 'payment_instrument_id',
47 $processor = new CRM_Financial_DAO_PaymentProcessor();
48 $processor->copyValues($params);
50 if (empty($params['id'])) {
51 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
52 $ppTypeDAO->id
= $params['payment_processor_type_id'];
53 if (!$ppTypeDAO->find(TRUE)) {
54 throw new CRM_Core_Exception(ts('Could not find payment processor meta information'));
57 // also copy meta fields from the info DAO
58 $processor->is_recur
= $ppTypeDAO->is_recur
;
59 $processor->billing_mode
= $ppTypeDAO->billing_mode
;
60 $processor->class_name
= $ppTypeDAO->class_name
;
61 $processor->payment_type
= $ppTypeDAO->payment_type
;
65 // CRM-11826, add entry in civicrm_entity_financial_account
66 // if financial_account_id is not NULL
67 if (!empty($params['financial_account_id'])) {
68 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
70 'entity_table' => 'civicrm_payment_processor',
71 'entity_id' => $processor->id
,
72 'account_relationship' => $relationTypeId,
73 'financial_account_id' => $params['financial_account_id'],
75 CRM_Financial_BAO_FinancialTypeAccount
::add($values);
78 if (isset($params['id']) && isset($params['is_active']) && !isset($params['is_test'])) {
79 // check if is_active has changed & if so update test instance is_active too.
80 $test_id = self
::getTestProcessorId($params['id']);
81 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
82 $testDAO->id
= $test_id;
83 if ($testDAO->find(TRUE)) {
84 $testDAO->is_active
= $params['is_active'];
89 Civi\Payment\System
::singleton()->flushProcessors();
94 * Retrieve array of allowed credit cards for this payment processor.
95 * @param int|null $paymentProcessorID
98 public static function getCreditCards($paymentProcessorID = NULL) {
99 if (!empty($paymentProcessorID)) {
100 $processor = new CRM_Financial_DAO_PaymentProcessor();
101 $processor->id
= $paymentProcessorID;
102 $processor->find(TRUE);
103 $cards = json_decode($processor->accepted_credit_cards
, TRUE);
110 * Get options for a given contribution field.
112 * @param string $fieldName
113 * @param string $context see CRM_Core_DAO::buildOptionsContext.
114 * @param array $props whatever is known about this dao object.
117 * @see CRM_Core_DAO::buildOptions
120 public static function buildOptions($fieldName, $context = NULL, $props = []) {
122 if ($fieldName === 'financial_account_id') {
123 // Pseudo-field - let's help out.
124 return CRM_Core_BAO_FinancialTrxn
::buildOptions('to_financial_account_id', $context, $props);
126 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
130 * Retrieve DB object based on input parameters.
132 * It also stores all the retrieved values in the default array.
134 * @param array $params
135 * (reference ) an assoc array of name/value pairs.
136 * @param array $defaults
137 * (reference ) an assoc array to hold the flattened values.
139 * @return CRM_Financial_DAO_PaymentProcessor|null
140 * object on success, null otherwise
142 public static function retrieve(&$params, &$defaults) {
143 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
144 $paymentProcessor->copyValues($params);
145 if ($paymentProcessor->find(TRUE)) {
146 CRM_Core_DAO
::storeValues($paymentProcessor, $defaults);
147 return $paymentProcessor;
153 * Update the is_active flag in the db.
156 * Id of the database record.
157 * @param bool $is_active
158 * Value we want to set the is_active field.
161 * true if we found and updated the object, else false
163 public static function setIsActive($id, $is_active) {
164 return CRM_Core_DAO
::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
168 * Retrieve the default payment processor.
170 * @return CRM_Financial_DAO_PaymentProcessor|null
171 * The default payment processor object on success,
174 public static function &getDefault() {
175 if (self
::$_defaultPaymentProcessor == NULL) {
176 $params = ['is_default' => 1];
178 self
::$_defaultPaymentProcessor = self
::retrieve($params, $defaults);
180 return self
::$_defaultPaymentProcessor;
184 * Delete payment processor.
186 * @param int $paymentProcessorID
189 public static function del($paymentProcessorID) {
190 if (!$paymentProcessorID) {
191 throw new CRM_Core_Exception(ts('Invalid value passed to delete function.'));
193 static::deleteRecord(['id' => $paymentProcessorID]);
197 * Callback for hook_civicrm_post().
198 * @param \Civi\Core\Event\PostEvent $event
200 public static function self_hook_civicrm_post(\Civi\Core\Event\PostEvent
$event) {
201 if ($event->action
=== 'delete') {
202 // When a paymentProcessor is deleted, delete the associated test processor
203 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
204 $testDAO->name
= $event->object->name
;
205 $testDAO->is_test
= 1;
208 Civi\Payment\System
::singleton()->flushProcessors();
213 * Get the payment processor details.
215 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
216 * The object is a key in the array.
218 * @param int $paymentProcessorID
219 * Payment processor id.
220 * @param string $mode
221 * Payment mode ie test or live.
224 * associated array with payment processor related fields
226 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
227 $capabilities = ($mode === 'test') ?
['TestMode'] : [];
228 $processors = self
::getPaymentProcessors($capabilities, [$paymentProcessorID]);
229 return $processors[$paymentProcessorID];
233 * Given a live processor ID get the test id.
238 * Test payment processor ID.
240 public static function getTestProcessorId($id) {
241 $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', [
245 return civicrm_api3('payment_processor', 'getvalue', [
247 'name' => $liveProcessorName,
249 'domain_id' => CRM_Core_Config
::domainID(),
254 * Compare 2 payment processors to see which should go first based on is_default
255 * (sort function for sortDefaultFirst)
256 * @param array $processor1
257 * @param array $processor2
261 public static function defaultComparison($processor1, $processor2) {
262 $p1 = $processor1['is_default'] ??
NULL;
263 $p2 = $processor2['is_default'] ??
NULL;
267 return ($p1 > $p2) ?
-1 : 1;
271 * Get all payment processors as an array of objects.
273 * @param string|null $mode
274 * only return this mode - test|live or NULL for all
276 * @param bool $isCurrentDomainOnly
277 * Do we only want to load payment processors associated with the current domain.
278 * @param bool|null $isActive
279 * Do we only want active processors, only inactive (FALSE) or all processors (NULL)
281 * @throws CiviCRM_API3_Exception
284 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE, $isActive = TRUE) {
286 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config
::domainID();
288 $processors = CRM_Utils_Cache
::singleton()->get($cacheKey);
289 if (!empty($processors)) {
294 $retrievalParameters = [
295 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
296 'api.payment_processor_type.getsingle' => 1,
298 if (isset($isActive)) {
299 // We use isset because we don't want to set the is_active parameter at all is $isActive is NULL
300 $retrievalParameters['is_active'] = $isActive;
302 if ($isCurrentDomainOnly) {
303 $retrievalParameters['domain_id'] = CRM_Core_Config
::domainID();
305 if ($mode === 'test') {
306 $retrievalParameters['is_test'] = 1;
308 elseif ($mode === 'live') {
309 $retrievalParameters['is_test'] = 0;
312 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
313 foreach ($processors['values'] as $processor) {
317 'payment_processor_type_id',
333 foreach ($fieldsToProvide as $field) {
334 // Prevent e-notices in processor classes when not configured.
335 if (!isset($processor[$field])) {
336 $processors['values'][$processor['id']][$field] = NULL;
339 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
340 $processors['values'][$processor['id']]['object'] = Civi\Payment\System
::singleton()->getByProcessor($processors['values'][$processor['id']]);
343 // Add the pay-later pseudo-processor.
344 $processors['values'][0] = [
345 'object' => new CRM_Core_Payment_Manual(),
347 'payment_processor_type_id' => 0,
348 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
349 'payment_processor_type' => 'Manual',
350 'class_name' => 'Payment_Manual',
351 'name' => 'pay_later',
352 'billing_mode' => '',
354 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
355 // Making this optionally recur would give lots of options -but it should
356 // be a row in the payment processor table before we do that.
361 CRM_Utils_Cache
::singleton()->set($cacheKey, $processors['values']);
363 return $processors['values'];
367 * Get Payment processors with specified capabilities.
368 * Note that both the singleton & the pseudoconstant function have caching so we don't add
369 * arguably this could go on the pseudoconstant class
371 * @param array $capabilities
372 * capabilities of processor e.g
378 * @param array|bool $ids
381 * available processors
383 * @throws \CiviCRM_API3_Exception
385 public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
386 if (is_array($ids)) {
387 if (in_array('TestMode', $capabilities, TRUE)) {
388 $testProcessors = in_array('TestMode', $capabilities) ? self
::getAllPaymentProcessors('test') : [];
389 $allProcessors = self
::getAllPaymentProcessors('all', FALSE, FALSE, NULL);
390 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
391 foreach ($possibleLiveIDs as $possibleLiveID) {
392 if (isset($allProcessors[$possibleLiveID]) && ($liveProcessorName = $allProcessors[$possibleLiveID]['name']) != FALSE) {
393 foreach ($testProcessors as $index => $testProcessor) {
394 if ($testProcessor['name'] === $liveProcessorName) {
395 $ids[] = $testProcessor['id'];
400 $processors = $testProcessors;
403 $processors = self
::getAllPaymentProcessors('all', FALSE, FALSE);
407 $processors = self
::getAllPaymentProcessors('all');
410 foreach ($processors as $index => $processor) {
411 if (is_array($ids) && !in_array($processor['id'], $ids)) {
412 unset($processors[$index]);
415 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
416 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
417 if (!$processor['object'] instanceof CRM_Core_Payment
) {
418 unset($processors[$index]);
421 foreach ($capabilities as $capability) {
422 if (($processor['object']->supports($capability)) == FALSE) {
423 unset($processors[$index]);
433 * Is there a processor on this site with the specified capability.
435 * The capabilities are defined on CRM_Core_Payment and can be extended by
439 * - supportsBackOffice
441 * - supportsFutureRecurDate
442 * - supportsRecurring
443 * - supportsCancelRecurring
444 * - supportsRecurContributionsForPledges
446 * They are passed as array('BackOffice');
448 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
450 * @param array $capabilities
454 public static function hasPaymentProcessorSupporting($capabilities = []) {
455 $capabilitiesString = implode('', $capabilities);
456 if (!isset(\Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString])) {
457 $result = self
::getPaymentProcessors($capabilities);
458 \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]);
460 return \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString];
464 * Retrieve payment processor id / info/ object based on component-id.
466 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
467 * that are entity specific as there is little shared code specific to obj or info
469 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
470 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
472 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
473 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
474 * no way to derive the processor - but hey - what processor? it didn't go through!
476 * Query for membership might look something like:
477 * SELECT fte.payment_processor_id
478 * FROM civicrm_membership mem
479 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
480 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
481 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
482 * 'civicrm_contribution'
483 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
485 * @param int $entityID
486 * @param string $component
488 * @param string $type
489 * Type of payment information to be retrieved.
491 * @return int|array|object
493 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
495 if (!in_array($component, [
504 if ($component === 'membership') {
506 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
507 FROM civicrm_membership mem
508 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
509 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
510 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
511 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
512 WHERE mp.membership_id = %1";
514 elseif ($component === 'contribute') {
516 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
517 FROM civicrm_contribution con
518 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
519 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
522 elseif ($component === 'recur') {
523 // @deprecated - use getPaymentProcessorForRecurringContribution.
525 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
526 FROM civicrm_contribution_recur cr
530 // We are interested in a single record.
533 $params = [1 => [$entityID, 'Integer']];
534 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
536 if (!$dao->fetch()) {
542 $ppID = (isset($dao->ppID1
) && $dao->ppID1
) ?
$dao->ppID1
: ($dao->ppID2 ??
NULL);
543 $mode = (isset($dao->is_test
) && $dao->is_test
) ?
'test' : 'live';
544 if (!$ppID ||
$type === 'id') {
547 elseif ($type === 'info') {
548 $result = self
::getPayment($ppID, $mode);
550 elseif ($type === 'obj' && is_numeric($ppID)) {
552 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
554 catch (API_Exception
$e) {
555 // Unable to load the processor because this function uses an unreliable method to derive it.
556 // The function looks to load the payment processor ID from the contribution page, which
557 // can support multiple processors.
560 $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant
::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
561 $result = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
567 * Get the payment processor associated with a recurring contribution series.
569 * @param int $contributionRecurID
571 * @return \CRM_Core_Payment
573 public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
574 $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
575 'id' => $contributionRecurID,
576 'return' => 'payment_processor_id',
578 return Civi\Payment\System
::singleton()->getById($paymentProcessorId);
582 * Get the name of the payment processor
584 * @param $paymentProcessorId
586 * @return null|string
588 public static function getPaymentProcessorName($paymentProcessorId) {
590 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
591 'return' => ['name'],
592 'id' => $paymentProcessorId,
594 return $paymentProcessor['name'];
596 catch (Exception
$e) {
597 return ts('Unknown') . ' (' . $paymentProcessorId . ')';
602 * Generate and assign an arbitrary value to a field of a test object.
604 * @param string $fieldName
605 * @param array $fieldDef
606 * @param int $counter
607 * The globally-unique ID of the test object.
609 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
610 if ($fieldName === 'class_name') {
611 $this->class_name
= 'Payment_Dummy';
614 parent
::assignTestValue($fieldName, $fieldDef, $counter);
619 * Get the default financial account id for payment processor accounts.
621 * Note that there is only a 'name' field & no label field. If people customise
622 * name then this won't work. This is new best-effort functionality so that's non-regressive.
624 * The fix for that is to add a label value to the financial account table.
626 public static function getDefaultFinancialAccountID() {
627 return CRM_Core_PseudoConstant
::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');