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 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
195 return civicrm_api3_create_success(array($contributionID => 1));
198 return civicrm_api3_create_error('Could not delete contribution');
203 * Modify metadata for delete action.
205 * Legacy support for contribution_id.
207 * @param array $params
209 function _civicrm_api3_contribution_delete_spec(&$params) {
210 $params['id']['api.aliases'] = array('contribution_id');
214 * Retrieve a set of contributions.
216 * @param array $params
220 * Array of contributions, if error an array with an error id and error message
222 function civicrm_api3_contribution_get($params) {
224 $mode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
225 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
227 $contribution = array();
228 while ($dao->fetch()) {
230 $contribution_details = $query->store($dao);
231 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
232 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
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.
242 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
243 * but we still return first soft credit as a part of contribution array
245 * @param $contribution
247 function _civicrm_api3_format_soft_credit(&$contribution) {
248 if (!empty($contribution['soft_credit'])) {
249 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
250 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
255 * Adjust Metadata for Get action.
257 * The metadata is used for setting defaults, documentation & validation.
259 * @param array $params
260 * Array of parameters determined by getfields.
262 function _civicrm_api3_contribution_get_spec(&$params) {
263 $params['contribution_test'] = array(
265 'type' => CRM_Utils_Type
::T_BOOLEAN
,
266 'title' => 'Get Test Contributions?',
267 'api.aliases' => array('is_test'),
270 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
271 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
272 $params['contact_id'] = $params['contribution_contact_id'];
273 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
274 unset($params['contribution_contact_id']);
278 * Legacy handling for contribution parameters.
280 * Take the input parameter list as specified in the data model and
281 * convert it into the same format that we use in QF and BAO object.
283 * @param array $params
284 * property name/value pairs to insert in new contact.
285 * @param array $values
286 * The reformatted properties that we can use internally.
290 function _civicrm_api3_contribute_format_params($params, &$values) {
291 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
292 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
297 * Adjust Metadata for Transact action.
299 * The metadata is used for setting defaults, documentation & validation.
301 * @param array $params
302 * Array of parameters determined by getfields.
304 function _civicrm_api3_contribution_transact_spec(&$params) {
305 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
306 $params = array_merge($params, $fields['values']);
307 $params['receive_date']['api.default'] = 'now';
311 * Process a transaction and record it against the contact.
313 * @param array $params
317 * contribution of created or updated record (or a civicrm error)
319 function civicrm_api3_contribution_transact($params) {
320 // Set some params specific to payment processing
321 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
323 // also trxn_id is not saved.
324 // but since there is no test it's not desirable to jump in & make the obvious changes.
325 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
326 $params['amount'] = $params['total_amount'];
327 if (!isset($params['net_amount'])) {
328 $params['net_amount'] = $params['amount'];
330 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
331 $params['invoiceID'] = $params['invoice_id'];
334 // Some payment processors expect a unique invoice_id - generate one if not supplied
335 $params['invoice_id'] = CRM_Utils_Array
::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
337 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
338 $paymentProcessor['object']->doPayment($params);
340 $params['payment_instrument_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ?
'Credit Card' : 'Debit Card';
341 return civicrm_api('Contribution', 'create', $params);
345 * Send a contribution confirmation (receipt or invoice).
347 * The appropriate online template will be used (the existence of related objects
348 * (e.g. memberships ) will affect this selection
350 * @param array $params
355 function civicrm_api3_contribution_sendconfirmation($params) {
356 $contribution = new CRM_Contribute_BAO_Contribution();
357 $contribution->id
= $params['id'];
358 if (!$contribution->find(TRUE)) {
359 throw new Exception('Contribution does not exist');
361 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
362 $contribution->loadRelatedObjects($input, $ids, TRUE);
363 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
367 * Adjust Metadata for sendconfirmation action.
369 * The metadata is used for setting defaults, documentation & validation.
371 * @param array $params
372 * Array of parameters determined by getfields.
374 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
375 $params['id'] = array(
377 'title' => 'Contribution ID',
378 'type' => CRM_Utils_Type
::T_INT
,
380 $params['receipt_from_email'] = array(
382 'title' => 'From Email address (string) required until someone provides a patch :-)',
383 'type' => CRM_Utils_Type
::T_STRING
,
385 $params['receipt_from_name'] = array(
386 'title' => 'From Name (string)',
387 'type' => CRM_Utils_Type
::T_STRING
,
389 $params['cc_receipt'] = array(
390 'title' => 'CC Email address (string)',
391 'type' => CRM_Utils_Type
::T_STRING
,
393 $params['bcc_receipt'] = array(
394 'title' => 'BCC Email address (string)',
395 'type' => CRM_Utils_Type
::T_STRING
,
397 $params['receipt_text'] = array(
398 'title' => 'Message (string)',
399 'type' => CRM_Utils_Type
::T_STRING
,
404 * Complete an existing (pending) transaction.
406 * This will update related entities (participant, membership, pledge etc)
407 * and take any complete actions from the contribution page (e.g. send receipt).
409 * @todo - most of this should live in the BAO layer but as we want it to be an addition
410 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
412 * @param array $params
415 * @throws API_Exception
418 function civicrm_api3_contribution_completetransaction(&$params) {
420 $input = $ids = array();
421 if (isset($params['payment_processor_id'])) {
422 $input['payment_processor_id'] = $params['payment_processor_id'];
424 $contribution = new CRM_Contribute_BAO_Contribution();
425 $contribution->id
= $params['id'];
426 $contribution->find(TRUE);
427 if (!$contribution->id
== $params['id']) {
428 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
431 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
432 throw new API_Exception('failed to load related objects');
434 elseif ($contribution->contribution_status_id
== CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
435 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
437 $input['trxn_id'] = !empty($params['trxn_id']) ?
$params['trxn_id'] : $contribution->trxn_id
;
438 if (!empty($params['fee_amount'])) {
439 $input['fee_amount'] = $params['fee_amount'];
441 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
446 * Provide function metadata.
448 * @param array $params
450 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
451 $params['id'] = array(
452 'title' => 'Contribution ID',
453 'type' => CRM_Utils_Type
::T_INT
,
454 'api.required' => TRUE,
456 $params['trxn_id'] = array(
457 'title' => 'Transaction ID',
458 'type' => CRM_Utils_Type
::T_STRING
,
460 $params['is_email_receipt'] = array(
461 'title' => 'Send email Receipt?',
462 'type' => CRM_Utils_Type
::T_BOOLEAN
,
464 $params['receipt_from_email'] = array(
465 'title' => 'Email to send receipt from.',
466 'description' => 'If not provided this will default to being based on domain mail or contribution page',
467 'type' => CRM_Utils_Type
::T_EMAIL
,
469 $params['receipt_from_name'] = array(
470 'title' => 'Name to send receipt from',
471 'description' => '. If not provided this will default to domain mail or contribution page',
472 'type' => CRM_Utils_Type
::T_STRING
,
474 $params['payment_processor_id'] = array(
475 'title' => 'Payment processor ID',
476 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
477 'type' => CRM_Utils_Type
::T_INT
,
479 $params['fee_amount'] = array(
480 'title' => 'Fee charged on transaction',
481 'description' => 'If a fee has been charged then the amount',
482 'type' => CRM_Utils_Type
::T_FLOAT
,
484 $params['trxn_date'] = array(
485 'title' => 'Transaction Date',
486 'description' => 'Date this transaction occurred',
487 'type' => CRM_Utils_Type
::T_DATE
,
492 * Complete an existing (pending) transaction.
494 * This will update related entities (participant, membership, pledge etc)
495 * and take any complete actions from the contribution page (e.g. send receipt).
497 * @todo - most of this should live in the BAO layer but as we want it to be an addition
498 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
500 * @param array $params
503 * @throws API_Exception
506 function civicrm_api3_contribution_repeattransaction(&$params) {
507 $input = $ids = array();
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, 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');
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'];
561 if (isset($params['is_email_receipt'])) {
562 $input['is_email_receipt'] = $params['is_email_receipt'];
564 if (!empty($params['trxn_date'])) {
565 $input['trxn_date'] = $params['trxn_date'];
567 if (empty($contribution->contribution_page_id
)) {
568 static $domainFromName;
569 static $domainFromEmail;
570 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) ||
empty($params['receipt_from_email']))) {
571 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE);
573 $input['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $params, $domainFromName);
574 $input['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $params, $domainFromEmail);
576 $transaction = new CRM_Core_Transaction();
577 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id
), $contribution,
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 'type' => CRM_Utils_Type
::T_INT
,
591 'api.required' => TRUE,
593 $params['trxn_id'] = array(
594 'title' => 'Transaction ID',
595 'type' => CRM_Utils_Type
::T_STRING
,
597 $params['is_email_receipt'] = array(
598 'title' => 'Send email Receipt?',
599 'type' => CRM_Utils_Type
::T_BOOLEAN
,
601 $params['contribution_status_id'] = array(
602 'title' => 'Contribution Status ID',
603 'name' => 'contribution_status_id',
604 'type' => CRM_Utils_Type
::T_INT
,
605 'pseudoconstant' => array(
606 'optionGroupName' => 'contribution_status',
608 'api.required' => TRUE,
610 $params['receive_date'] = array(
611 'title' => 'Contribution Receive Date',
612 'name' => 'receive_date',
613 'type' => CRM_Utils_Type
::T_DATE
,
614 'api.default' => 'now',
616 $params['trxn_id'] = array(
617 'title' => 'Transaction ID',
619 'type' => CRM_Utils_Type
::T_STRING
,
621 $params['payment_processor_id'] = array(
622 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
623 'title' => 'Payment processor ID',
624 'name' => 'payment_processor_id',
625 'type' => CRM_Utils_Type
::T_INT
,