3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This api exposes CiviCRM Contribution records.
31 * @package CiviCRM_APIv3
35 * Add or update a Contribution.
37 * @param array $params
40 * @throws API_Exception
44 function civicrm_api3_contribution_create(&$params) {
46 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
47 $params = array_merge($params, $values);
49 if (empty($params['id'])) {
55 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types, $op);
56 if (!in_array($params['financial_type_id'], array_keys($types))) {
57 return civicrm_api3_create_error('You do not have permission to create this contribution');
60 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
62 //throw error for invalid status change such as setting completed back to pending
63 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
64 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
65 CRM_Contribute_BAO_Contribution
::checkStatusValidation(NULL, $params, $error);
66 if (array_key_exists('contribution_status_id', $error)) {
67 throw new API_Exception($error['contribution_status_id']);
70 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
72 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
73 if (array_key_exists('financial_type_id', $error)) {
74 throw new API_Exception($error['financial_type_id']);
77 _civicrm_api3_contribution_create_legacy_support_45($params);
79 // Make sure tax calculation is handled via api.
80 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
82 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Contribution');
86 * Adjust Metadata for Create action.
88 * The metadata is used for setting defaults, documentation & validation.
90 * @param array $params
91 * Array of parameters determined by getfields.
93 function _civicrm_api3_contribution_create_spec(&$params) {
94 $params['contact_id']['api.required'] = 1;
95 $params['total_amount']['api.required'] = 1;
96 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
97 $params['receive_date']['api.default'] = 'now';
98 $params['payment_processor'] = array(
99 'name' => 'payment_processor',
100 'title' => 'Payment Processor ID',
101 'description' => 'ID of payment processor used for this contribution',
102 // field is called payment processor - not payment processor id but can only be one id so
103 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
104 'api.aliases' => array('payment_processor_id'),
105 'type' => CRM_Utils_Type
::T_INT
,
107 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
108 $params['financial_type_id']['api.required'] = 1;
109 $params['note'] = array(
111 'uniqueName' => 'contribution_note',
114 'description' => 'Associated Note in the notes table',
116 $params['soft_credit_to'] = array(
117 'name' => 'soft_credit_to',
118 'title' => 'Soft Credit contact ID (legacy)',
120 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
121 'FKClassName' => 'CRM_Contact_DAO_Contact',
123 $params['honor_contact_id'] = array(
124 'name' => 'honor_contact_id',
125 'title' => 'Honoree contact ID (legacy)',
127 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
128 'FKClassName' => 'CRM_Contact_DAO_Contact',
130 $params['honor_type_id'] = array(
131 'name' => 'honor_type_id',
132 'title' => 'Honoree Type (legacy)',
134 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
135 'pseudoconstant' => TRUE,
137 // note this is a recommended option but not adding as a default to avoid
138 // creating unnecessary changes for the dev
139 $params['skipRecentView'] = array(
140 'name' => 'skipRecentView',
141 'title' => 'Skip adding to recent view',
142 'type' => CRM_Utils_Type
::T_BOOLEAN
,
143 'description' => 'Do not add to recent view (setting this improves performance)',
145 $params['skipLineItem'] = array(
146 'name' => 'skipLineItem',
147 'title' => 'Skip adding line items',
148 'type' => CRM_Utils_Type
::T_BOOLEAN
,
150 'description' => 'Do not add line items by default (if you wish to add your own)',
152 $params['batch_id'] = array(
155 'description' => 'Batch which relevant transactions should be added to',
160 * Support for schema changes made in 4.5.
162 * The main purpose of the API is to provide integrators a level of stability not provided by
163 * the core code or schema - this means we have to provide support for api calls (where possible)
164 * across schema changes.
166 * @param array $params
168 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
169 //legacy soft credit handling - recommended approach is chaining
170 if (!empty($params['soft_credit_to'])) {
171 $params['soft_credit'][] = array(
172 'contact_id' => $params['soft_credit_to'],
173 'amount' => $params['total_amount'],
174 'soft_credit_type_id' => CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"),
177 if (!empty($params['honor_contact_id'])) {
178 $params['soft_credit'][] = array(
179 'contact_id' => $params['honor_contact_id'],
180 'amount' => $params['total_amount'],
181 'soft_credit_type_id' => CRM_Utils_Array
::value('honor_type_id', $params, CRM_Core_OptionGroup
::getValue('soft_credit_type', 'in_honor_of', 'name')),
187 * Delete a Contribution.
189 * @param array $params
194 function civicrm_api3_contribution_delete($params) {
196 $contributionID = !empty($params['contribution_id']) ?
$params['contribution_id'] : $params['id'];
197 // First check contribution financial type
198 $financialType = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
199 // Now check permissioned lineitems & permissioned contribution
200 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
201 && !CRM_Core_Permission
::check('delete contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($financialType)) ||
202 !CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($contributionID, 'delete', FALSE)
204 return civicrm_api3_create_error('You do not have permission to delete this contribution');
206 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
207 return civicrm_api3_create_success(array($contributionID => 1));
210 return civicrm_api3_create_error('Could not delete contribution');
215 * Modify metadata for delete action.
217 * Legacy support for contribution_id.
219 * @param array $params
221 function _civicrm_api3_contribution_delete_spec(&$params) {
222 $params['id']['api.aliases'] = array('contribution_id');
226 * Retrieve a set of contributions.
228 * @param array $params
232 * Array of contributions, if error an array with an error id and error message
234 function civicrm_api3_contribution_get($params) {
236 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
237 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
239 $contribution = array();
240 while ($dao->fetch()) {
242 $contribution_details = $query->store($dao);
243 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
244 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
245 // format soft credit for backward compatibility
246 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
248 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
252 * This function is used to format the soft credit for backward compatibility.
254 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
255 * but we still return first soft credit as a part of contribution array
257 * @param $contribution
259 function _civicrm_api3_format_soft_credit(&$contribution) {
260 if (!empty($contribution['soft_credit'])) {
261 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
262 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
267 * Adjust Metadata for Get action.
269 * The metadata is used for setting defaults, documentation & validation.
271 * @param array $params
272 * Array of parameters determined by getfields.
274 function _civicrm_api3_contribution_get_spec(&$params) {
275 $params['contribution_test'] = array(
277 'type' => CRM_Utils_Type
::T_BOOLEAN
,
278 'title' => 'Get Test Contributions?',
279 'api.aliases' => array('is_test'),
282 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
283 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
284 $params['contact_id'] = $params['contribution_contact_id'];
285 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
286 unset($params['contribution_contact_id']);
290 * Legacy handling for contribution parameters.
292 * Take the input parameter list as specified in the data model and
293 * convert it into the same format that we use in QF and BAO object.
295 * @param array $params
296 * property name/value pairs to insert in new contact.
297 * @param array $values
298 * The reformatted properties that we can use internally.
302 function _civicrm_api3_contribute_format_params($params, &$values) {
303 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
304 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
309 * Adjust Metadata for Transact action.
311 * The metadata is used for setting defaults, documentation & validation.
313 * @param array $params
314 * Array of parameters determined by getfields.
316 function _civicrm_api3_contribution_transact_spec(&$params) {
317 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
318 $params = array_merge($params, $fields['values']);
319 $params['receive_date']['api.default'] = 'now';
323 * Process a transaction and record it against the contact.
325 * @param array $params
329 * contribution of created or updated record (or a civicrm error)
331 function civicrm_api3_contribution_transact($params) {
332 // Set some params specific to payment processing
333 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
335 // also trxn_id is not saved.
336 // but since there is no test it's not desirable to jump in & make the obvious changes.
337 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
338 $params['amount'] = $params['total_amount'];
339 if (!isset($params['net_amount'])) {
340 $params['net_amount'] = $params['amount'];
342 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
343 $params['invoiceID'] = $params['invoice_id'];
346 // Some payment processors expect a unique invoice_id - generate one if not supplied
347 $params['invoice_id'] = CRM_Utils_Array
::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
349 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
350 $paymentProcessor['object']->doPayment($params);
352 $params['payment_instrument_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ?
'Credit Card' : 'Debit Card';
353 return civicrm_api('Contribution', 'create', $params);
357 * Send a contribution confirmation (receipt or invoice).
359 * The appropriate online template will be used (the existence of related objects
360 * (e.g. memberships ) will affect this selection
362 * @param array $params
367 function civicrm_api3_contribution_sendconfirmation($params) {
368 $contribution = new CRM_Contribute_BAO_Contribution();
369 $contribution->id
= $params['id'];
370 if (!$contribution->find(TRUE)) {
371 throw new Exception('Contribution does not exist');
373 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
374 $contribution->loadRelatedObjects($input, $ids, TRUE);
375 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
379 * Adjust Metadata for sendconfirmation action.
381 * The metadata is used for setting defaults, documentation & validation.
383 * @param array $params
384 * Array of parameters determined by getfields.
386 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
387 $params['id'] = array(
389 'title' => 'Contribution ID',
390 'type' => CRM_Utils_Type
::T_INT
,
392 $params['receipt_from_email'] = array(
394 'title' => 'From Email address (string) required until someone provides a patch :-)',
395 'type' => CRM_Utils_Type
::T_STRING
,
397 $params['receipt_from_name'] = array(
398 'title' => 'From Name (string)',
399 'type' => CRM_Utils_Type
::T_STRING
,
401 $params['cc_receipt'] = array(
402 'title' => 'CC Email address (string)',
403 'type' => CRM_Utils_Type
::T_STRING
,
405 $params['bcc_receipt'] = array(
406 'title' => 'BCC Email address (string)',
407 'type' => CRM_Utils_Type
::T_STRING
,
409 $params['receipt_text'] = array(
410 'title' => 'Message (string)',
411 'type' => CRM_Utils_Type
::T_STRING
,
416 * Complete an existing (pending) transaction.
418 * This will update related entities (participant, membership, pledge etc)
419 * and take any complete actions from the contribution page (e.g. send receipt).
421 * @todo - most of this should live in the BAO layer but as we want it to be an addition
422 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
424 * @param array $params
427 * @throws API_Exception
430 function civicrm_api3_contribution_completetransaction(&$params) {
432 $input = $ids = array();
433 if (isset($params['payment_processor_id'])) {
434 $input['payment_processor_id'] = $params['payment_processor_id'];
436 $contribution = new CRM_Contribute_BAO_Contribution();
437 $contribution->id
= $params['id'];
438 $contribution->find(TRUE);
439 if (!$contribution->id
== $params['id']) {
440 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
443 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
444 throw new API_Exception('failed to load related objects');
446 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
447 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
449 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
450 if (!empty($params['fee_amount'])) {
451 $input['fee_amount'] = $params['fee_amount'];
453 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
458 * Provide function metadata.
460 * @param array $params
462 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
463 $params['id'] = array(
464 'title' => 'Contribution ID',
465 'type' => CRM_Utils_Type
::T_INT
,
466 'api.required' => TRUE,
468 $params['trxn_id'] = array(
469 'title' => 'Transaction ID',
470 'type' => CRM_Utils_Type
::T_STRING
,
472 $params['is_email_receipt'] = array(
473 'title' => 'Send email Receipt?',
474 'type' => CRM_Utils_Type
::T_BOOLEAN
,
476 $params['receipt_from_email'] = array(
477 'title' => 'Email to send receipt from.',
478 'description' => 'If not provided this will default to being based on domain mail or contribution page',
479 'type' => CRM_Utils_Type
::T_EMAIL
,
481 $params['receipt_from_name'] = array(
482 'title' => 'Name to send receipt from',
483 'description' => '. If not provided this will default to domain mail or contribution page',
484 'type' => CRM_Utils_Type
::T_STRING
,
486 $params['payment_processor_id'] = array(
487 'title' => 'Payment processor ID',
488 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
489 'type' => CRM_Utils_Type
::T_INT
,
491 $params['fee_amount'] = array(
492 'title' => 'Fee charged on transaction',
493 'description' => 'If a fee has been charged then the amount',
494 'type' => CRM_Utils_Type
::T_FLOAT
,
496 $params['trxn_date'] = array(
497 'title' => 'Transaction Date',
498 'description' => 'Date this transaction occurred',
499 'type' => CRM_Utils_Type
::T_DATE
,
504 * Complete an existing (pending) transaction.
506 * This will update related entities (participant, membership, pledge etc)
507 * and take any complete actions from the contribution page (e.g. send receipt).
509 * @todo - most of this should live in the BAO layer but as we want it to be an addition
510 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
512 * @param array $params
515 * @throws API_Exception
518 function civicrm_api3_contribution_repeattransaction(&$params) {
519 $input = $ids = array();
520 $contribution = new CRM_Contribute_BAO_Contribution();
521 $contribution->id
= $params['original_contribution_id'];
522 if (!$contribution->find(TRUE)) {
523 throw new API_Exception(
524 'A valid original contribution ID is required', 'invalid_data');
526 $original_contribution = clone $contribution;
528 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
529 throw new API_Exception('failed to load related objects');
532 unset($contribution->id
, $contribution->receive_date
, $contribution->invoice_id
);
533 $contribution->contribution_status_id
= $params['contribution_status_id'];
534 $contribution->receive_date
= $params['receive_date'];
536 $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount');
537 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
539 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
541 catch(Exception
$e) {
542 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
547 * Calls IPN complete transaction for completing or repeating a transaction.
549 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
550 * when separating them in the api layer.
552 * @param array $params
553 * @param CRM_Contribute_BAO_Contribution $contribution
554 * @param array $input
558 * @param CRM_Contribute_BAO_Contribution $firstContribution
562 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
563 $objects = $contribution->_relatedObjects
;
564 $objects['contribution'] = &$contribution;
566 if ($firstContribution) {
567 $objects['first_contribution'] = $firstContribution;
569 $input['component'] = $contribution->_component
;
570 $input['is_test'] = $contribution->is_test
;
571 $input['amount'] = empty($input['total_amount']) ?
$contribution->total_amount
: $input['total_amount'];
573 if (isset($params['is_email_receipt'])) {
574 $input['is_email_receipt'] = $params['is_email_receipt'];
576 if (!empty($params['trxn_date'])) {
577 $input['trxn_date'] = $params['trxn_date'];
579 if (empty($contribution->contribution_page_id
)) {
580 static $domainFromName;
581 static $domainFromEmail;
582 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) ||
empty($params['receipt_from_email']))) {
583 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE);
585 $input['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $params, $domainFromName);
586 $input['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $params, $domainFromEmail);
588 $transaction = new CRM_Core_Transaction();
589 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
), $contribution,
595 * Provide function metadata.
597 * @param array $params
599 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
600 $params['original_contribution_id'] = array(
601 'title' => 'Original Contribution ID',
602 'type' => CRM_Utils_Type
::T_INT
,
603 'api.required' => TRUE,
605 $params['trxn_id'] = array(
606 'title' => 'Transaction ID',
607 'type' => CRM_Utils_Type
::T_STRING
,
609 $params['is_email_receipt'] = array(
610 'title' => 'Send email Receipt?',
611 'type' => CRM_Utils_Type
::T_BOOLEAN
,
613 $params['contribution_status_id'] = array(
614 'title' => 'Contribution Status ID',
615 'name' => 'contribution_status_id',
616 'type' => CRM_Utils_Type
::T_INT
,
617 'pseudoconstant' => array(
618 'optionGroupName' => 'contribution_status',
620 'api.required' => TRUE,
622 $params['receive_date'] = array(
623 'title' => 'Contribution Receive Date',
624 'name' => 'receive_date',
625 'type' => CRM_Utils_Type
::T_DATE
,
626 'api.default' => 'now',
628 $params['trxn_id'] = array(
629 'title' => 'Transaction ID',
631 'type' => CRM_Utils_Type
::T_STRING
,
633 $params['payment_processor_id'] = array(
634 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
635 'title' => 'Payment processor ID',
636 'name' => 'payment_processor_id',
637 'type' => CRM_Utils_Type
::T_INT
,