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'])) {
52 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types, $op);
53 if (!in_array($params['financial_type_id'], array_keys($types))) {
54 return civicrm_api3_create_error('You do not have permission to create this contribution');
57 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
59 //throw error for invalid status change such as setting completed back to pending
60 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
61 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
62 CRM_Contribute_BAO_Contribution
::checkStatusValidation(NULL, $params, $error);
63 if (array_key_exists('contribution_status_id', $error)) {
64 throw new API_Exception($error['contribution_status_id']);
67 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
69 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
70 if (array_key_exists('financial_type_id', $error)) {
71 throw new API_Exception($error['financial_type_id']);
74 _civicrm_api3_contribution_create_legacy_support_45($params);
76 // Make sure tax calculation is handled via api.
77 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
79 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Contribution');
83 * Adjust Metadata for Create action.
85 * The metadata is used for setting defaults, documentation & validation.
87 * @param array $params
88 * Array of parameters determined by getfields.
90 function _civicrm_api3_contribution_create_spec(&$params) {
91 $params['contact_id']['api.required'] = 1;
92 $params['total_amount']['api.required'] = 1;
93 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
94 $params['receive_date']['api.default'] = 'now';
95 $params['payment_processor'] = array(
96 'name' => 'payment_processor',
97 'title' => 'Payment Processor ID',
98 'description' => 'ID of payment processor used for this contribution',
99 // field is called payment processor - not payment processor id but can only be one id so
100 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
101 'api.aliases' => array('payment_processor_id'),
102 'type' => CRM_Utils_Type
::T_INT
,
104 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
105 $params['financial_type_id']['api.required'] = 1;
106 $params['note'] = array(
108 'uniqueName' => 'contribution_note',
111 'description' => 'Associated Note in the notes table',
113 $params['soft_credit_to'] = array(
114 'name' => 'soft_credit_to',
115 'title' => 'Soft Credit contact ID (legacy)',
117 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
118 'FKClassName' => 'CRM_Contact_DAO_Contact',
120 $params['honor_contact_id'] = array(
121 'name' => 'honor_contact_id',
122 'title' => 'Honoree contact ID (legacy)',
124 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
125 'FKClassName' => 'CRM_Contact_DAO_Contact',
127 $params['honor_type_id'] = array(
128 'name' => 'honor_type_id',
129 'title' => 'Honoree Type (legacy)',
131 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
132 'pseudoconstant' => TRUE,
134 // note this is a recommended option but not adding as a default to avoid
135 // creating unnecessary changes for the dev
136 $params['skipRecentView'] = array(
137 'name' => 'skipRecentView',
138 'title' => 'Skip adding to recent view',
139 'type' => CRM_Utils_Type
::T_BOOLEAN
,
140 'description' => 'Do not add to recent view (setting this improves performance)',
142 $params['skipLineItem'] = array(
143 'name' => 'skipLineItem',
144 'title' => 'Skip adding line items',
145 'type' => CRM_Utils_Type
::T_BOOLEAN
,
147 'description' => 'Do not add line items by default (if you wish to add your own)',
149 $params['batch_id'] = array(
152 'description' => 'Batch which relevant transactions should be added to',
157 * Support for schema changes made in 4.5.
159 * The main purpose of the API is to provide integrators a level of stability not provided by
160 * the core code or schema - this means we have to provide support for api calls (where possible)
161 * across schema changes.
163 * @param array $params
165 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
166 //legacy soft credit handling - recommended approach is chaining
167 if (!empty($params['soft_credit_to'])) {
168 $params['soft_credit'][] = array(
169 'contact_id' => $params['soft_credit_to'],
170 'amount' => $params['total_amount'],
171 'soft_credit_type_id' => CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"),
174 if (!empty($params['honor_contact_id'])) {
175 $params['soft_credit'][] = array(
176 'contact_id' => $params['honor_contact_id'],
177 'amount' => $params['total_amount'],
178 'soft_credit_type_id' => CRM_Utils_Array
::value('honor_type_id', $params, CRM_Core_OptionGroup
::getValue('soft_credit_type', 'in_honor_of', 'name')),
184 * Delete a Contribution.
186 * @param array $params
191 function civicrm_api3_contribution_delete($params) {
193 $contributionID = !empty($params['contribution_id']) ?
$params['contribution_id'] : $params['id'];
194 // First check contribution financial type
195 $financialType = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
196 // Now check permissioned lineitems & permissioned contribution
197 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
198 && !CRM_Core_Permission
::check('delete contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($financialType)) ||
199 !CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($contributionID, 'delete', FALSE)
201 return civicrm_api3_create_error('You do not have permission to delete this contribution');
203 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
204 return civicrm_api3_create_success(array($contributionID => 1));
207 return civicrm_api3_create_error('Could not delete contribution');
212 * Modify metadata for delete action.
214 * Legacy support for contribution_id.
216 * @param array $params
218 function _civicrm_api3_contribution_delete_spec(&$params) {
219 $params['id']['api.aliases'] = array('contribution_id');
223 * Retrieve a set of contributions.
225 * @param array $params
229 * Array of contributions, if error an array with an error id and error message
231 function civicrm_api3_contribution_get($params) {
233 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
234 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
236 $contribution = array();
237 while ($dao->fetch()) {
239 $contribution_details = $query->store($dao);
240 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
241 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
242 // format soft credit for backward compatibility
243 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
245 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
249 * This function is used to format the soft credit for backward compatibility.
251 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
252 * but we still return first soft credit as a part of contribution array
254 * @param $contribution
256 function _civicrm_api3_format_soft_credit(&$contribution) {
257 if (!empty($contribution['soft_credit'])) {
258 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
259 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
264 * Adjust Metadata for Get action.
266 * The metadata is used for setting defaults, documentation & validation.
268 * @param array $params
269 * Array of parameters determined by getfields.
271 function _civicrm_api3_contribution_get_spec(&$params) {
272 $params['contribution_test'] = array(
274 'type' => CRM_Utils_Type
::T_BOOLEAN
,
275 'title' => 'Get Test Contributions?',
276 'api.aliases' => array('is_test'),
279 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
280 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
281 $params['contact_id'] = $params['contribution_contact_id'];
282 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
283 unset($params['contribution_contact_id']);
287 * Legacy handling for contribution parameters.
289 * Take the input parameter list as specified in the data model and
290 * convert it into the same format that we use in QF and BAO object.
292 * @param array $params
293 * property name/value pairs to insert in new contact.
294 * @param array $values
295 * The reformatted properties that we can use internally.
299 function _civicrm_api3_contribute_format_params($params, &$values) {
300 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
301 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
306 * Adjust Metadata for Transact action.
308 * The metadata is used for setting defaults, documentation & validation.
310 * @param array $params
311 * Array of parameters determined by getfields.
313 function _civicrm_api3_contribution_transact_spec(&$params) {
314 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
315 $params = array_merge($params, $fields['values']);
316 $params['receive_date']['api.default'] = 'now';
320 * Process a transaction and record it against the contact.
322 * @param array $params
326 * contribution of created or updated record (or a civicrm error)
328 function civicrm_api3_contribution_transact($params) {
329 // Set some params specific to payment processing
330 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
332 // also trxn_id is not saved.
333 // but since there is no test it's not desirable to jump in & make the obvious changes.
334 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
335 $params['amount'] = $params['total_amount'];
336 if (!isset($params['net_amount'])) {
337 $params['net_amount'] = $params['amount'];
339 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
340 $params['invoiceID'] = $params['invoice_id'];
343 // Some payment processors expect a unique invoice_id - generate one if not supplied
344 $params['invoice_id'] = CRM_Utils_Array
::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
346 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
347 $paymentProcessor['object']->doPayment($params);
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).
356 * The appropriate online template will be used (the existence of related objects
357 * (e.g. memberships ) will affect this selection
359 * @param array $params
364 function civicrm_api3_contribution_sendconfirmation($params) {
365 $contribution = new CRM_Contribute_BAO_Contribution();
366 $contribution->id
= $params['id'];
367 if (!$contribution->find(TRUE)) {
368 throw new Exception('Contribution does not exist');
370 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
371 $contribution->loadRelatedObjects($input, $ids, TRUE);
372 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
376 * Adjust Metadata for sendconfirmation action.
378 * The metadata is used for setting defaults, documentation & validation.
380 * @param array $params
381 * Array of parameters determined by getfields.
383 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
384 $params['id'] = array(
386 'title' => 'Contribution ID',
387 'type' => CRM_Utils_Type
::T_INT
,
389 $params['receipt_from_email'] = array(
391 'title' => 'From Email address (string) required until someone provides a patch :-)',
392 'type' => CRM_Utils_Type
::T_STRING
,
394 $params['receipt_from_name'] = array(
395 'title' => 'From Name (string)',
396 'type' => CRM_Utils_Type
::T_STRING
,
398 $params['cc_receipt'] = array(
399 'title' => 'CC Email address (string)',
400 'type' => CRM_Utils_Type
::T_STRING
,
402 $params['bcc_receipt'] = array(
403 'title' => 'BCC Email address (string)',
404 'type' => CRM_Utils_Type
::T_STRING
,
406 $params['receipt_text'] = array(
407 'title' => 'Message (string)',
408 'type' => CRM_Utils_Type
::T_STRING
,
413 * Complete an existing (pending) transaction.
415 * This will update related entities (participant, membership, pledge etc)
416 * and take any complete actions from the contribution page (e.g. send receipt).
418 * @todo - most of this should live in the BAO layer but as we want it to be an addition
419 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
421 * @param array $params
424 * @throws API_Exception
427 function civicrm_api3_contribution_completetransaction(&$params) {
429 $input = $ids = array();
430 if (isset($params['payment_processor_id'])) {
431 $input['payment_processor_id'] = $params['payment_processor_id'];
433 $contribution = new CRM_Contribute_BAO_Contribution();
434 $contribution->id
= $params['id'];
435 $contribution->find(TRUE);
436 if (!$contribution->id
== $params['id']) {
437 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
440 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
441 throw new API_Exception('failed to load related objects');
443 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
444 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
446 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
447 if (!empty($params['fee_amount'])) {
448 $input['fee_amount'] = $params['fee_amount'];
450 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
455 * Provide function metadata.
457 * @param array $params
459 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
460 $params['id'] = array(
461 'title' => 'Contribution ID',
462 'type' => CRM_Utils_Type
::T_INT
,
463 'api.required' => TRUE,
465 $params['trxn_id'] = array(
466 'title' => 'Transaction ID',
467 'type' => CRM_Utils_Type
::T_STRING
,
469 $params['is_email_receipt'] = array(
470 'title' => 'Send email Receipt?',
471 'type' => CRM_Utils_Type
::T_BOOLEAN
,
473 $params['receipt_from_email'] = array(
474 'title' => 'Email to send receipt from.',
475 'description' => 'If not provided this will default to being based on domain mail or contribution page',
476 'type' => CRM_Utils_Type
::T_EMAIL
,
478 $params['receipt_from_name'] = array(
479 'title' => 'Name to send receipt from',
480 'description' => '. If not provided this will default to domain mail or contribution page',
481 'type' => CRM_Utils_Type
::T_STRING
,
483 $params['payment_processor_id'] = array(
484 'title' => 'Payment processor ID',
485 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
486 'type' => CRM_Utils_Type
::T_INT
,
488 $params['fee_amount'] = array(
489 'title' => 'Fee charged on transaction',
490 'description' => 'If a fee has been charged then the amount',
491 'type' => CRM_Utils_Type
::T_FLOAT
,
493 $params['trxn_date'] = array(
494 'title' => 'Transaction Date',
495 'description' => 'Date this transaction occurred',
496 'type' => CRM_Utils_Type
::T_DATE
,
501 * Complete an existing (pending) transaction.
503 * This will update related entities (participant, membership, pledge etc)
504 * and take any complete actions from the contribution page (e.g. send receipt).
506 * @todo - most of this should live in the BAO layer but as we want it to be an addition
507 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
509 * @param array $params
512 * @throws API_Exception
515 function civicrm_api3_contribution_repeattransaction(&$params) {
516 $input = $ids = array();
517 $contribution = new CRM_Contribute_BAO_Contribution();
518 $contribution->id
= $params['original_contribution_id'];
519 if (!$contribution->find(TRUE)) {
520 throw new API_Exception(
521 'A valid original contribution ID is required', 'invalid_data');
523 $original_contribution = clone $contribution;
525 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
526 throw new API_Exception('failed to load related objects');
529 unset($contribution->id
, $contribution->receive_date
, $contribution->invoice_id
);
530 $contribution->contribution_status_id
= $params['contribution_status_id'];
531 $contribution->receive_date
= $params['receive_date'];
533 $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount');
534 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
536 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
538 catch(Exception
$e) {
539 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
544 * Calls IPN complete transaction for completing or repeating a transaction.
546 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
547 * when separating them in the api layer.
549 * @param array $params
550 * @param CRM_Contribute_BAO_Contribution $contribution
551 * @param array $input
555 * @param CRM_Contribute_BAO_Contribution $firstContribution
559 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
560 $objects = $contribution->_relatedObjects
;
561 $objects['contribution'] = &$contribution;
563 if ($firstContribution) {
564 $objects['first_contribution'] = $firstContribution;
566 $input['component'] = $contribution->_component
;
567 $input['is_test'] = $contribution->is_test
;
568 $input['amount'] = empty($input['total_amount']) ?
$contribution->total_amount
: $input['total_amount'];
570 if (isset($params['is_email_receipt'])) {
571 $input['is_email_receipt'] = $params['is_email_receipt'];
573 if (!empty($params['trxn_date'])) {
574 $input['trxn_date'] = $params['trxn_date'];
576 if (empty($contribution->contribution_page_id
)) {
577 static $domainFromName;
578 static $domainFromEmail;
579 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) ||
empty($params['receipt_from_email']))) {
580 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE);
582 $input['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $params, $domainFromName);
583 $input['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $params, $domainFromEmail);
585 $transaction = new CRM_Core_Transaction();
586 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
), $contribution,
592 * Provide function metadata.
594 * @param array $params
596 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
597 $params['original_contribution_id'] = array(
598 'title' => 'Original Contribution ID',
599 'type' => CRM_Utils_Type
::T_INT
,
600 'api.required' => TRUE,
602 $params['trxn_id'] = array(
603 'title' => 'Transaction ID',
604 'type' => CRM_Utils_Type
::T_STRING
,
606 $params['is_email_receipt'] = array(
607 'title' => 'Send email Receipt?',
608 'type' => CRM_Utils_Type
::T_BOOLEAN
,
610 $params['contribution_status_id'] = array(
611 'title' => 'Contribution Status ID',
612 'name' => 'contribution_status_id',
613 'type' => CRM_Utils_Type
::T_INT
,
614 'pseudoconstant' => array(
615 'optionGroupName' => 'contribution_status',
617 'api.required' => TRUE,
619 $params['receive_date'] = array(
620 'title' => 'Contribution Receive Date',
621 'name' => 'receive_date',
622 'type' => CRM_Utils_Type
::T_DATE
,
623 'api.default' => 'now',
625 $params['trxn_id'] = array(
626 'title' => 'Transaction ID',
628 'type' => CRM_Utils_Type
::T_STRING
,
630 $params['payment_processor_id'] = array(
631 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
632 'title' => 'Payment processor ID',
633 'name' => 'payment_processor_id',
634 'type' => CRM_Utils_Type
::T_INT
,