3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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']) && !empty($params['contribution_status_id'])) {
51 //throw error for invalid status change such as setting completed back to pending
52 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
53 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
54 CRM_Contribute_BAO_Contribution
::checkStatusValidation(NULL, $params, $error);
55 if (array_key_exists('contribution_status_id', $error)) {
56 throw new API_Exception($error['contribution_status_id']);
60 _civicrm_api3_contribution_create_legacy_support_45($params);
62 // Make sure tax calculation is handled via api.
63 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
65 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Contribution');
69 * Adjust Metadata for Create action.
71 * The metadata is used for setting defaults, documentation & validation.
73 * @param array $params
74 * Array of parameters determined by getfields.
76 function _civicrm_api3_contribution_create_spec(&$params) {
77 $params['contact_id']['api.required'] = 1;
78 $params['total_amount']['api.required'] = 1;
79 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
80 $params['receive_date']['api.default'] = 'now';
81 $params['payment_processor'] = array(
82 'name' => 'payment_processor',
83 'title' => 'Payment Processor ID',
84 'description' => 'ID of payment processor used for this contribution',
85 // field is called payment processor - not payment processor id but can only be one id so
86 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
87 'api.aliases' => array('payment_processor_id'),
89 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
90 $params['financial_type_id']['api.required'] = 1;
91 $params['note'] = array(
93 'uniqueName' => 'contribution_note',
96 'description' => 'Associated Note in the notes table',
98 $params['soft_credit_to'] = array(
99 'name' => 'soft_credit_to',
100 'title' => 'Soft Credit contact ID (legacy)',
102 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
103 'FKClassName' => 'CRM_Contact_DAO_Contact',
105 $params['honor_contact_id'] = array(
106 'name' => 'honor_contact_id',
107 'title' => 'Honoree contact ID (legacy)',
109 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
110 'FKClassName' => 'CRM_Contact_DAO_Contact',
112 $params['honor_type_id'] = array(
113 'name' => 'honor_type_id',
114 'title' => 'Honoree Type (legacy)',
116 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
117 'pseudoconstant' => TRUE,
119 // note this is a recommended option but not adding as a default to avoid
120 // creating unnecessary changes for the dev
121 $params['skipRecentView'] = array(
122 'name' => 'skipRecentView',
123 'title' => 'Skip adding to recent view',
124 'type' => CRM_Utils_Type
::T_BOOLEAN
,
125 'description' => 'Do not add to recent view (setting this improves performance)',
127 $params['skipLineItem'] = array(
128 'name' => 'skipLineItem',
129 'title' => 'Skip adding line items',
132 'description' => 'Do not add line items by default (if you wish to add your own)',
134 $params['batch_id'] = array(
137 'description' => 'Batch which relevant transactions should be added to',
142 * Support for schema changes made in 4.5.
144 * The main purpose of the API is to provide integrators a level of stability not provided by
145 * the core code or schema - this means we have to provide support for api calls (where possible)
146 * across schema changes.
148 * @param array $params
150 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
151 //legacy soft credit handling - recommended approach is chaining
152 if (!empty($params['soft_credit_to'])) {
153 $params['soft_credit'][] = array(
154 'contact_id' => $params['soft_credit_to'],
155 'amount' => $params['total_amount'],
156 'soft_credit_type_id' => CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"),
159 if (!empty($params['honor_contact_id'])) {
160 $params['soft_credit'][] = array(
161 'contact_id' => $params['honor_contact_id'],
162 'amount' => $params['total_amount'],
163 'soft_credit_type_id' => CRM_Utils_Array
::value('honor_type_id', $params, CRM_Core_OptionGroup
::getValue('soft_credit_type', 'in_honor_of', 'name')),
169 * Delete a Contribution.
171 * @param array $params
176 function civicrm_api3_contribution_delete($params) {
178 $contributionID = !empty($params['contribution_id']) ?
$params['contribution_id'] : $params['id'];
179 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
180 return civicrm_api3_create_success(array($contributionID => 1));
183 return civicrm_api3_create_error('Could not delete contribution');
188 * Modify metadata for delete action.
190 * Legacy support for contribution_id.
192 * @param array $params
194 function _civicrm_api3_contribution_delete_spec(&$params) {
195 $params['id']['api.aliases'] = array('contribution_id');
199 * Retrieve a set of contributions.
201 * @param array $params
205 * Array of contributions, if error an array with an error id and error message
207 function civicrm_api3_contribution_get($params) {
209 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
210 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
212 $contribution = array();
213 while ($dao->fetch()) {
215 $contribution_details = $query->store($dao);
216 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
217 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
218 // format soft credit for backward compatibility
219 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
221 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
225 * This function is used to format the soft credit for backward compatibility.
227 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
228 * but we still return first soft credit as a part of contribution array
230 * @param $contribution
232 function _civicrm_api3_format_soft_credit(&$contribution) {
233 if (!empty($contribution['soft_credit'])) {
234 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
235 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
240 * Adjust Metadata for Get action.
242 * The metadata is used for setting defaults, documentation & validation.
244 * @param array $params
245 * Array of parameters determined by getfields.
247 function _civicrm_api3_contribution_get_spec(&$params) {
248 $params['contribution_test']['api.default'] = 0;
249 $params['contribution_test']['title'] = 'Get Test Contributions?';
250 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
251 $params['contact_id'] = $params['contribution_contact_id'];
252 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
253 unset($params['contribution_contact_id']);
257 * Legacy handling for contribution parameters.
259 * Take the input parameter list as specified in the data model and
260 * convert it into the same format that we use in QF and BAO object.
262 * @param array $params
263 * property name/value pairs to insert in new contact.
264 * @param array $values
265 * The reformatted properties that we can use internally.
269 function _civicrm_api3_contribute_format_params($params, &$values) {
270 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
271 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
276 * Adjust Metadata for Transact action.
278 * The metadata is used for setting defaults, documentation & validation.
280 * @param array $params
281 * Array of parameters determined by getfields.
283 function _civicrm_api3_contribution_transact_spec(&$params) {
284 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
285 $params = array_merge($params, $fields['values']);
286 $params['receive_date']['api.default'] = 'now';
290 * Process a transaction and record it against the contact.
292 * @param array $params
296 * contribution of created or updated record (or a civicrm error)
298 function civicrm_api3_contribution_transact($params) {
299 // Set some params specific to payment processing
300 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
302 // also trxn_id is not saved.
303 // but since there is no test it's not desirable to jump in & make the obvious changes.
304 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
305 $params['amount'] = $params['total_amount'];
306 if (!isset($params['net_amount'])) {
307 $params['net_amount'] = $params['amount'];
309 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
310 $params['invoiceID'] = $params['invoice_id'];
313 // Some payment processors expect a unique invoice_id - generate one if not supplied
314 $params['invoice_id'] = CRM_Utils_Array
::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
316 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
317 if (civicrm_error($paymentProcessor)) {
318 return $paymentProcessor;
321 $payment = CRM_Core_Payment
::singleton($params['payment_processor_mode'], $paymentProcessor);
322 if (civicrm_error($payment)) {
326 $transaction = $payment->doPayment($params);
328 $params['payment_instrument_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ?
'Credit Card' : 'Debit Card';
329 return civicrm_api('Contribution', 'create', $params);
333 * Send a contribution confirmation (receipt or invoice).
335 * The appropriate online template will be used (the existence of related objects
336 * (e.g. memberships ) will affect this selection
338 * @param array $params
343 function civicrm_api3_contribution_sendconfirmation($params) {
344 $contribution = new CRM_Contribute_BAO_Contribution();
345 $contribution->id
= $params['id'];
346 if (!$contribution->find(TRUE)) {
347 throw new Exception('Contribution does not exist');
349 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
350 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
351 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
355 * Adjust Metadata for sendconfirmation action.
357 * The metadata is used for setting defaults, documentation & validation.
359 * @param array $params
360 * Array of parameters determined by getfields.
362 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
363 $params['id'] = array(
365 'title' => 'Contribution ID',
367 $params['receipt_from_email'] = array(
369 'title' => 'From Email address (string) required until someone provides a patch :-)',
371 $params['receipt_from_name'] = array(
372 'title' => 'From Name (string)',
374 $params['cc_receipt'] = array(
375 'title' => 'CC Email address (string)',
377 $params['bcc_receipt'] = array(
378 'title' => 'BCC Email address (string)',
380 $params['receipt_text'] = array(
381 'title' => 'Message (string)',
386 * Complete an existing (pending) transaction.
388 * This will update related entities (participant, membership, pledge etc)
389 * and take any complete actions from the contribution page (e.g. send receipt).
391 * @todo - most of this should live in the BAO layer but as we want it to be an addition
392 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
394 * @param array $params
397 * @throws API_Exception
400 function civicrm_api3_contribution_completetransaction(&$params) {
402 $input = $ids = array();
403 $contribution = new CRM_Contribute_BAO_Contribution();
404 $contribution->id
= $params['id'];
405 $contribution->find(TRUE);
406 if (!$contribution->id
== $params['id']) {
407 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
410 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
411 throw new API_Exception('failed to load related objects');
413 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
414 throw new API_Exception(ts('Contribution already completed'));
416 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
417 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
419 catch(Exception
$e) {
420 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
425 * Provide function metadata.
427 * @param array $params
429 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
430 $params['id'] = array(
431 'title' => 'Contribution ID',
432 'type' => CRM_Utils_Type
::T_INT
,
433 'api.required' => TRUE,
435 $params['trxn_id'] = array(
436 'title' => 'Transaction ID',
437 'type' => CRM_Utils_Type
::T_STRING
,
439 $params['is_email_receipt'] = array(
440 'title' => 'Send email Receipt?',
441 'type' => CRM_Utils_Type
::T_BOOLEAN
,
443 $params['receipt_from_email'] = array(
444 'title' => 'Email to send receipt from.',
445 'description' => 'If not provided this will default to being based on domain mail or contribution page',
446 'type' => CRM_Utils_Type
::T_EMAIL
,
448 $params['receipt_from_name'] = array(
449 'title' => 'Name to send receipt from',
450 'description' => '. If not provided this will default to domain mail or contribution page',
451 'type' => CRM_Utils_Type
::T_STRING
,
456 * Complete an existing (pending) transaction.
458 * This will update related entities (participant, membership, pledge etc)
459 * and take any complete actions from the contribution page (e.g. send receipt).
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
464 * @param array $params
467 * @throws API_Exception
470 function civicrm_api3_contribution_repeattransaction(&$params) {
471 $input = $ids = array();
472 $contribution = new CRM_Contribute_BAO_Contribution();
473 $contribution->id
= $params['original_contribution_id'];
474 if (!$contribution->find(TRUE)) {
475 throw new API_Exception(
476 'A valid original contribution ID is required', 'invalid_data');
478 $original_contribution = clone $contribution;
480 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
481 throw new API_Exception('failed to load related objects');
484 unset($contribution->id
, $contribution->receive_date
, $contribution->invoice_id
);
485 $contribution->contribution_status_id
= $params['contribution_status_id'];
486 $contribution->receive_date
= $params['receive_date'];
487 // Have not set trxn_id to required but an e-notice if not provided seems appropriate.
488 $input['trxn_id'] = $params['trxn_id'];
490 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
492 catch(Exception
$e) {
493 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
498 * Calls IPN complete transaction for completing or repeating a transaction.
500 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
501 * when separating them in the api layer.
503 * @param array $params
504 * @param CRM_Contribute_BAO_Contribution $contribution
505 * @param array $input
509 * @param CRM_Contribute_BAO_Contribution $firstContribution
513 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
514 $objects = $contribution->_relatedObjects
;
515 $objects['contribution'] = &$contribution;
517 if ($firstContribution) {
518 $objects['first_contribution'] = $firstContribution;
520 $input['component'] = $contribution->_component
;
521 $input['is_test'] = $contribution->is_test
;
522 $input['amount'] = $contribution->total_amount
;
523 if (isset($params['is_email_receipt'])) {
524 $input['is_email_receipt'] = $params['is_email_receipt'];
526 if (empty($contribution->contribution_page_id
)) {
527 static $domainFromName;
528 static $domainFromEmail;
529 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) ||
empty($params['receipt_from_email']))) {
530 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE);
532 $input['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $params, $domainFromName);
533 $input['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $params, $domainFromEmail);
535 // @todo required for base ipn but problematic as api layer handles this
536 $transaction = new CRM_Core_Transaction();
537 $ipn = new CRM_Core_Payment_BaseIPN();
538 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
));
543 * Provide function metadata.
545 * @param array $params
547 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
548 $params['original_contribution_id'] = array(
549 'title' => 'Original Contribution ID',
550 'type' => CRM_Utils_Type
::T_INT
,
551 'api.required' => TRUE,
553 $params['trxn_id'] = array(
554 'title' => 'Transaction ID',
555 'type' => CRM_Utils_Type
::T_STRING
,
557 $params['is_email_receipt'] = array(
558 'title' => 'Send email Receipt?',
559 'type' => CRM_Utils_Type
::T_BOOLEAN
,
561 $params['contribution_status_id'] = array(
562 'title' => 'Contribution Status ID',
563 'name' => 'contribution_status_id',
564 'type' => CRM_Utils_Type
::T_INT
,
565 'pseudoconstant' => array(
566 'optionGroupName' => 'contribution_status',
568 'api.required' => TRUE,
570 $params['receive_date'] = array(
571 'title' => 'Contribution Receive Date',
572 'name' => 'receive_date',
573 'type' => CRM_Utils_Type
::T_DATE
,
574 'api.default' => 'now',
576 $params['trxn_id'] = array(
577 'title' => 'Transaction ID',
579 'type' => CRM_Utils_Type
::T_STRING
,
581 $params['payment_processor_id'] = array(
582 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
583 'title' => 'Payment processor ID',
584 'name' => 'payment_processor_id',
585 'type' => CRM_Utils_Type
::T_INT
,