Merge pull request #17595 from eileenmcnaughton/settings
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api exposes CiviCRM Contribution records.
14 *
15 * @package CiviCRM_APIv3
16 */
17
18 /**
19 * Add or update a Contribution.
20 *
21 * @param array $params
22 * Input parameters.
23 *
24 * @throws API_Exception
25 * @return array
26 * Api result array
27 */
28 function civicrm_api3_contribution_create($params) {
29 $values = [];
30 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
31 $params = array_merge($params, $values);
32 // The BAO should not clean money - it should be done in the form layer & api wrapper
33 // (although arguably the api should expect pre-cleaned it seems to do some cleaning.)
34 if (empty($params['skipCleanMoney'])) {
35 foreach (['total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount'] as $field) {
36 if (isset($params[$field])) {
37 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
38 }
39 }
40 }
41 $params['skipCleanMoney'] = TRUE;
42
43 if (!empty($params['check_permissions']) && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
44 if (empty($params['id'])) {
45 $op = CRM_Core_Action::ADD;
46 }
47 else {
48 if (empty($params['financial_type_id'])) {
49 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['id'], 'financial_type_id');
50 }
51 $op = CRM_Core_Action::UPDATE;
52 }
53 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
54 if (!in_array($params['financial_type_id'], array_keys($types))) {
55 throw new API_Exception('You do not have permission to create this contribution');
56 }
57 }
58 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
59 $error = [];
60 //throw error for invalid status change such as setting completed back to pending
61 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
62 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
63 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
64 if (array_key_exists('contribution_status_id', $error)) {
65 throw new API_Exception($error['contribution_status_id']);
66 }
67 }
68 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
69 $error = [];
70 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
71 if (array_key_exists('financial_type_id', $error)) {
72 throw new API_Exception($error['financial_type_id']);
73 }
74 }
75 _civicrm_api3_contribution_create_legacy_support_45($params);
76
77 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
78 }
79
80 /**
81 * Adjust Metadata for Create action.
82 *
83 * The metadata is used for setting defaults, documentation & validation.
84 *
85 * @param array $params
86 * Array of parameters determined by getfields.
87 */
88 function _civicrm_api3_contribution_create_spec(&$params) {
89 $params['contact_id']['api.required'] = 1;
90 $params['total_amount']['api.required'] = 1;
91 $params['payment_instrument_id']['api.aliases'] = ['payment_instrument'];
92 $params['receive_date']['api.default'] = 'now';
93 $params['receive_date']['api.required'] = TRUE;
94 $params['payment_processor'] = [
95 'name' => 'payment_processor',
96 'title' => 'Payment Processor ID',
97 'description' => 'ID of payment processor used for this contribution',
98 // field is called payment processor - not payment processor id but can only be one id so
99 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
100 'api.aliases' => ['payment_processor_id'],
101 'type' => CRM_Utils_Type::T_INT,
102 ];
103 $params['financial_type_id']['api.aliases'] = ['contribution_type_id', 'contribution_type'];
104 $params['financial_type_id']['api.required'] = 1;
105 $params['note'] = [
106 'name' => 'note',
107 'uniqueName' => 'contribution_note',
108 'title' => 'note',
109 'type' => 2,
110 'description' => 'Associated Note in the notes table',
111 ];
112 $params['soft_credit_to'] = [
113 'name' => 'soft_credit_to',
114 'title' => 'Soft Credit contact ID (legacy)',
115 'type' => CRM_Utils_Type::T_INT,
116 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
117 'FKClassName' => 'CRM_Contact_DAO_Contact',
118 ];
119 $params['honor_contact_id'] = [
120 'name' => 'honor_contact_id',
121 'title' => 'Honoree contact ID (legacy)',
122 'type' => CRM_Utils_Type::T_INT,
123 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
124 'FKClassName' => 'CRM_Contact_DAO_Contact',
125 ];
126 $params['honor_type_id'] = [
127 'name' => 'honor_type_id',
128 'title' => 'Honoree Type (legacy)',
129 'type' => CRM_Utils_Type::T_INT,
130 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
131 'pseudoconstant' => TRUE,
132 ];
133 // note this is a recommended option but not adding as a default to avoid
134 // creating unnecessary changes for the dev
135 $params['skipRecentView'] = [
136 'name' => 'skipRecentView',
137 'title' => 'Skip adding to recent view',
138 'type' => CRM_Utils_Type::T_BOOLEAN,
139 'description' => 'Do not add to recent view (setting this improves performance)',
140 ];
141 $params['skipLineItem'] = [
142 'name' => 'skipLineItem',
143 'title' => 'Skip adding line items',
144 'type' => CRM_Utils_Type::T_BOOLEAN,
145 'api.default' => 0,
146 'description' => 'Do not add line items by default (if you wish to add your own)',
147 ];
148 $params['batch_id'] = [
149 'title' => 'Batch',
150 'type' => CRM_Utils_Type::T_INT,
151 'description' => 'Batch which relevant transactions should be added to',
152 ];
153 $params['refund_trxn_id'] = [
154 'title' => 'Refund Transaction ID',
155 'type' => CRM_Utils_Type::T_STRING,
156 'description' => 'Transaction ID specific to the refund taking place',
157 ];
158 $params['card_type_id'] = [
159 'title' => 'Card Type ID',
160 'description' => 'Providing Credit Card Type ID',
161 'type' => CRM_Utils_Type::T_INT,
162 'pseudoconstant' => [
163 'optionGroupName' => 'accept_creditcard',
164 ],
165 ];
166 }
167
168 /**
169 * Support for schema changes made in 4.5.
170 *
171 * The main purpose of the API is to provide integrators a level of stability not provided by
172 * the core code or schema - this means we have to provide support for api calls (where possible)
173 * across schema changes.
174 *
175 * @param array $params
176 */
177 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
178 //legacy soft credit handling - recommended approach is chaining
179 if (!empty($params['soft_credit_to'])) {
180 $params['soft_credit'][] = [
181 'contact_id' => $params['soft_credit_to'],
182 'amount' => $params['total_amount'],
183 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
184 ];
185 }
186 if (!empty($params['honor_contact_id'])) {
187 $params['soft_credit'][] = [
188 'contact_id' => $params['honor_contact_id'],
189 'amount' => $params['total_amount'],
190 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'in_honor_of')),
191 ];
192 }
193 }
194
195 /**
196 * Delete a Contribution.
197 *
198 * @param array $params
199 * Input parameters.
200 *
201 * @return array
202 * @throws \API_Exception
203 */
204 function civicrm_api3_contribution_delete($params) {
205
206 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
207 // First check contribution financial type
208 $financialType = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
209 // Now check permissioned lineitems & permissioned contribution
210 if (!empty($params['check_permissions']) && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() &&
211 (
212 !CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($financialType))
213 || !CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($contributionID, 'delete', FALSE)
214 )
215 ) {
216 throw new API_Exception('You do not have permission to delete this contribution');
217 }
218 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
219 return civicrm_api3_create_success([$contributionID => 1]);
220 }
221 else {
222 throw new API_Exception('Could not delete contribution');
223 }
224 }
225
226 /**
227 * Modify metadata for delete action.
228 *
229 * Legacy support for contribution_id.
230 *
231 * @param array $params
232 */
233 function _civicrm_api3_contribution_delete_spec(&$params) {
234 $params['id']['api.aliases'] = ['contribution_id'];
235 }
236
237 /**
238 * Retrieve a set of contributions.
239 *
240 * @param array $params
241 * Input parameters.
242 *
243 * @return array
244 * Array of contributions, if error an array with an error id and error message
245 */
246 function civicrm_api3_contribution_get($params) {
247
248 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
249 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
250 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
251
252 // Get the contributions based on parameters passed in
253 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
254 if (!empty($contributions)) {
255 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftCreditContributionFields(array_keys($contributions), TRUE);
256 foreach ($contributions as $id => $contribution) {
257 $contributions[$id] = isset($softContributions[$id]) ? array_merge($contribution, $softContributions[$id]) : $contribution;
258 // format soft credit for backward compatibility
259 _civicrm_api3_format_soft_credit($contributions[$id]);
260 _civicrm_api3_contribution_add_supported_fields($contributions[$id]);
261 }
262 }
263 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
264 }
265
266 /**
267 * Fix the return values to reflect cases where the schema has been changed.
268 *
269 * At the query object level using uniquenames dismbiguates between tables.
270 *
271 * However, adding uniquename can change inputs accepted by the api, so we need
272 * to ensure we are asking for the unique name return fields.
273 *
274 * @param array $params
275 *
276 * @return array
277 * @throws \API_Exception
278 */
279 function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
280 $additionalOptions = [];
281 $options = _civicrm_api3_get_options_from_params($params, TRUE);
282 foreach (['check_number', 'address_id', 'cancel_date'] as $changedVariable) {
283 if (isset($options['return']) && !empty($options['return'][$changedVariable])) {
284 $additionalOptions['return']['contribution_' . $changedVariable] = 1;
285 }
286 }
287 return $additionalOptions;
288 }
289
290 /**
291 * Support for supported output variables.
292 *
293 * @param $contribution
294 */
295 function _civicrm_api3_contribution_add_supported_fields(&$contribution) {
296 // These are output fields that are supported in our test contract.
297 // Arguably we should also do the same with 'campaign_id' &
298 // 'source' - which are also fields being rendered with unique names.
299 // That seems more consistent with other api where we output the actual field names.
300 $outputAliases = [
301 'contribution_check_number' => 'check_number',
302 'contribution_address_id' => 'address_id',
303 'payment_instrument_id' => 'instrument_id',
304 'contribution_cancel_date' => 'cancel_date',
305 ];
306 foreach ($outputAliases as $returnName => $copyTo) {
307 if (array_key_exists($returnName, $contribution)) {
308 $contribution[$copyTo] = $contribution[$returnName];
309 }
310 }
311
312 }
313
314 /**
315 * Get number of contacts matching the supplied criteria.
316 *
317 * @param array $params
318 *
319 * @return int
320 */
321 function civicrm_api3_contribution_getcount($params) {
322 $count = _civicrm_api3_get_using_query_object('Contribution', $params, [], TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
323 return (int) $count;
324 }
325
326 /**
327 * This function is used to format the soft credit for backward compatibility.
328 *
329 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
330 * but we still return first soft credit as a part of contribution array
331 *
332 * @param $contribution
333 */
334 function _civicrm_api3_format_soft_credit(&$contribution) {
335 if (!empty($contribution['soft_credit'])) {
336 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
337 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
338 }
339 }
340
341 /**
342 * Adjust Metadata for Get action.
343 *
344 * The metadata is used for setting defaults, documentation & validation.
345 *
346 * @param array $params
347 * Array of parameters determined by getfields.
348 */
349 function _civicrm_api3_contribution_get_spec(&$params) {
350 $params['contribution_test'] = [
351 'api.default' => 0,
352 'type' => CRM_Utils_Type::T_BOOLEAN,
353 'title' => 'Get Test Contributions?',
354 'api.aliases' => ['is_test'],
355 ];
356
357 $params['financial_type_id']['api.aliases'] = ['contribution_type_id'];
358 $params['payment_instrument_id']['api.aliases'] = ['contribution_payment_instrument', 'payment_instrument'];
359 $params['contact_id'] = $params['contribution_contact_id'] ?? NULL;
360 $params['contact_id']['api.aliases'] = ['contribution_contact_id'];
361 $params['is_template']['api.default'] = 0;
362 unset($params['contribution_contact_id']);
363 }
364
365 /**
366 * Legacy handling for contribution parameters.
367 *
368 * Take the input parameter list as specified in the data model and
369 * convert it into the same format that we use in QF and BAO object.
370 *
371 * @param array $params
372 * property name/value pairs to insert in new contact.
373 * @param array $values
374 * The reformatted properties that we can use internally.
375 *
376 * @return array
377 */
378 function _civicrm_api3_contribute_format_params($params, &$values) {
379 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
380 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
381 return [];
382 }
383
384 /**
385 * Send a contribution confirmation (receipt or invoice).
386 *
387 * The appropriate online template will be used (the existence of related objects
388 * (e.g. memberships ) will affect this selection
389 *
390 * @param array $params
391 * Input parameters.
392 *
393 * @throws Exception
394 */
395 function civicrm_api3_contribution_sendconfirmation($params) {
396 $ids = [];
397 $allowedParams = [
398 'receipt_from_email',
399 'receipt_from_name',
400 'receipt_update',
401 'cc_receipt',
402 'bcc_receipt',
403 'receipt_text',
404 'payment_processor_id',
405 ];
406 $input = array_intersect_key($params, array_flip($allowedParams));
407 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id']);
408 }
409
410 /**
411 * Adjust Metadata for sendconfirmation action.
412 *
413 * The metadata is used for setting defaults, documentation & validation.
414 *
415 * @param array $params
416 * Array of parameters determined by getfields.
417 */
418 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
419 $params['id'] = [
420 'api.required' => 1,
421 'title' => ts('Contribution ID'),
422 'type' => CRM_Utils_Type::T_INT,
423 ];
424 $params['receipt_from_email'] = [
425 'title' => ts('From Email address (string)'),
426 'type' => CRM_Utils_Type::T_STRING,
427 ];
428 $params['receipt_from_name'] = [
429 'title' => ts('From Name (string)'),
430 'type' => CRM_Utils_Type::T_STRING,
431 ];
432 $params['cc_receipt'] = [
433 'title' => ts('CC Email address (string)'),
434 'type' => CRM_Utils_Type::T_STRING,
435 ];
436 $params['bcc_receipt'] = [
437 'title' => ts('BCC Email address (string)'),
438 'type' => CRM_Utils_Type::T_STRING,
439 ];
440 $params['receipt_text'] = [
441 'title' => ts('Message (string)'),
442 'type' => CRM_Utils_Type::T_STRING,
443 ];
444 $params['receipt_update'] = [
445 'title' => ts('Update the Receipt Date'),
446 'type' => CRM_Utils_Type::T_BOOLEAN,
447 'api.default' => TRUE,
448 ];
449 $params['payment_processor_id'] = [
450 'title' => ts('Payment processor Id (avoids mis-guesses)'),
451 'type' => CRM_Utils_Type::T_INT,
452 ];
453 }
454
455 /**
456 * Complete an existing (pending) transaction.
457 *
458 * This will update related entities (participant, membership, pledge etc)
459 * and take any complete actions from the contribution page (e.g. send receipt).
460 *
461 * @todo - most of this should live in the BAO layer but as we want it to be an addition
462 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
463 *
464 * @param array $params
465 * Input parameters.
466 *
467 * @return array
468 * API result array
469 * @throws \API_Exception
470 * @throws \CRM_Core_Exception
471 * @throws \Exception
472 */
473 function civicrm_api3_contribution_completetransaction($params) {
474 $input = $ids = [];
475
476 $contribution = new CRM_Contribute_BAO_Contribution();
477 $contribution->id = $params['id'];
478 if (!$contribution->find(TRUE)) {
479 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
480 }
481
482 if (isset($params['payment_processor_id'])) {
483 $input['payment_processor_id'] = $params['payment_processor_id'];
484 }
485 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
486 throw new API_Exception('failed to load related objects');
487 }
488 elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
489 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
490 }
491 $params['trxn_id'] = $params['trxn_id'] ?? $contribution->trxn_id;
492
493 $passThroughParams = [
494 'fee_amount',
495 'payment_processor_id',
496 'trxn_id',
497 ];
498 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
499
500 return _ipn_process_transaction($params, $contribution, $input, $ids);
501 }
502
503 /**
504 * Provide function metadata.
505 *
506 * @param array $params
507 */
508 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
509 $params['id'] = [
510 'title' => 'Contribution ID',
511 'type' => CRM_Utils_Type::T_INT,
512 'api.required' => TRUE,
513 ];
514 $params['trxn_id'] = [
515 'title' => 'Transaction ID',
516 'type' => CRM_Utils_Type::T_STRING,
517 ];
518 $params['is_email_receipt'] = [
519 'title' => 'Send email Receipt?',
520 'type' => CRM_Utils_Type::T_BOOLEAN,
521 ];
522 $params['receipt_from_email'] = [
523 'title' => 'Email to send receipt from.',
524 'description' => 'If not provided this will default to being based on domain mail or contribution page',
525 'type' => CRM_Utils_Type::T_EMAIL,
526 ];
527 $params['receipt_from_name'] = [
528 'title' => 'Name to send receipt from',
529 'description' => '. If not provided this will default to domain mail or contribution page',
530 'type' => CRM_Utils_Type::T_STRING,
531 ];
532 $params['payment_processor_id'] = [
533 'title' => 'Payment processor ID',
534 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
535 'type' => CRM_Utils_Type::T_INT,
536 ];
537 $params['fee_amount'] = [
538 'title' => 'Fee charged on transaction',
539 'description' => 'If a fee has been charged then the amount',
540 'type' => CRM_Utils_Type::T_FLOAT,
541 ];
542 $params['trxn_date'] = [
543 'title' => 'Transaction Date',
544 'description' => 'Date this transaction occurred',
545 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
546 ];
547 $params['card_type_id'] = [
548 'title' => 'Card Type ID',
549 'description' => 'Providing Credit Card Type ID',
550 'type' => CRM_Utils_Type::T_INT,
551 'pseudoconstant' => [
552 'optionGroupName' => 'accept_creditcard',
553 ],
554 ];
555 // At some point we will deprecate this api in favour of calling payment create which will in turn call this
556 // api if appropriate to transition related entities and send receipts - ie. financial responsibility should
557 // not exist in completetransaction. For now we just need to allow payment.create to force a bypass on the
558 // things it does itself.
559 $params['is_post_payment_create'] = [
560 'title' => 'Is this being called from payment create?',
561 'type' => CRM_Utils_Type::T_BOOLEAN,
562 'description' => 'The \'correct\' flow is to call payment.create for the financial side & for that to call completecontribution for the entity & receipt management. However, we need to still support completetransaction directly for legacy reasons',
563 ];
564 }
565
566 /**
567 * Complete an existing (pending) transaction.
568 *
569 * This will update related entities (participant, membership, pledge etc)
570 * and take any complete actions from the contribution page (e.g. send receipt).
571 *
572 * @todo - most of this should live in the BAO layer but as we want it to be an addition
573 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
574 *
575 * @param array $params
576 * Input parameters.
577 *
578 * @return array
579 * Api result array.
580 * @throws API_Exception
581 */
582 function civicrm_api3_contribution_repeattransaction($params) {
583 $input = $ids = [];
584 civicrm_api3_verify_one_mandatory($params, NULL, ['contribution_recur_id', 'original_contribution_id']);
585 if (empty($params['original_contribution_id'])) {
586 // CRM-19873 call with test mode.
587 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', [
588 'return' => 'id',
589 'contribution_status_id' => ['IN' => ['Completed']],
590 'contribution_recur_id' => $params['contribution_recur_id'],
591 'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
592 'options' => ['limit' => 1, 'sort' => 'id DESC'],
593 ]);
594 }
595 $contribution = new CRM_Contribute_BAO_Contribution();
596 $contribution->id = $params['original_contribution_id'];
597 if (!$contribution->find(TRUE)) {
598 throw new API_Exception(
599 'A valid original contribution ID is required', 'invalid_data');
600 }
601 // We don't support repeattransaction without a related recurring contribution.
602 if (empty($contribution->contribution_recur_id)) {
603 throw new API_Exception(
604 'Repeattransaction API can only be used in the context of contributions that have a contribution_recur_id.',
605 'invalid_data'
606 );
607 }
608
609 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', [
610 'return' => 'payment_processor_id',
611 'id' => $contribution->contribution_recur_id,
612 ]);
613 try {
614 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
615 throw new API_Exception('failed to load related objects');
616 }
617
618 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
619 $contribution->receive_date = $params['receive_date'];
620
621 $passThroughParams = [
622 'trxn_id',
623 'total_amount',
624 'campaign_id',
625 'fee_amount',
626 'financial_type_id',
627 'contribution_status_id',
628 'membership_id',
629 ];
630 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
631
632 return _ipn_process_transaction($params, $contribution, $input, $ids);
633 }
634 catch (Exception $e) {
635 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
636 }
637 }
638
639 /**
640 * Calls IPN complete transaction for completing or repeating a transaction.
641 *
642 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
643 * when separating them in the api layer.
644 *
645 * @param array $params
646 * @param CRM_Contribute_BAO_Contribution $contribution
647 * @param array $input
648 *
649 * @param array $ids
650 *
651 * @return mixed
652 * @throws \CRM_Core_Exception
653 * @throws \CiviCRM_API3_Exception
654 */
655 function _ipn_process_transaction($params, $contribution, $input, $ids) {
656 $objects = $contribution->_relatedObjects;
657 $objects['contribution'] = &$contribution;
658 $input['component'] = $contribution->_component;
659 $input['is_test'] = $contribution->is_test;
660 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
661
662 if (isset($params['is_email_receipt'])) {
663 $input['is_email_receipt'] = $params['is_email_receipt'];
664 }
665 if (!empty($params['trxn_date'])) {
666 $input['trxn_date'] = $params['trxn_date'];
667 }
668 if (!empty($params['receive_date'])) {
669 $input['receive_date'] = $params['receive_date'];
670 }
671 if (empty($contribution->contribution_page_id)) {
672 static $domainFromName;
673 static $domainFromEmail;
674 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
675 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
676 }
677 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
678 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
679 }
680 $input['card_type_id'] = $params['card_type_id'] ?? NULL;
681 $input['pan_truncation'] = $params['pan_truncation'] ?? NULL;
682 if (!empty($params['payment_instrument_id'])) {
683 $input['payment_instrument_id'] = $params['payment_instrument_id'];
684 }
685 return CRM_Contribute_BAO_Contribution::completeOrder($input, [
686 'related_contact' => $ids['related_contact'] ?? NULL,
687 'participant' => !empty($objects['participant']) ? $objects['participant']->id : NULL,
688 'contributionRecur' => !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
689 ], $objects,
690 $params['is_post_payment_create'] ?? NULL);
691 }
692
693 /**
694 * Provide function metadata.
695 *
696 * @param array $params
697 */
698 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
699 $params['original_contribution_id'] = [
700 'title' => 'Original Contribution ID',
701 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
702 'type' => CRM_Utils_Type::T_INT,
703 ];
704 $params['contribution_recur_id'] = [
705 'title' => 'Recurring contribution ID',
706 'type' => CRM_Utils_Type::T_INT,
707 ];
708 $params['trxn_id'] = [
709 'title' => 'Transaction ID',
710 'type' => CRM_Utils_Type::T_STRING,
711 ];
712 $params['is_email_receipt'] = [
713 'title' => 'Send email Receipt?',
714 'type' => CRM_Utils_Type::T_BOOLEAN,
715 ];
716 $params['contribution_status_id'] = [
717 'title' => 'Contribution Status ID',
718 'name' => 'contribution_status_id',
719 'type' => CRM_Utils_Type::T_INT,
720 'pseudoconstant' => [
721 'optionGroupName' => 'contribution_status',
722 ],
723 'api.required' => TRUE,
724 'api.default' => 'Pending',
725 ];
726 $params['receive_date'] = [
727 'title' => 'Contribution Receive Date',
728 'name' => 'receive_date',
729 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
730 'api.default' => 'now',
731 ];
732 $params['trxn_id'] = [
733 'title' => 'Transaction ID',
734 'name' => 'trxn_id',
735 'type' => CRM_Utils_Type::T_STRING,
736 ];
737 $params['campaign_id'] = [
738 'title' => 'Campaign ID',
739 'name' => 'campaign_id',
740 'type' => CRM_Utils_Type::T_INT,
741 'pseudoconstant' => [
742 'table' => 'civicrm_campaign',
743 'keyColumn' => 'id',
744 'labelColumn' => 'title',
745 ],
746 ];
747 $params['financial_type_id'] = [
748 'title' => 'Financial ID (ignored if more than one line item)',
749 'name' => 'financial_type_id',
750 'type' => CRM_Utils_Type::T_INT,
751 'pseudoconstant' => [
752 'table' => 'civicrm_financial_type',
753 'keyColumn' => 'id',
754 'labelColumn' => 'name',
755 ],
756 ];
757 $params['payment_processor_id'] = [
758 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
759 'title' => 'Payment processor ID',
760 'name' => 'payment_processor_id',
761 'type' => CRM_Utils_Type::T_INT,
762 ];
763 }
764
765 /**
766 * Declare deprecated functions.
767 *
768 * @return array
769 * Array of deprecated actions
770 */
771 function _civicrm_api3_contribution_deprecation() {
772 return ['transact' => 'Contribute.transact is ureliable & unsupported - see https://docs.civicrm.org/dev/en/latest/financial/OrderAPI/ for how to move on'];
773 }