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 * Added by Ward; basic filter-able contribution list
207 * use filter.receive_date_high etc
210 function civicrm_api3_contribution_list($params) {
211 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
215 * Retrieve a set of contributions, given a set of input params
217 * @param array $params (reference ) input parameters
218 * @param array $returnProperties Which properties should be included in the
219 * returned Contribution object. If NULL, the default
220 * set of properties will be included.
222 * @return array (reference ) array of contributions, if error an array with an error id and error message
225 * {@getfields Contribution_get}
226 * @example ContributionGet.php
228 function civicrm_api3_contribution_get($params) {
230 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
231 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
233 $contribution = array();
234 while ($dao->fetch()) {
236 $contribution_details = $query->store($dao);
237 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
238 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
239 // format soft credit for backward compatibility
240 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
242 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
246 * This function is used to format the soft credit for backward compatibility.
248 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
249 * but we still return first soft credit as a part of contribution array
251 * @param $contribution
253 function _civicrm_api3_format_soft_credit(&$contribution) {
254 if (!empty($contribution['soft_credit'])) {
255 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
256 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
261 * Adjust Metadata for Get action.
263 * The metadata is used for setting defaults, documentation & validation.
265 * @param array $params
266 * Array of parameters determined by getfields.
268 function _civicrm_api3_contribution_get_spec(&$params) {
269 $params['contribution_test'] = array(
271 'type' => CRM_Utils_Type
::T_BOOLEAN
,
272 'title' => 'Get Test Contributions?',
274 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
275 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
276 $params['contact_id'] = $params['contribution_contact_id'];
277 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
278 unset($params['contribution_contact_id']);
282 * Legacy handling for contribution parameters.
284 * Take the input parameter list as specified in the data model and
285 * convert it into the same format that we use in QF and BAO object.
287 * @param array $params
288 * property name/value pairs to insert in new contact.
289 * @param array $values
290 * The reformatted properties that we can use internally.
294 function _civicrm_api3_contribute_format_params($params, &$values) {
295 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
296 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
301 * Adjust Metadata for Transact action.
303 * The metadata is used for setting defaults, documentation & validation.
305 * @param array $params
306 * Array of parameters determined by getfields.
308 function _civicrm_api3_contribution_transact_spec(&$params) {
309 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
310 $params = array_merge($params, $fields['values']);
311 $params['receive_date']['api.default'] = 'now';
315 * Process a transaction and record it against the contact.
317 * @param array $params
321 * contribution of created or updated record (or a civicrm error)
323 function civicrm_api3_contribution_transact($params) {
324 // Set some params specific to payment processing
325 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
327 // also trxn_id is not saved.
328 // but since there is no test it's not desirable to jump in & make the obvious changes.
329 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
330 $params['amount'] = $params['total_amount'];
331 if (!isset($params['net_amount'])) {
332 $params['net_amount'] = $params['amount'];
334 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
335 $params['invoiceID'] = $params['invoice_id'];
338 // Some payment processors expect a unique invoice_id - generate one if not supplied
339 $params['invoice_id'] = CRM_Utils_Array
::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
341 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
342 if (civicrm_error($paymentProcessor)) {
343 return $paymentProcessor;
346 $payment = CRM_Core_Payment
::singleton($params['payment_processor_mode'], $paymentProcessor);
347 if (civicrm_error($payment)) {
351 $transaction = $payment->doPayment($params);
353 $params['payment_instrument_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ?
'Credit Card' : 'Debit Card';
354 return civicrm_api('Contribution', 'create', $params);
358 * Send a contribution confirmation (receipt or invoice).
360 * The appropriate online template will be used (the existence of related objects
361 * (e.g. memberships ) will affect this selection
363 * @param array $params
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.
384 * @param array $params
385 * Array of parameters determined by getfields.
387 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
388 $params['id'] = array(
390 'title' => 'Contribution ID',
391 'type' => CRM_Utils_Type
::T_INT
,
393 $params['receipt_from_email'] = array(
395 'title' => 'From Email address (string) required until someone provides a patch :-)',
396 'type' => CRM_Utils_Type
::T_STRING
,
398 $params['receipt_from_name'] = array(
399 'title' => 'From Name (string)',
400 'type' => CRM_Utils_Type
::T_STRING
,
402 $params['cc_receipt'] = array(
403 'title' => 'CC Email address (string)',
404 'type' => CRM_Utils_Type
::T_STRING
,
406 $params['bcc_receipt'] = array(
407 'title' => 'BCC Email address (string)',
408 'type' => CRM_Utils_Type
::T_STRING
,
410 $params['receipt_text'] = array(
411 'title' => 'Message (string)',
412 'type' => CRM_Utils_Type
::T_STRING
,
417 * Complete an existing (pending) transaction.
419 * This will update related entities (participant, membership, pledge etc)
420 * and take any complete actions from the contribution page (e.g. send receipt).
422 * @todo - most of this should live in the BAO layer but as we want it to be an addition
423 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
425 * @param array $params
428 * @throws API_Exception
431 function civicrm_api3_contribution_completetransaction(&$params) {
433 $input = $ids = array();
434 $contribution = new CRM_Contribute_BAO_Contribution();
435 $contribution->id
= $params['id'];
436 $contribution->find(TRUE);
437 if (!$contribution->id
== $params['id']) {
438 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
441 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
442 throw new API_Exception('failed to load related objects');
444 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
445 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
447 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
448 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
453 * Provide function metadata.
455 * @param array $params
457 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
458 $params['id'] = array(
459 'title' => 'Contribution ID',
460 'type' => CRM_Utils_Type
::T_INT
,
461 'api.required' => TRUE,
463 $params['trxn_id'] = array(
464 'title' => 'Transaction ID',
465 'type' => CRM_Utils_Type
::T_STRING
,
467 $params['is_email_receipt'] = array(
468 'title' => 'Send email Receipt?',
469 'type' => CRM_Utils_Type
::T_BOOLEAN
,
471 $params['receipt_from_email'] = array(
472 'title' => 'Email to send receipt from.',
473 'description' => 'If not provided this will default to being based on domain mail or contribution page',
474 'type' => CRM_Utils_Type
::T_EMAIL
,
476 $params['receipt_from_name'] = array(
477 'title' => 'Name to send receipt from',
478 'description' => '. If not provided this will default to domain mail or contribution page',
479 'type' => CRM_Utils_Type
::T_STRING
,
484 * Complete an existing (pending) transaction.
486 * This will update related entities (participant, membership, pledge etc)
487 * and take any complete actions from the contribution page (e.g. send receipt).
489 * @todo - most of this should live in the BAO layer but as we want it to be an addition
490 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
492 * @param array $params
495 * @throws API_Exception
498 function civicrm_api3_contribution_repeattransaction(&$params) {
499 $input = $ids = array();
500 civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
501 if (empty($params['original_contribution_id'])) {
502 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array(
504 'contribution_recur_id' => $params['contribution_recur_id'],
505 'options' => array('limit' => 1, 'sort' => 'id DESC'),
508 $contribution = new CRM_Contribute_BAO_Contribution();
509 $contribution->id
= $params['original_contribution_id'];
510 if (!$contribution->find(TRUE)) {
511 throw new API_Exception(
512 'A valid original contribution ID is required', 'invalid_data');
514 $original_contribution = clone $contribution;
516 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
517 throw new API_Exception('failed to load related objects');
520 unset($contribution->id
, $contribution->receive_date
, $contribution->invoice_id
);
521 $contribution->contribution_status_id
= $params['contribution_status_id'];
522 $contribution->receive_date
= $params['receive_date'];
524 $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount', 'financial_type_id');
525 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
527 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
529 catch(Exception
$e) {
530 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
535 * Calls IPN complete transaction for completing or repeating a transaction.
537 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
538 * when separating them in the api layer.
540 * @param array $params
541 * @param CRM_Contribute_BAO_Contribution $contribution
542 * @param array $input
546 * @param CRM_Contribute_BAO_Contribution $firstContribution
550 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
551 $objects = $contribution->_relatedObjects
;
552 $objects['contribution'] = &$contribution;
554 if ($firstContribution) {
555 $objects['first_contribution'] = $firstContribution;
557 $input['component'] = $contribution->_component
;
558 $input['is_test'] = $contribution->is_test
;
559 $input['amount'] = empty($input['total_amount']) ?
$contribution->total_amount
: $input['total_amount'];
560 if (isset($params['fee_amount'])) {
561 $input['fee_amount'] = $params['fee_amount'];
563 if (isset($params['is_email_receipt'])) {
564 $input['is_email_receipt'] = $params['is_email_receipt'];
566 if (empty($contribution->contribution_page_id
)) {
567 static $domainFromName;
568 static $domainFromEmail;
569 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) ||
empty($params['receipt_from_email']))) {
570 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE);
572 $input['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $params, $domainFromName);
573 $input['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $params, $domainFromEmail);
575 // @todo required for base ipn but problematic as api layer handles this
576 $transaction = new CRM_Core_Transaction();
577 $ipn = new CRM_Core_Payment_BaseIPN();
578 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
));
583 * Provide function metadata.
585 * @param array $params
587 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
588 $params['original_contribution_id'] = array(
589 'title' => 'Original Contribution ID',
590 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
591 'type' => CRM_Utils_Type
::T_INT
,
593 $params['contribution_recur_id'] = array(
594 'title' => 'Recurring contribution ID',
595 'type' => CRM_Utils_Type
::T_INT
,
597 $params['trxn_id'] = array(
598 'title' => 'Transaction ID',
599 'type' => CRM_Utils_Type
::T_STRING
,
601 $params['is_email_receipt'] = array(
602 'title' => 'Send email Receipt?',
603 'type' => CRM_Utils_Type
::T_BOOLEAN
,
605 $params['contribution_status_id'] = array(
606 'title' => 'Contribution Status ID',
607 'name' => 'contribution_status_id',
608 'type' => CRM_Utils_Type
::T_INT
,
609 'pseudoconstant' => array(
610 'optionGroupName' => 'contribution_status',
612 'api.required' => TRUE,
614 $params['receive_date'] = array(
615 'title' => 'Contribution Receive Date',
616 'name' => 'receive_date',
617 'type' => CRM_Utils_Type
::T_DATE
,
618 'api.default' => 'now',
620 $params['trxn_id'] = array(
621 'title' => 'Transaction ID',
623 'type' => CRM_Utils_Type
::T_STRING
,
625 $params['campaign_id'] = array(
626 'title' => 'Campaign ID',
627 'name' => 'campaign_id',
628 'type' => CRM_Utils_Type
::T_INT
,
629 'pseudoconstant' => array(
630 'table' => 'civicrm_campaign',
632 'labelColumn' => 'title',
635 $params['financial_type_id'] = array(
636 'title' => 'Financial ID (ignored if more than one line item)',
637 'name' => 'financial_type_id',
638 'type' => CRM_Utils_Type
::T_INT
,
639 'pseudoconstant' => array(
640 'table' => 'civicrm_financial_type',
642 'labelColumn' => 'name',
645 $params['payment_processor_id'] = array(
646 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
647 'title' => 'Payment processor ID',
648 'name' => 'payment_processor_id',
649 'type' => CRM_Utils_Type
::T_INT
,