4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
30 * File for the CiviCRM APIv3 Contribution functions
32 * @package CiviCRM_APIv3
33 * @subpackage API_Contribute
35 * @copyright CiviCRM LLC (c) 2004-2014
36 * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
41 * Add or update a contribution
43 * @param array $params
44 * (reference ) input parameters.
46 * @throws API_Exception
51 * @example ContributionCreate.php
52 * {@getfields Contribution_create}
54 function civicrm_api3_contribution_create(&$params) {
56 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
57 $params = array_merge($params, $values);
59 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
61 //throw error for invalid status change such as setting completed back to pending
62 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
63 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
64 CRM_Contribute_BAO_Contribution
::checkStatusValidation(NULL, $params, $error);
65 if (array_key_exists('contribution_status_id', $error)) {
66 throw new API_Exception($error['contribution_status_id']);
70 _civicrm_api3_contribution_create_legacy_support_45($params);
72 // make sure tax calculation is handled via api
73 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
75 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Contribution');
79 * Adjust Metadata for Create action
81 * The metadata is used for setting defaults, documentation & validation
82 * @param array $params
83 * Array or parameters determined by getfields.
85 function _civicrm_api3_contribution_create_spec(&$params) {
86 $params['contact_id']['api.required'] = 1;
87 $params['total_amount']['api.required'] = 1;
88 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
89 $params['receive_date']['api.default'] = 'now';
90 $params['payment_processor'] = array(
91 'name' => 'payment_processor',
92 'title' => 'Payment Processor ID',
93 'description' => 'ID of payment processor used for this contribution',
94 // field is called payment processor - not payment processor id but can only be one id so
95 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
96 'api.aliases' => array('payment_processor_id'),
98 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
99 $params['financial_type_id']['api.required'] = 1;
100 $params['note'] = array(
102 'uniqueName' => 'contribution_note',
105 'description' => 'Associated Note in the notes table',
107 $params['soft_credit_to'] = array(
108 'name' => 'soft_credit_to',
109 'title' => 'Soft Credit contact ID (legacy)',
111 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
112 'FKClassName' => 'CRM_Contact_DAO_Contact',
114 $params['honor_contact_id'] = array(
115 'name' => 'honor_contact_id',
116 'title' => 'Honoree contact ID (legacy)',
118 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
119 'FKClassName' => 'CRM_Contact_DAO_Contact',
121 $params['honor_type_id'] = array(
122 'name' => 'honor_type_id',
123 'title' => 'Honoree Type (legacy)',
125 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
126 'pseudoconstant' => TRUE,
128 // note this is a recommended option but not adding as a default to avoid
129 // creating unnecessary changes for the dev
130 $params['skipRecentView'] = array(
131 'name' => 'skipRecentView',
132 'title' => 'Skip adding to recent view',
133 'type' => CRM_Utils_Type
::T_BOOLEAN
,
134 'description' => 'Do not add to recent view (setting this improves performance)',
136 $params['skipLineItem'] = array(
137 'name' => 'skipLineItem',
138 'title' => 'Skip adding line items',
141 'description' => 'Do not add line items by default (if you wish to add your own)',
143 $params['batch_id'] = array(
146 'description' => 'Batch which relevant transactions should be added to',
151 * Support for schema changes made in 4.5
152 * The main purpose of the API is to provide integrators a level of stability not provided by
153 * the core code or schema - this means we have to provide support for api calls (where possible)
154 * across schema changes.
156 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
157 //legacy soft credit handling - recommended approach is chaining
158 if (!empty($params['soft_credit_to'])) {
159 $params['soft_credit'][] = array(
160 'contact_id' => $params['soft_credit_to'],
161 'amount' => $params['total_amount'],
162 'soft_credit_type_id' => CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"),
165 if (!empty($params['honor_contact_id'])) {
166 $params['soft_credit'][] = array(
167 'contact_id' => $params['honor_contact_id'],
168 'amount' => $params['total_amount'],
169 'soft_credit_type_id' => CRM_Utils_Array
::value('honor_type_id', $params, CRM_Core_OptionGroup
::getValue('soft_credit_type', 'in_honor_of', 'name')),
175 * Delete a contribution
177 * @param array $params
178 * (reference ) input parameters.
181 * true if success, else false
184 * {@getfields Contribution_delete}
185 * @example ContributionDelete.php
187 function civicrm_api3_contribution_delete($params) {
189 $contributionID = !empty($params['contribution_id']) ?
$params['contribution_id'] : $params['id'];
190 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
191 return civicrm_api3_create_success(array($contributionID => 1));
194 return civicrm_api3_create_error('Could not delete contribution');
199 * modify metadata. Legacy support for contribution_id
201 function _civicrm_api3_contribution_delete_spec(&$params) {
202 $params['id']['api.aliases'] = array('contribution_id');
206 * Retrieve a set of contributions, given a set of input params
208 * @param array $params
209 * (reference ) input parameters.
212 * Array of contributions, if error an array with an error id and error message
215 * {@getfields Contribution_get}
216 * @example ContributionGet.php
218 function civicrm_api3_contribution_get($params) {
220 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
221 $entity = 'contribution';
222 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
224 $contribution = array();
225 while ($dao->fetch()) {
227 $contribution_details = $query->store($dao);
228 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
229 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
230 if (isset($contribution[$dao->contribution_id
]['financial_type_id'])) {
231 $contribution[$dao->contribution_id
]['financial_type_id'] = $contribution[$dao->contribution_id
]['financial_type_id'];
233 // format soft credit for backward compatibility
234 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
236 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
240 * This function is used to format the soft credit for backward compatibility
241 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
242 * but we still return first soft credit as a part of contribution array
244 function _civicrm_api3_format_soft_credit(&$contribution) {
245 if (!empty($contribution['soft_credit'])) {
246 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
247 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
252 * Adjust Metadata for Get action
254 * The metadata is used for setting defaults, documentation & validation
255 * @param array $params
256 * Array or parameters determined by getfields.
258 function _civicrm_api3_contribution_get_spec(&$params) {
259 $params['contribution_test']['api.default'] = 0;
260 $params['contribution_test']['title'] = 'Get Test Contributions?';
261 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
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 * take the input parameter list as specified in the data model and
269 * convert it into the same format that we use in QF and BAO object
271 * @param array $params
272 * Associative array of property name/value.
273 * pairs to insert in new contact.
274 * @param array $values
275 * The reformatted properties that we can use internally.
278 * @param bool $create
280 * @return array|CRM_Error
283 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
284 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
285 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
290 * Adjust Metadata for Transact action
292 * The metadata is used for setting defaults, documentation & validation
293 * @param array $params
294 * Array or parameters determined by getfields.
296 function _civicrm_api3_contribution_transact_spec(&$params) {
297 $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
298 $params = array_merge($params, $fields['values']);
299 $params['receive_date']['api.default'] = 'now';
303 * Process a transaction and record it against the contact.
305 * @param array $params
306 * (reference ) input parameters.
309 * (reference ) contribution of created or updated record (or a civicrm error)
314 function civicrm_api3_contribution_transact($params) {
315 // Set some params specific to payment processing
316 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
317 $params['amount'] = $params['total_amount'];
318 if (!isset($params['net_amount'])) {
319 $params['net_amount'] = $params['amount'];
321 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
322 $params['invoiceID'] = $params['invoice_id'];
325 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
326 if (civicrm_error($paymentProcessor)) {
327 return $paymentProcessor;
330 $payment = CRM_Core_Payment
::singleton($params['payment_processor_mode'], $paymentProcessor);
331 if (civicrm_error($payment)) {
335 $transaction = $payment->doDirectPayment($params);
336 if (civicrm_error($transaction)) {
340 // but actually, $payment->doDirectPayment() doesn't return a
341 // CRM_Core_Error by itself
342 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
343 $errs = $transaction->getErrors();
345 $last_error = array_shift($errs);
346 return CRM_Core_Error
::createApiError($last_error['message']);
349 $params['payment_instrument_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ?
'Credit Card' : 'Debit Card';
350 return civicrm_api('contribution', 'create', $params);
354 * Send a contribution confirmation (receipt or invoice)
355 * The appropriate online template will be used (the existence of related objects
356 * (e.g. memberships ) will affect this selection
358 * @param array $params
360 * {@getfields Contribution_sendconfirmation}
368 function civicrm_api3_contribution_sendconfirmation($params) {
369 $contribution = new CRM_Contribute_BAO_Contribution();
370 $contribution->id
= $params['id'];
371 if (! $contribution->find(TRUE)) {
372 throw new Exception('Contribution does not exist');
374 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
375 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
376 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
380 * Adjust Metadata for sendconfirmation action
382 * The metadata is used for setting defaults, documentation & validation
383 * @param array $params
384 * Array or parameters determined by getfields.
386 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
387 $params['id'] = array(
389 'title' => 'Contribution ID',
391 $params['receipt_from_email'] = array(
393 'title' => 'From Email address (string) required until someone provides a patch :-)',
395 $params['receipt_from_name'] = array(
396 'title' => 'From Name (string)',
398 $params['cc_receipt'] = array(
399 'title' => 'CC Email address (string)',
401 $params['bcc_receipt'] = array(
402 'title' => 'BCC Email address (string)',
404 $params['receipt_text'] = array(
405 'title' => 'Message (string)',
410 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
411 * and taking any complete actions from the contribution page (e.g. send receipt)
413 * @todo - most of this should live in the BAO layer but as we want it to be an addition
414 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
416 * @param array $params
418 * {@getfields Contribution_completetransaction}
420 * @throws API_Exception
426 function civicrm_api3_contribution_completetransaction(&$params) {
428 $input = $ids = array();
429 $contribution = new CRM_Contribute_BAO_Contribution();
430 $contribution->id
= $params['id'];
431 $contribution->find(TRUE);
432 if (!$contribution->id
== $params['id']) {
433 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
436 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
437 throw new API_Exception('failed to load related objects');
439 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
440 throw new API_Exception(ts('Contribution already completed'));
442 $objects = $contribution->_relatedObjects
;
443 $objects['contribution'] = &$contribution;
444 $input['component'] = $contribution->_component
;
445 $input['is_test'] = $contribution->is_test
;
446 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
447 $input['amount'] = $contribution->total_amount
;
448 if (isset($params['is_email_receipt'])) {
449 $input['is_email_receipt'] = $params['is_email_receipt'];
451 // @todo required for base ipn but problematic as api layer handles this
452 $transaction = new CRM_Core_Transaction();
453 $ipn = new CRM_Core_Payment_BaseIPN();
454 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
));
456 catch(Exception
$e) {
457 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
462 * provide function metadata
463 * @param array $params
465 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
466 $params['id'] = array(
467 'title' => 'Contribution ID',
468 'type' => CRM_Utils_Type
::T_INT
,
469 'api.required' => TRUE,
471 $params['trxn_id'] = array(
472 'title' => 'Transaction ID',
473 'type' => CRM_Utils_Type
::T_STRING
,
475 $params['is_email_receipt'] = array(
476 'title' => 'Send email Receipt?',
477 'type' => CRM_Utils_Type
::T_BOOLEAN
,