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 $processor = new CRM_Financial_DAO_PaymentProcessor();
39 $processor->copyValues($params);
41 if (empty($params['id'])) {
42 $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
43 $ppTypeDAO->id
= $params['payment_processor_type_id'];
44 if (!$ppTypeDAO->find(TRUE)) {
45 CRM_Core_Error
::fatal(ts('Could not find payment processor meta information'));
48 // also copy meta fields from the info DAO
49 $processor->is_recur
= $ppTypeDAO->is_recur
;
50 $processor->billing_mode
= $ppTypeDAO->billing_mode
;
51 $processor->class_name
= $ppTypeDAO->class_name
;
52 $processor->payment_type
= $ppTypeDAO->payment_type
;
56 // CRM-11826, add entry in civicrm_entity_financial_account
57 // if financial_account_id is not NULL
58 if (!empty($params['financial_account_id'])) {
59 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
61 'entity_table' => 'civicrm_payment_processor',
62 'entity_id' => $processor->id
,
63 'account_relationship' => $relationTypeId,
64 'financial_account_id' => $params['financial_account_id'],
66 CRM_Financial_BAO_FinancialTypeAccount
::add($values);
69 if (isset($params['id']) && isset($params['is_active']) && !isset($params['is_test'])) {
70 // check if is_active has changed & if so update test instance is_active too.
71 $test_id = self
::getTestProcessorId($params['id']);
72 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
73 $testDAO->id
= $test_id;
74 if ($testDAO->find(TRUE)) {
75 $testDAO->is_active
= $params['is_active'];
80 Civi\Payment\System
::singleton()->flushProcessors();
87 public function __construct() {
88 parent
::__construct();
92 * Retrieve array of allowed credit cards for this payment processor.
93 * @param interger|null $paymentProcessorID id of processor.
96 public static function getCreditCards($paymentProcessorID = NULL) {
97 if (!empty($paymentProcessorID)) {
98 $processor = new CRM_Financial_DAO_PaymentProcessor();
99 $processor->id
= $paymentProcessorID;
100 $processor->find(TRUE);
101 $cards = json_decode($processor->accepted_credit_cards
, TRUE);
108 * Get options for a given contribution field.
110 * @param string $fieldName
111 * @param string $context see CRM_Core_DAO::buildOptionsContext.
112 * @param array $props whatever is known about this dao object.
115 * @see CRM_Core_DAO::buildOptions
118 public static function buildOptions($fieldName, $context = NULL, $props = []) {
120 if ($fieldName === 'financial_account_id') {
121 // Pseudo-field - let's help out.
122 return CRM_Core_BAO_FinancialTrxn
::buildOptions('to_financial_account_id', $context, $props);
124 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
128 * Retrieve DB object based on input parameters.
130 * It also stores all the retrieved values in the default array.
132 * @param array $params
133 * (reference ) an assoc array of name/value pairs.
134 * @param array $defaults
135 * (reference ) an assoc array to hold the flattened values.
137 * @return CRM_Financial_DAO_PaymentProcessor|null
138 * object on success, null otherwise
140 public static function retrieve(&$params, &$defaults) {
141 $paymentProcessor = new CRM_Financial_DAO_PaymentProcessor();
142 $paymentProcessor->copyValues($params);
143 if ($paymentProcessor->find(TRUE)) {
144 CRM_Core_DAO
::storeValues($paymentProcessor, $defaults);
145 return $paymentProcessor;
151 * Update the is_active flag in the db.
154 * Id of the database record.
155 * @param bool $is_active
156 * Value we want to set the is_active field.
159 * true if we found and updated the object, else false
161 public static function setIsActive($id, $is_active) {
162 return CRM_Core_DAO
::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
166 * Retrieve the default payment processor.
168 * @return CRM_Financial_DAO_PaymentProcessor|null
169 * The default payment processor object on success,
172 public static function &getDefault() {
173 if (self
::$_defaultPaymentProcessor == NULL) {
174 $params = ['is_default' => 1];
176 self
::$_defaultPaymentProcessor = self
::retrieve($params, $defaults);
178 return self
::$_defaultPaymentProcessor;
182 * Delete payment processor.
184 * @param int $paymentProcessorID
188 public static function del($paymentProcessorID) {
189 if (!$paymentProcessorID) {
190 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
193 $dao = new CRM_Financial_DAO_PaymentProcessor();
194 $dao->id
= $paymentProcessorID;
195 if (!$dao->find(TRUE)) {
199 $testDAO = new CRM_Financial_DAO_PaymentProcessor();
200 $testDAO->name
= $dao->name
;
201 $testDAO->is_test
= 1;
205 Civi\Payment\System
::singleton()->flushProcessors();
209 * Get the payment processor details.
211 * This returns an array whereas Civi\Payment\System::singleton->getByID() returns an object.
212 * The object is a key in the array.
214 * @param int $paymentProcessorID
215 * Payment processor id.
216 * @param string $mode
217 * Payment mode ie test or live.
220 * associated array with payment processor related fields
222 public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
223 $capabilities = ($mode == 'test') ?
['TestMode'] : [];
224 $processors = self
::getPaymentProcessors($capabilities, [$paymentProcessorID]);
225 return $processors[$paymentProcessorID];
229 * Given a live processor ID get the test id.
234 * Test payment processor ID.
236 public static function getTestProcessorId($id) {
237 $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', [
241 return civicrm_api3('payment_processor', 'getvalue', [
243 'name' => $liveProcessorName,
245 'domain_id' => CRM_Core_Config
::domainID(),
250 * Compare 2 payment processors to see which should go first based on is_default
251 * (sort function for sortDefaultFirst)
252 * @param array $processor1
253 * @param array $processor2
257 public static function defaultComparison($processor1, $processor2) {
258 $p1 = CRM_Utils_Array
::value('is_default', $processor1);
259 $p2 = CRM_Utils_Array
::value('is_default', $processor2);
263 return ($p1 > $p2) ?
-1 : 1;
267 * Get all payment processors as an array of objects.
269 * @param string|NULL $mode
270 * only return this mode - test|live or NULL for all
272 * @param bool $isCurrentDomainOnly
273 * Do we only want to load payment processors associated with the current domain.
275 * @throws CiviCRM_API3_Exception
278 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE) {
280 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config
::domainID();
282 $processors = CRM_Utils_Cache
::singleton()->get($cacheKey);
283 if (!empty($processors)) {
288 $retrievalParameters = [
290 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
291 'api.payment_processor_type.getsingle' => 1,
293 if ($isCurrentDomainOnly) {
294 $retrievalParameters['domain_id'] = CRM_Core_Config
::domainID();
296 if ($mode == 'test') {
297 $retrievalParameters['is_test'] = 1;
299 elseif ($mode == 'live') {
300 $retrievalParameters['is_test'] = 0;
303 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
304 foreach ($processors['values'] as $processor) {
308 'payment_processor_type_id',
324 foreach ($fieldsToProvide as $field) {
325 // Prevent e-notices in processor classes when not configured.
326 if (!isset($processor[$field])) {
327 $processors['values'][$processor['id']][$field] = NULL;
330 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
331 $processors['values'][$processor['id']]['object'] = Civi\Payment\System
::singleton()->getByProcessor($processor);
334 // Add the pay-later pseudo-processor.
335 $processors['values'][0] = [
336 'object' => new CRM_Core_Payment_Manual(),
338 'payment_processor_type_id' => 0,
339 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
340 'payment_processor_type' => 'Manual',
341 'class_name' => 'Payment_Manual',
342 'name' => 'pay_later',
343 'billing_mode' => '',
345 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
346 // Making this optionally recur would give lots of options -but it should
347 // be a row in the payment processor table before we do that.
352 CRM_Utils_Cache
::singleton()->set($cacheKey, $processors['values']);
354 return $processors['values'];
358 * Get Payment processors with specified capabilities.
359 * Note that both the singleton & the pseudoconstant function have caching so we don't add
360 * arguably this could go on the pseudoconstant class
362 * @param array $capabilities
363 * capabilities of processor e.g
369 * @param array|bool $ids
372 * available processors
374 public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
375 $testProcessors = in_array('TestMode', $capabilities) ? self
::getAllPaymentProcessors('test') : [];
376 if (is_array($ids)) {
377 $processors = self
::getAllPaymentProcessors('all', FALSE, FALSE);
378 if (in_array('TestMode', $capabilities)) {
379 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
380 foreach ($possibleLiveIDs as $possibleLiveID) {
381 if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
382 foreach ($testProcessors as $index => $testProcessor) {
383 if ($testProcessor['name'] == $liveProcessorName) {
384 $ids[] = $testProcessor['id'];
389 $processors = $testProcessors;
393 $processors = self
::getAllPaymentProcessors('all');
396 foreach ($processors as $index => $processor) {
397 if (is_array($ids) && !in_array($processor['id'], $ids)) {
398 unset($processors[$index]);
401 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
402 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
403 if (!is_a($processor['object'], 'CRM_Core_Payment')) {
404 unset($processors[$index]);
407 foreach ($capabilities as $capability) {
408 if (($processor['object']->supports($capability)) == FALSE) {
409 unset($processors[$index]);
419 * Is there a processor on this site with the specified capability.
421 * The capabilities are defined on CRM_Core_Payment and can be extended by
425 * - supportsBackOffice
427 * - supportsFutureRecurDate
428 * - supportsRecurring
429 * - supportsCancelRecurring
430 * - supportsRecurContributionsForPledges
432 * They are passed as array('BackOffice');
434 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
436 * @param array $capabilities
440 public static function hasPaymentProcessorSupporting($capabilities = []) {
441 $capabilitiesString = implode('', $capabilities);
442 if (!isset(\Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString])) {
443 $result = self
::getPaymentProcessors($capabilities);
444 \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]) ?
TRUE : FALSE;
446 return \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString];
450 * Retrieve payment processor id / info/ object based on component-id.
452 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
453 * that are entity specific as there is little shared code specific to obj or info
455 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
456 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
458 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
459 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
460 * no way to derive the processor - but hey - what processor? it didn't go through!
462 * Query for membership might look something like:
463 * SELECT fte.payment_processor_id
464 * FROM civicrm_membership mem
465 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
466 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
467 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
468 * 'civicrm_contribution'
469 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
471 * @param int $entityID
472 * @param string $component
474 * @param string $type
475 * Type of payment information to be retrieved.
477 * @return int|array|object
479 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
481 if (!in_array($component, [
490 if ($component == 'membership') {
492 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
493 FROM civicrm_membership mem
494 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
495 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
496 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
497 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
498 WHERE mp.membership_id = %1";
500 elseif ($component == 'contribute') {
502 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
503 FROM civicrm_contribution con
504 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
505 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
508 elseif ($component == 'recur') {
509 // @deprecated - use getPaymentProcessorForRecurringContribution.
511 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
512 FROM civicrm_contribution_recur cr
516 // We are interested in a single record.
519 $params = [1 => [$entityID, 'Integer']];
520 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
522 if (!$dao->fetch()) {
528 $ppID = (isset($dao->ppID1
) && $dao->ppID1
) ?
$dao->ppID1
: (isset($dao->ppID2
) ?
$dao->ppID2
: NULL);
529 $mode = (isset($dao->is_test
) && $dao->is_test
) ?
'test' : 'live';
530 if (!$ppID ||
$type == 'id') {
533 elseif ($type == 'info') {
534 $result = self
::getPayment($ppID, $mode);
536 elseif ($type == 'obj' && is_numeric($ppID)) {
538 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
540 catch (API_Exception
$e) {
541 // Unable to load the processor because this function uses an unreliable method to derive it.
542 // The function looks to load the payment processor ID from the contribution page, which
543 // can support multiple processors.
546 $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant
::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
547 $result = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
553 * Get the payment processor associated with a recurring contribution series.
555 * @param int $contributionRecurID
557 * @return \CRM_Core_Payment
559 public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
560 $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
561 'id' => $contributionRecurID,
562 'return' => 'payment_processor_id',
564 return Civi\Payment\System
::singleton()->getById($paymentProcessorId);
568 * Get the name of the payment processor
570 * @param $paymentProcessorId
572 * @return null|string
574 public static function getPaymentProcessorName($paymentProcessorId) {
576 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
577 'return' => ['name'],
578 'id' => $paymentProcessorId,
580 return $paymentProcessor['name'];
582 catch (Exception
$e) {
583 return ts('Unknown') . ' (' . $paymentProcessorId . ')';
588 * Generate and assign an arbitrary value to a field of a test object.
590 * @param string $fieldName
591 * @param array $fieldDef
592 * @param int $counter
593 * The globally-unique ID of the test object.
595 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
596 if ($fieldName === 'class_name') {
597 $this->class_name
= 'Payment_Dummy';
600 parent
::assignTestValue($fieldName, $fieldDef, $counter);
605 * Get the default financial account id for payment processor accounts.
607 * Note that there is only a 'name' field & no label field. If people customise
608 * name then this won't work. This is new best-effort functionality so that's non-regressive.
610 * The fix for that is to add a label value to the financial account table.
612 public static function getDefaultFinancialAccountID() {
613 return CRM_Core_PseudoConstant
::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');