3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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']) && !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']);
59 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
61 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
62 if (array_key_exists('financial_type_id', $error)) {
63 throw new API_Exception($error['financial_type_id']);
66 _civicrm_api3_contribution_create_legacy_support_45($params);
68 // Make sure tax calculation is handled via api.
69 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
71 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Contribution');
75 * Adjust Metadata for Create action.
77 * The metadata is used for setting defaults, documentation & validation.
79 * @param array $params
80 * Array of parameters determined by getfields.
82 function _civicrm_api3_contribution_create_spec(&$params) {
83 $params['contact_id']['api.required'] = 1;
84 $params['total_amount']['api.required'] = 1;
85 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
86 $params['receive_date']['api.default'] = 'now';
87 $params['payment_processor'] = array(
88 'name' => 'payment_processor',
89 'title' => 'Payment Processor ID',
90 'description' => 'ID of payment processor used for this contribution',
91 // field is called payment processor - not payment processor id but can only be one id so
92 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
93 'api.aliases' => array('payment_processor_id'),
94 'type' => CRM_Utils_Type
::T_INT
,
96 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
97 $params['financial_type_id']['api.required'] = 1;
98 $params['note'] = array(
100 'uniqueName' => 'contribution_note',
103 'description' => 'Associated Note in the notes table',
105 $params['soft_credit_to'] = array(
106 'name' => 'soft_credit_to',
107 'title' => 'Soft Credit contact ID (legacy)',
109 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
110 'FKClassName' => 'CRM_Contact_DAO_Contact',
112 $params['honor_contact_id'] = array(
113 'name' => 'honor_contact_id',
114 'title' => 'Honoree contact ID (legacy)',
116 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
117 'FKClassName' => 'CRM_Contact_DAO_Contact',
119 $params['honor_type_id'] = array(
120 'name' => 'honor_type_id',
121 'title' => 'Honoree Type (legacy)',
123 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
124 'pseudoconstant' => TRUE,
126 // note this is a recommended option but not adding as a default to avoid
127 // creating unnecessary changes for the dev
128 $params['skipRecentView'] = array(
129 'name' => 'skipRecentView',
130 'title' => 'Skip adding to recent view',
131 'type' => CRM_Utils_Type
::T_BOOLEAN
,
132 'description' => 'Do not add to recent view (setting this improves performance)',
134 $params['skipLineItem'] = array(
135 'name' => 'skipLineItem',
136 'title' => 'Skip adding line items',
139 'description' => 'Do not add line items by default (if you wish to add your own)',
141 $params['batch_id'] = array(
144 'description' => 'Batch which relevant transactions should be added to',
149 * Support for schema changes made in 4.5.
151 * The main purpose of the API is to provide integrators a level of stability not provided by
152 * the core code or schema - this means we have to provide support for api calls (where possible)
153 * across schema changes.
155 * @param array $params
157 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
158 //legacy soft credit handling - recommended approach is chaining
159 if (!empty($params['soft_credit_to'])) {
160 $params['soft_credit'][] = array(
161 'contact_id' => $params['soft_credit_to'],
162 'amount' => $params['total_amount'],
163 'soft_credit_type_id' => CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"),
166 if (!empty($params['honor_contact_id'])) {
167 $params['soft_credit'][] = array(
168 'contact_id' => $params['honor_contact_id'],
169 'amount' => $params['total_amount'],
170 'soft_credit_type_id' => CRM_Utils_Array
::value('honor_type_id', $params, CRM_Core_OptionGroup
::getValue('soft_credit_type', 'in_honor_of', 'name')),
176 * Delete a Contribution.
178 * @param array $params
183 function civicrm_api3_contribution_delete($params) {
185 $contributionID = !empty($params['contribution_id']) ?
$params['contribution_id'] : $params['id'];
186 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
187 return civicrm_api3_create_success(array($contributionID => 1));
190 return civicrm_api3_create_error('Could not delete contribution');
195 * Modify metadata for delete action.
197 * Legacy support for contribution_id.
199 * @param array $params
201 function _civicrm_api3_contribution_delete_spec(&$params) {
202 $params['id']['api.aliases'] = array('contribution_id');
206 * Retrieve a set of contributions.
208 * @param array $params
212 * Array of contributions, if error an array with an error id and error message
214 function civicrm_api3_contribution_get($params) {
216 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
217 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
219 $contribution = array();
220 while ($dao->fetch()) {
222 $contribution_details = $query->store($dao);
223 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
224 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
225 // format soft credit for backward compatibility
226 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
228 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
232 * This function is used to format the soft credit for backward compatibility.
234 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
235 * but we still return first soft credit as a part of contribution array
237 * @param $contribution
239 function _civicrm_api3_format_soft_credit(&$contribution) {
240 if (!empty($contribution['soft_credit'])) {
241 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
242 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
247 * Adjust Metadata for Get action.
249 * The metadata is used for setting defaults, documentation & validation.
251 * @param array $params
252 * Array of parameters determined by getfields.
254 function _civicrm_api3_contribution_get_spec(&$params) {
255 $params['contribution_test'] = array(
257 'type' => CRM_Utils_Type
::T_BOOLEAN
,
258 'title' => 'Get Test Contributions?',
260 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
261 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
262 $params['contact_id'] = $params['contribution_contact_id'];
263 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
264 unset($params['contribution_contact_id']);
268 * Legacy handling for contribution parameters.
270 * Take the input parameter list as specified in the data model and
271 * convert it into the same format that we use in QF and BAO object.
273 * @param array $params
274 * property name/value pairs to insert in new contact.
275 * @param array $values
276 * The reformatted properties that we can use internally.
280 function _civicrm_api3_contribute_format_params($params, &$values) {
281 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
282 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
287 * Adjust Metadata for Transact action.
289 * The metadata is used for setting defaults, documentation & validation.
291 * @param array $params
292 * Array of parameters determined by getfields.
294 function _civicrm_api3_contribution_transact_spec(&$params) {
295 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
296 $params = array_merge($params, $fields['values']);
297 $params['receive_date']['api.default'] = 'now';
301 * Process a transaction and record it against the contact.
303 * @param array $params
307 * contribution of created or updated record (or a civicrm error)
309 function civicrm_api3_contribution_transact($params) {
310 // Set some params specific to payment processing
311 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
313 // also trxn_id is not saved.
314 // but since there is no test it's not desirable to jump in & make the obvious changes.
315 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
316 $params['amount'] = $params['total_amount'];
317 if (!isset($params['net_amount'])) {
318 $params['net_amount'] = $params['amount'];
320 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
321 $params['invoiceID'] = $params['invoice_id'];
324 // Some payment processors expect a unique invoice_id - generate one if not supplied
325 $params['invoice_id'] = CRM_Utils_Array
::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
327 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
328 if (civicrm_error($paymentProcessor)) {
329 return $paymentProcessor;
332 $payment = CRM_Core_Payment
::singleton($params['payment_processor_mode'], $paymentProcessor);
333 if (civicrm_error($payment)) {
337 $transaction = $payment->doPayment($params);
339 $params['payment_instrument_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ?
'Credit Card' : 'Debit Card';
340 return civicrm_api('Contribution', 'create', $params);
344 * Send a contribution confirmation (receipt or invoice).
346 * The appropriate online template will be used (the existence of related objects
347 * (e.g. memberships ) will affect this selection
349 * @param array $params
354 function civicrm_api3_contribution_sendconfirmation($params) {
355 $contribution = new CRM_Contribute_BAO_Contribution();
356 $contribution->id
= $params['id'];
357 if (!$contribution->find(TRUE)) {
358 throw new Exception('Contribution does not exist');
360 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
361 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
362 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
366 * Adjust Metadata for sendconfirmation action.
368 * The metadata is used for setting defaults, documentation & validation.
370 * @param array $params
371 * Array of parameters determined by getfields.
373 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
374 $params['id'] = array(
376 'title' => 'Contribution ID',
377 'type' => CRM_Utils_Type
::T_INT
,
379 $params['receipt_from_email'] = array(
381 'title' => 'From Email address (string) required until someone provides a patch :-)',
382 'type' => CRM_Utils_Type
::T_STRING
,
384 $params['receipt_from_name'] = array(
385 'title' => 'From Name (string)',
386 'type' => CRM_Utils_Type
::T_STRING
,
388 $params['cc_receipt'] = array(
389 'title' => 'CC Email address (string)',
390 'type' => CRM_Utils_Type
::T_STRING
,
392 $params['bcc_receipt'] = array(
393 'title' => 'BCC Email address (string)',
394 'type' => CRM_Utils_Type
::T_STRING
,
396 $params['receipt_text'] = array(
397 'title' => 'Message (string)',
398 'type' => CRM_Utils_Type
::T_STRING
,
403 * Complete an existing (pending) transaction.
405 * This will update related entities (participant, membership, pledge etc)
406 * and take any complete actions from the contribution page (e.g. send receipt).
408 * @todo - most of this should live in the BAO layer but as we want it to be an addition
409 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
411 * @param array $params
414 * @throws API_Exception
417 function civicrm_api3_contribution_completetransaction(&$params) {
419 $input = $ids = array();
420 $contribution = new CRM_Contribute_BAO_Contribution();
421 $contribution->id
= $params['id'];
422 $contribution->find(TRUE);
423 if (!$contribution->id
== $params['id']) {
424 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
427 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
428 throw new API_Exception('failed to load related objects');
430 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
431 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
433 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
434 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
439 * Provide function metadata.
441 * @param array $params
443 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
444 $params['id'] = array(
445 'title' => 'Contribution ID',
446 'type' => CRM_Utils_Type
::T_INT
,
447 'api.required' => TRUE,
449 $params['trxn_id'] = array(
450 'title' => 'Transaction ID',
451 'type' => CRM_Utils_Type
::T_STRING
,
453 $params['is_email_receipt'] = array(
454 'title' => 'Send email Receipt?',
455 'type' => CRM_Utils_Type
::T_BOOLEAN
,
457 $params['receipt_from_email'] = array(
458 'title' => 'Email to send receipt from.',
459 'description' => 'If not provided this will default to being based on domain mail or contribution page',
460 'type' => CRM_Utils_Type
::T_EMAIL
,
462 $params['receipt_from_name'] = array(
463 'title' => 'Name to send receipt from',
464 'description' => '. If not provided this will default to domain mail or contribution page',
465 'type' => CRM_Utils_Type
::T_STRING
,
470 * Complete an existing (pending) transaction.
472 * This will update related entities (participant, membership, pledge etc)
473 * and take any complete actions from the contribution page (e.g. send receipt).
475 * @todo - most of this should live in the BAO layer but as we want it to be an addition
476 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
478 * @param array $params
481 * @throws API_Exception
484 function civicrm_api3_contribution_repeattransaction(&$params) {
485 $input = $ids = array();
486 $contribution = new CRM_Contribute_BAO_Contribution();
487 $contribution->id
= $params['original_contribution_id'];
488 if (!$contribution->find(TRUE)) {
489 throw new API_Exception(
490 'A valid original contribution ID is required', 'invalid_data');
492 $original_contribution = clone $contribution;
494 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
495 throw new API_Exception('failed to load related objects');
498 unset($contribution->id
, $contribution->receive_date
, $contribution->invoice_id
);
499 $contribution->contribution_status_id
= $params['contribution_status_id'];
500 $contribution->receive_date
= $params['receive_date'];
502 $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount');
503 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
505 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
507 catch(Exception
$e) {
508 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
513 * Calls IPN complete transaction for completing or repeating a transaction.
515 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
516 * when separating them in the api layer.
518 * @param array $params
519 * @param CRM_Contribute_BAO_Contribution $contribution
520 * @param array $input
524 * @param CRM_Contribute_BAO_Contribution $firstContribution
528 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
529 $objects = $contribution->_relatedObjects
;
530 $objects['contribution'] = &$contribution;
532 if ($firstContribution) {
533 $objects['first_contribution'] = $firstContribution;
535 $input['component'] = $contribution->_component
;
536 $input['is_test'] = $contribution->is_test
;
537 $input['amount'] = empty($input['total_amount']) ?
$contribution->total_amount
: $input['total_amount'];
539 if (isset($params['is_email_receipt'])) {
540 $input['is_email_receipt'] = $params['is_email_receipt'];
542 if (empty($contribution->contribution_page_id
)) {
543 static $domainFromName;
544 static $domainFromEmail;
545 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) ||
empty($params['receipt_from_email']))) {
546 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE);
548 $input['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $params, $domainFromName);
549 $input['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $params, $domainFromEmail);
551 // @todo required for base ipn but problematic as api layer handles this
552 $transaction = new CRM_Core_Transaction();
553 $ipn = new CRM_Core_Payment_BaseIPN();
554 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
));
559 * Provide function metadata.
561 * @param array $params
563 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
564 $params['original_contribution_id'] = array(
565 'title' => 'Original Contribution ID',
566 'type' => CRM_Utils_Type
::T_INT
,
567 'api.required' => TRUE,
569 $params['trxn_id'] = array(
570 'title' => 'Transaction ID',
571 'type' => CRM_Utils_Type
::T_STRING
,
573 $params['is_email_receipt'] = array(
574 'title' => 'Send email Receipt?',
575 'type' => CRM_Utils_Type
::T_BOOLEAN
,
577 $params['contribution_status_id'] = array(
578 'title' => 'Contribution Status ID',
579 'name' => 'contribution_status_id',
580 'type' => CRM_Utils_Type
::T_INT
,
581 'pseudoconstant' => array(
582 'optionGroupName' => 'contribution_status',
584 'api.required' => TRUE,
586 $params['receive_date'] = array(
587 'title' => 'Contribution Receive Date',
588 'name' => 'receive_date',
589 'type' => CRM_Utils_Type
::T_DATE
,
590 'api.default' => 'now',
592 $params['trxn_id'] = array(
593 'title' => 'Transaction ID',
595 'type' => CRM_Utils_Type
::T_STRING
,
597 $params['payment_processor_id'] = array(
598 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
599 'title' => 'Payment processor ID',
600 'name' => 'payment_processor_id',
601 'type' => CRM_Utils_Type
::T_INT
,