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 CRM_Core_Error
::fatal(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 CRM_Core_Error
::fatal(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 = CRM_Utils_Array
::value('is_default', $processor1);
266 $p2 = CRM_Utils_Array
::value('is_default', $processor2);
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.
282 * @throws CiviCRM_API3_Exception
285 public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE) {
287 $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config
::domainID();
289 $processors = CRM_Utils_Cache
::singleton()->get($cacheKey);
290 if (!empty($processors)) {
295 $retrievalParameters = [
297 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
298 'api.payment_processor_type.getsingle' => 1,
300 if ($isCurrentDomainOnly) {
301 $retrievalParameters['domain_id'] = CRM_Core_Config
::domainID();
303 if ($mode == 'test') {
304 $retrievalParameters['is_test'] = 1;
306 elseif ($mode == 'live') {
307 $retrievalParameters['is_test'] = 0;
310 $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
311 foreach ($processors['values'] as $processor) {
315 'payment_processor_type_id',
331 foreach ($fieldsToProvide as $field) {
332 // Prevent e-notices in processor classes when not configured.
333 if (!isset($processor[$field])) {
334 $processors['values'][$processor['id']][$field] = NULL;
337 $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name'];
338 $processors['values'][$processor['id']]['object'] = Civi\Payment\System
::singleton()->getByProcessor($processor);
341 // Add the pay-later pseudo-processor.
342 $processors['values'][0] = [
343 'object' => new CRM_Core_Payment_Manual(),
345 'payment_processor_type_id' => 0,
346 // This shouldn't be required but there are still some processors hacked into core with nasty 'if's.
347 'payment_processor_type' => 'Manual',
348 'class_name' => 'Payment_Manual',
349 'name' => 'pay_later',
350 'billing_mode' => '',
352 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
353 // Making this optionally recur would give lots of options -but it should
354 // be a row in the payment processor table before we do that.
359 CRM_Utils_Cache
::singleton()->set($cacheKey, $processors['values']);
361 return $processors['values'];
365 * Get Payment processors with specified capabilities.
366 * Note that both the singleton & the pseudoconstant function have caching so we don't add
367 * arguably this could go on the pseudoconstant class
369 * @param array $capabilities
370 * capabilities of processor e.g
376 * @param array|bool $ids
379 * available processors
381 public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
382 if (is_array($ids)) {
383 $testProcessors = in_array('TestMode', $capabilities) ? self
::getAllPaymentProcessors('test') : [];
384 $processors = self
::getAllPaymentProcessors('all', FALSE, FALSE);
385 if (in_array('TestMode', $capabilities)) {
386 $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
387 foreach ($possibleLiveIDs as $possibleLiveID) {
388 if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
389 foreach ($testProcessors as $index => $testProcessor) {
390 if ($testProcessor['name'] == $liveProcessorName) {
391 $ids[] = $testProcessor['id'];
396 $processors = $testProcessors;
400 $processors = self
::getAllPaymentProcessors('all');
403 foreach ($processors as $index => $processor) {
404 if (is_array($ids) && !in_array($processor['id'], $ids)) {
405 unset($processors[$index]);
408 // Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
409 // This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
410 if (!is_a($processor['object'], 'CRM_Core_Payment')) {
411 unset($processors[$index]);
414 foreach ($capabilities as $capability) {
415 if (($processor['object']->supports($capability)) == FALSE) {
416 unset($processors[$index]);
426 * Is there a processor on this site with the specified capability.
428 * The capabilities are defined on CRM_Core_Payment and can be extended by
432 * - supportsBackOffice
434 * - supportsFutureRecurDate
435 * - supportsRecurring
436 * - supportsCancelRecurring
437 * - supportsRecurContributionsForPledges
439 * They are passed as array('BackOffice');
441 * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
443 * @param array $capabilities
447 public static function hasPaymentProcessorSupporting($capabilities = []) {
448 $capabilitiesString = implode('', $capabilities);
449 if (!isset(\Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString])) {
450 $result = self
::getPaymentProcessors($capabilities);
451 \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]) ?
TRUE : FALSE;
453 return \Civi
::$statics[__CLASS__
]['supported_capabilities'][$capabilitiesString];
457 * Retrieve payment processor id / info/ object based on component-id.
459 * @todo function needs revisiting. The whole 'info / obj' thing is an overload. Recommend creating new functions
460 * that are entity specific as there is little shared code specific to obj or info
462 * Also, it does not accurately derive the processor - for a completed contribution the best place to look is in the
463 * relevant financial_trxn record. For a recurring contribution it is in the contribution_recur table.
465 * For a membership the relevant contribution_recur should be derived & then resolved as above. The contribution page
466 * is never a reliable place to look as there can be more than one configured. For a pending contribution there is
467 * no way to derive the processor - but hey - what processor? it didn't go through!
469 * Query for membership might look something like:
470 * SELECT fte.payment_processor_id
471 * FROM civicrm_membership mem
472 * INNER JOIN civicrm_line_item li ON ( mem.id = li.entity_id AND li.entity_table = 'civicrm_membership')
473 * INNER JOIN civicrm_contribution con ON ( li.contribution_id = con.id )
474 * LEFT JOIN civicrm_entity_financial_trxn ft ON ft.entity_id = con.id AND ft.entity_table =
475 * 'civicrm_contribution'
476 * LEFT JOIN civicrm_financial_trxn fte ON fte.id = ft.financial_trxn_id
478 * @param int $entityID
479 * @param string $component
481 * @param string $type
482 * Type of payment information to be retrieved.
484 * @return int|array|object
486 public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
488 if (!in_array($component, [
497 if ($component == 'membership') {
499 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
500 FROM civicrm_membership mem
501 INNER JOIN civicrm_membership_payment mp ON ( mem.id = mp.membership_id )
502 INNER JOIN civicrm_contribution con ON ( mp.contribution_id = con.id )
503 LEFT JOIN civicrm_contribution_recur cr ON ( mem.contribution_recur_id = cr.id )
504 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
505 WHERE mp.membership_id = %1";
507 elseif ($component == 'contribute') {
509 SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test
510 FROM civicrm_contribution con
511 LEFT JOIN civicrm_contribution_recur cr ON ( con.contribution_recur_id = cr.id )
512 LEFT JOIN civicrm_contribution_page cp ON ( con.contribution_page_id = cp.id )
515 elseif ($component == 'recur') {
516 // @deprecated - use getPaymentProcessorForRecurringContribution.
518 SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
519 FROM civicrm_contribution_recur cr
523 // We are interested in a single record.
526 $params = [1 => [$entityID, 'Integer']];
527 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
529 if (!$dao->fetch()) {
535 $ppID = (isset($dao->ppID1
) && $dao->ppID1
) ?
$dao->ppID1
: (isset($dao->ppID2
) ?
$dao->ppID2
: NULL);
536 $mode = (isset($dao->is_test
) && $dao->is_test
) ?
'test' : 'live';
537 if (!$ppID ||
$type == 'id') {
540 elseif ($type == 'info') {
541 $result = self
::getPayment($ppID, $mode);
543 elseif ($type == 'obj' && is_numeric($ppID)) {
545 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
547 catch (API_Exception
$e) {
548 // Unable to load the processor because this function uses an unreliable method to derive it.
549 // The function looks to load the payment processor ID from the contribution page, which
550 // can support multiple processors.
553 $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant
::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
554 $result = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
560 * Get the payment processor associated with a recurring contribution series.
562 * @param int $contributionRecurID
564 * @return \CRM_Core_Payment
566 public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
567 $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
568 'id' => $contributionRecurID,
569 'return' => 'payment_processor_id',
571 return Civi\Payment\System
::singleton()->getById($paymentProcessorId);
575 * Get the name of the payment processor
577 * @param $paymentProcessorId
579 * @return null|string
581 public static function getPaymentProcessorName($paymentProcessorId) {
583 $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
584 'return' => ['name'],
585 'id' => $paymentProcessorId,
587 return $paymentProcessor['name'];
589 catch (Exception
$e) {
590 return ts('Unknown') . ' (' . $paymentProcessorId . ')';
595 * Generate and assign an arbitrary value to a field of a test object.
597 * @param string $fieldName
598 * @param array $fieldDef
599 * @param int $counter
600 * The globally-unique ID of the test object.
602 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
603 if ($fieldName === 'class_name') {
604 $this->class_name
= 'Payment_Dummy';
607 parent
::assignTestValue($fieldName, $fieldDef, $counter);
612 * Get the default financial account id for payment processor accounts.
614 * Note that there is only a 'name' field & no label field. If people customise
615 * name then this won't work. This is new best-effort functionality so that's non-regressive.
617 * The fix for that is to add a label value to the financial account table.
619 public static function getDefaultFinancialAccountID() {
620 return CRM_Core_PseudoConstant
::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');