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
{
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
37 public static function create($params) {
38 // If we are creating a new PaymentProcessor and have not specified the payment instrument to use, get the default from the Payment Processor Type.
39 if (empty($params['id']) && empty($params['payment_instrument_id'])) {
40 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessorType', 'getvalue', [
41 'id' => $params['payment_processor_type_id'],
42 'return' => 'payment_instrument_id',
45 $processor = new CRM_Financial_DAO_PaymentProcessor();
46 $processor->copyValues($params);
48 if (empty($params['id'])) {
49 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
50 $ppTypeDAO->id
= $params['payment_processor_type_id'];
51 if (!$ppTypeDAO->find(TRUE)) {
52 throw new CRM_Core_Exception(ts('Could not find payment processor meta information'));
55 // also copy meta fields from the info DAO
56 $processor->is_recur
= $ppTypeDAO->is_recur
;
57 $processor->billing_mode
= $ppTypeDAO->billing_mode
;
58 $processor->class_name
= $ppTypeDAO->class_name
;
59 $processor->payment_type
= $ppTypeDAO->payment_type
;
63 // CRM-11826, add entry in civicrm_entity_financial_account
64 // if financial_account_id is not NULL
65 if (!empty($params['financial_account_id'])) {
66 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
68 'entity_table' => 'civicrm_payment_processor',
69 'entity_id' => $processor->id
,
70 'account_relationship' => $relationTypeId,
71 'financial_account_id' => $params['financial_account_id'],
73 CRM_Financial_BAO_FinancialTypeAccount
::add($values);
76 if (isset($params['id']) && isset($params['is_active']) && !isset($params['is_test'])) {
77 // check if is_active has changed & if so update test instance is_active too.
78 $test_id = self
::getTestProcessorId($params['id']);
79 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
80 $testDAO->id
= $test_id;
81 if ($testDAO->find(TRUE)) {
82 $testDAO->is_active
= $params['is_active'];
87 Civi\Payment\System
::singleton()->flushProcessors();
94 public function __construct() {
95 parent
::__construct();
99 * Retrieve array of allowed credit cards for this payment processor.
100 * @param interger|null $paymentProcessorID id of processor.
103 public static function getCreditCards($paymentProcessorID = NULL) {
104 if (!empty($paymentProcessorID)) {
105 $processor = new CRM_Financial_DAO_PaymentProcessor();
106 $processor->id
= $paymentProcessorID;
107 $processor->find(TRUE);
108 $cards = json_decode($processor->accepted_credit_cards
, TRUE);
115 * Get options for a given contribution field.
117 * @param string $fieldName
118 * @param string $context see CRM_Core_DAO::buildOptionsContext.
119 * @param array $props whatever is known about this dao object.
122 * @see CRM_Core_DAO::buildOptions
125 public static function buildOptions($fieldName, $context = NULL, $props = []) {
127 if ($fieldName === 'financial_account_id') {
128 // Pseudo-field - let's help out.
129 return CRM_Core_BAO_FinancialTrxn
::buildOptions('to_financial_account_id', $context, $props);
131 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
135 * Retrieve DB object based on input parameters.
137 * It also stores all the retrieved values in the default array.
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
141 * @param array $defaults
142 * (reference ) an assoc array to hold the flattened values.
144 * @return CRM_Financial_DAO_PaymentProcessor|null
145 * object on success, null otherwise
147 public static function retrieve(&$params, &$defaults) {
148 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
149 $paymentProcessor->copyValues($params);
150 if ($paymentProcessor->find(TRUE)) {
151 CRM_Core_DAO
::storeValues($paymentProcessor, $defaults);
152 return $paymentProcessor;
158 * Update the is_active flag in the db.
161 * Id of the database record.
162 * @param bool $is_active
163 * Value we want to set the is_active field.
166 * true if we found and updated the object, else false
168 public static function setIsActive($id, $is_active) {
169 return CRM_Core_DAO
::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
173 * Retrieve the default payment processor.
175 * @return CRM_Financial_DAO_PaymentProcessor|null
176 * The default payment processor object on success,
179 public static function &getDefault() {
180 if (self
::$_defaultPaymentProcessor == NULL) {
181 $params = ['is_default' => 1];
183 self
::$_defaultPaymentProcessor = self
::retrieve($params, $defaults);
185 return self
::$_defaultPaymentProcessor;
189 * Delete payment processor.
191 * @param int $paymentProcessorID
195 public static function del($paymentProcessorID) {
196 if (!$paymentProcessorID) {
197 throw new CRM_Core_Exception(ts('Invalid value passed to delete function.'));
200 $dao = new CRM_Financial_DAO_PaymentProcessor();
201 $dao->id
= $paymentProcessorID;
202 if (!$dao->find(TRUE)) {
206 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
207 $testDAO->name
= $dao->name
;
208 $testDAO->is_test
= 1;
212 Civi\Payment\System
::singleton()->flushProcessors();
216 * Get the payment processor details.
218 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
219 * The object is a key in the array.
221 * @param int $paymentProcessorID
222 * Payment processor id.
223 * @param string $mode
224 * Payment mode ie test or live.
227 * associated array with payment processor related fields
229 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
230 $capabilities = ($mode == 'test') ?
['TestMode'] : [];
231 $processors = self
::getPaymentProcessors($capabilities, [$paymentProcessorID]);
232 return $processors[$paymentProcessorID];
236 * Given a live processor ID get the test id.
241 * Test payment processor ID.
243 public static function getTestProcessorId($id) {
244 $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', [
248 return civicrm_api3('payment_processor', 'getvalue', [
250 'name' => $liveProcessorName,
252 'domain_id' => CRM_Core_Config
::domainID(),
257 * Compare 2 payment processors to see which should go first based on is_default
258 * (sort function for sortDefaultFirst)
259 * @param array $processor1
260 * @param array $processor2
264 public static function defaultComparison($processor1, $processor2) {
265 $p1 = $processor1['is_default'] ??
NULL;
266 $p2 = $processor2['is_default'] ??
NULL;
270 return ($p1 > $p2) ?
-1 : 1;
274 * Get all payment processors as an array of objects.
276 * @param string|NULL $mode
277 * only return this mode - test|live or NULL for all
279 * @param bool $isCurrentDomainOnly
280 * Do we only want to load payment processors associated with the current domain.
281 * @param bool|NULL $isActive
282 * Do we only want active processors, only inactive (FALSE) or all processors (NULL)
284 * @throws CiviCRM_API3_Exception
287 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE, $isActive = TRUE) {
289 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config
::domainID();
291 $processors = CRM_Utils_Cache
::singleton()->get($cacheKey);
292 if (!empty($processors)) {
297 $retrievalParameters = [
298 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
299 'api.payment_processor_type.getsingle' => 1,
301 if (isset($isActive)) {
302 // We use isset because we don't want to set the is_active parameter at all is $isActive is NULL
303 $retrievalParameters['is_active'] = $isActive;
305 if ($isCurrentDomainOnly) {
306 $retrievalParameters['domain_id'] = CRM_Core_Config
::domainID();
308 if ($mode == 'test') {
309 $retrievalParameters['is_test'] = 1;
311 elseif ($mode == 'live') {
312 $retrievalParameters['is_test'] = 0;
315 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
316 foreach ($processors['values'] as $processor) {
320 'payment_processor_type_id',
336 foreach ($fieldsToProvide as $field) {
337 // Prevent e-notices in processor classes when not configured.
338 if (!isset($processor[$field])) {
339 $processors['values'][$processor['id']][$field] = NULL;
342 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
343 $processors['values'][$processor['id']]['object'] = Civi\Payment\System
::singleton()->getByProcessor($processors['values'][$processor['id']]);
346 // Add the pay-later pseudo-processor.
347 $processors['values'][0] = [
348 'object' => new CRM_Core_Payment_Manual(),
350 'payment_processor_type_id' => 0,
351 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
352 'payment_processor_type' => 'Manual',
353 'class_name' => 'Payment_Manual',
354 'name' => 'pay_later',
355 'billing_mode' => '',
357 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
358 // Making this optionally recur would give lots of options -but it should
359 // be a row in the payment processor table before we do that.
364 CRM_Utils_Cache
::singleton()->set($cacheKey, $processors['values']);
366 return $processors['values'];
370 * Get Payment processors with specified capabilities.
371 * Note that both the singleton & the pseudoconstant function have caching so we don't add
372 * arguably this could go on the pseudoconstant class
374 * @param array $capabilities
375 * capabilities of processor e.g
381 * @param array|bool $ids
384 * available processors
386 * @throws \CiviCRM_API3_Exception
388 public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
389 if (is_array($ids)) {
390 if (in_array('TestMode', $capabilities, TRUE)) {
391 $testProcessors = in_array('TestMode', $capabilities) ? self
::getAllPaymentProcessors('test') : [];
392 $allProcessors = self
::getAllPaymentProcessors('all', FALSE, FALSE, NULL);
393 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
394 foreach ($possibleLiveIDs as $possibleLiveID) {
395 if (isset($allProcessors[$possibleLiveID]) && ($liveProcessorName = $allProcessors[$possibleLiveID]['name']) != FALSE) {
396 foreach ($testProcessors as $index => $testProcessor) {
397 if ($testProcessor['name'] === $liveProcessorName) {
398 $ids[] = $testProcessor['id'];
403 $processors = $testProcessors;
406 $processors = self
::getAllPaymentProcessors('all', FALSE, FALSE);
410 $processors = self
::getAllPaymentProcessors('all');
413 foreach ($processors as $index => $processor) {
414 if (is_array($ids) && !in_array($processor['id'], $ids)) {
415 unset($processors[$index]);
418 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
419 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
420 if (!$processor['object'] instanceof \CRM_Core_Payment
) {
421 unset($processors[$index]);
424 foreach ($capabilities as $capability) {
425 if (($processor['object']->supports($capability)) == FALSE) {
426 unset($processors[$index]);
436 * Is there a processor on this site with the specified capability.
438 * The capabilities are defined on CRM_Core_Payment and can be extended by
442 * - supportsBackOffice
444 * - supportsFutureRecurDate
445 * - supportsRecurring
446 * - supportsCancelRecurring
447 * - supportsRecurContributionsForPledges
449 * They are passed as array('BackOffice');
451 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
453 * @param array $capabilities
457 public static function hasPaymentProcessorSupporting($capabilities = []) {
458 $capabilitiesString = implode('', $capabilities);
459 if (!isset(\Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString])) {
460 $result = self
::getPaymentProcessors($capabilities);
461 \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]);
463 return \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString];
467 * Retrieve payment processor id / info/ object based on component-id.
469 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
470 * that are entity specific as there is little shared code specific to obj or info
472 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
473 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
475 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
476 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
477 * no way to derive the processor - but hey - what processor? it didn't go through!
479 * Query for membership might look something like:
480 * SELECT fte.payment_processor_id
481 * FROM civicrm_membership mem
482 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
483 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
484 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
485 * 'civicrm_contribution'
486 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
488 * @param int $entityID
489 * @param string $component
491 * @param string $type
492 * Type of payment information to be retrieved.
494 * @return int|array|object
496 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
498 if (!in_array($component, [
507 if ($component == 'membership') {
509 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
510 FROM civicrm_membership mem
511 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
512 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
513 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
514 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
515 WHERE mp.membership_id = %1";
517 elseif ($component == 'contribute') {
519 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
520 FROM civicrm_contribution con
521 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
522 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
525 elseif ($component == 'recur') {
526 // @deprecated - use getPaymentProcessorForRecurringContribution.
528 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
529 FROM civicrm_contribution_recur cr
533 // We are interested in a single record.
536 $params = [1 => [$entityID, 'Integer']];
537 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
539 if (!$dao->fetch()) {
545 $ppID = (isset($dao->ppID1
) && $dao->ppID1
) ?
$dao->ppID1
: ($dao->ppID2 ??
NULL);
546 $mode = (isset($dao->is_test
) && $dao->is_test
) ?
'test' : 'live';
547 if (!$ppID ||
$type == 'id') {
550 elseif ($type == 'info') {
551 $result = self
::getPayment($ppID, $mode);
553 elseif ($type == 'obj' && is_numeric($ppID)) {
555 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
557 catch (API_Exception
$e) {
558 // Unable to load the processor because this function uses an unreliable method to derive it.
559 // The function looks to load the payment processor ID from the contribution page, which
560 // can support multiple processors.
563 $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant
::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
564 $result = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
570 * Get the payment processor associated with a recurring contribution series.
572 * @param int $contributionRecurID
574 * @return \CRM_Core_Payment
576 public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
577 $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
578 'id' => $contributionRecurID,
579 'return' => 'payment_processor_id',
581 return Civi\Payment\System
::singleton()->getById($paymentProcessorId);
585 * Get the name of the payment processor
587 * @param $paymentProcessorId
589 * @return null|string
591 public static function getPaymentProcessorName($paymentProcessorId) {
593 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
594 'return' => ['name'],
595 'id' => $paymentProcessorId,
597 return $paymentProcessor['name'];
599 catch (Exception
$e) {
600 return ts('Unknown') . ' (' . $paymentProcessorId . ')';
605 * Generate and assign an arbitrary value to a field of a test object.
607 * @param string $fieldName
608 * @param array $fieldDef
609 * @param int $counter
610 * The globally-unique ID of the test object.
612 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
613 if ($fieldName === 'class_name') {
614 $this->class_name
= 'Payment_Dummy';
617 parent
::assignTestValue($fieldName, $fieldDef, $counter);
622 * Get the default financial account id for payment processor accounts.
624 * Note that there is only a 'name' field & no label field. If people customise
625 * name then this won't work. This is new best-effort functionality so that's non-regressive.
627 * The fix for that is to add a label value to the financial account table.
629 public static function getDefaultFinancialAccountID() {
630 return CRM_Core_PseudoConstant
::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');