CRM-15496 api contribution.complete_transaction improve recurring handling
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
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. |
14 | |
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. |
19 | |
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 +--------------------------------------------------------------------+
27 */
28
29 /**
30 * File for the CiviCRM APIv3 Contribution functions
31 *
32 * @package CiviCRM_APIv3
33 * @subpackage API_Contribute
34 *
35 * @copyright CiviCRM LLC (c) 2004-2014
36 * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
37 *
38 */
39
40 /**
41 * Add or update a contribution
42 *
43 * @param array $params (reference ) input parameters
44 *
45 * @throws API_Exception
46 * @return array Api result array
47 * @static void
48 * @access public
49 * @example ContributionCreate.php
50 * {@getfields Contribution_create}
51 */
52 function civicrm_api3_contribution_create(&$params) {
53 $values = array();
54 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
55 $params = array_merge($params, $values);
56
57 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
58 $error = array();
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']);
65 }
66 }
67
68 _civicrm_api3_contribution_create_legacy_support_45($params);
69
70 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
71 }
72
73 /**
74 * Adjust Metadata for Create action
75 *
76 * The metadata is used for setting defaults, documentation & validation
77 * @param array $params array or parameters determined by getfields
78 */
79 function _civicrm_api3_contribution_create_spec(&$params) {
80 $params['contact_id']['api.required'] = 1;
81 $params['total_amount']['api.required'] = 1;
82 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
83 $params['receive_date']['api.default'] = 'now';
84 $params['payment_processor'] = array(
85 'name' => 'payment_processor',
86 'title' => 'Payment Processor ID',
87 'description' => 'ID of payment processor used for this contribution',
88 // field is called payment processor - not payment processor id but can only be one id so
89 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
90 'api.aliases' => array('payment_processor_id'),
91 );
92 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
93 $params['financial_type_id']['api.required'] = 1;
94 $params['note'] = array(
95 'name' => 'note',
96 'uniqueName' => 'contribution_note',
97 'title' => 'note',
98 'type' => 2,
99 'description' => 'Associated Note in the notes table',
100 );
101 $params['soft_credit_to'] = array(
102 'name' => 'soft_credit_to',
103 'title' => 'Soft Credit contact ID',
104 'type' => 1,
105 'description' => 'ID of Contact to be Soft credited to',
106 'FKClassName' => 'CRM_Contact_DAO_Contact',
107 );
108 $params['honor_contact_id'] = array(
109 'name' => 'honor_contact_id',
110 'title' => 'Honoree contact ID',
111 'type' => 1,
112 'description' => 'ID of honoree contact',
113 'FKClassName' => 'CRM_Contact_DAO_Contact',
114 );
115 // note this is a recommended option but not adding as a default to avoid
116 // creating unnecessary changes for the dev
117 $params['skipRecentView'] = array(
118 'name' => 'skipRecentView',
119 'title' => 'Skip adding to recent view',
120 'type' => CRM_Utils_Type::T_BOOLEAN,
121 'description' => 'Do not add to recent view (setting this improves performance)',
122 );
123 $params['skipLineItem'] = array(
124 'name' => 'skipLineItem',
125 'title' => 'Skip adding line items',
126 'type' => 1,
127 'api.default' => 0,
128 'description' => 'Do not add line items by default (if you wish to add your own)',
129 );
130 $params['batch_id'] = array(
131 'title' => 'Batch',
132 'type' => 1,
133 'description' => 'Batch which relevant transactions should be added to',
134 );
135 }
136
137 /**
138 * Support for schema changes made in 4.5
139 * The main purpose of the API is to provide integrators a level of stability not provided by
140 * the core code or schema - this means we have to provide support for api calls (where possible)
141 * across schema changes.
142 */
143 function _civicrm_api3_contribution_create_legacy_support_45(&$params){
144 //legacy soft credit handling - recommended approach is chaining
145 if(!empty($params['soft_credit_to'])){
146 $params['soft_credit'] = array(array(
147 'contact_id' => $params['soft_credit_to'],
148 'amount' => $params['total_amount'],
149 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type")));
150 }
151 if(!empty($params['honor_contact_id'])){
152 $params['soft_credit'] = array(array(
153 'contact_id' => $params['honor_contact_id'],
154 'amount' => $params['total_amount'],
155 'soft_credit_type_id' => CRM_Core_OptionGroup::getValue('soft_credit_type', 'in_honor_of', 'name')));
156 }
157 }
158
159 /**
160 * Delete a contribution
161 *
162 * @param array $params (reference ) input parameters
163 *
164 * @return boolean true if success, else false
165 * @static void
166 * @access public
167 * {@getfields Contribution_delete}
168 * @example ContributionDelete.php
169 */
170 function civicrm_api3_contribution_delete($params) {
171
172 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
173 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
174 return civicrm_api3_create_success(array($contributionID => 1));
175 }
176 else {
177 return civicrm_api3_create_error('Could not delete contribution');
178 }
179 }
180
181 /**
182 * modify metadata. Legacy support for contribution_id
183 */
184 function _civicrm_api3_contribution_delete_spec(&$params) {
185 $params['id']['api.aliases'] = array('contribution_id');
186 }
187
188 /**
189 * Retrieve a set of contributions, given a set of input params
190 *
191 * @param array $params (reference ) input parameters
192 *
193 * @internal param array $returnProperties Which properties should be included in the
194 * returned Contribution object. If NULL, the default
195 * set of properties will be included.
196 *
197 * @return array (reference ) array of contributions, if error an array with an error id and error message
198 * @static void
199 * @access public
200 * {@getfields Contribution_get}
201 * @example ContributionGet.php
202 */
203 function civicrm_api3_contribution_get($params) {
204
205 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
206 $entity = 'contribution';
207 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
208
209 $contribution = array();
210 while ($dao->fetch()) {
211 //CRM-8662
212 $contribution_details = $query->store($dao);
213 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id , TRUE);
214 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
215 if(isset($contribution[$dao->contribution_id]['financial_type_id'])){
216 $contribution[$dao->contribution_id]['financial_type_id'] = $contribution[$dao->contribution_id]['financial_type_id'];
217 }
218 // format soft credit for backward compatibility
219 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
220 }
221 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
222 }
223
224 /**
225 * This function is used to format the soft credit for backward compatibility
226 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
227 * but we still return first soft credit as a part of contribution array
228 */
229 function _civicrm_api3_format_soft_credit(&$contribution) {
230 if (!empty($contribution['soft_credit'])) {
231 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
232 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
233 }
234 }
235
236 /**
237 * Adjust Metadata for Get action
238 *
239 * The metadata is used for setting defaults, documentation & validation
240 * @param array $params array or parameters determined by getfields
241 */
242 function _civicrm_api3_contribution_get_spec(&$params) {
243 $params['contribution_test']['api.default'] = 0;
244 $params['contribution_test']['title'] = 'Get Test Contributions?';
245 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
246 $params['contact_id'] = $params['contribution_contact_id'];
247 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
248 unset($params['contribution_contact_id']);
249 }
250
251 /**
252 * take the input parameter list as specified in the data model and
253 * convert it into the same format that we use in QF and BAO object
254 *
255 * @param array $params Associative array of property name/value
256 * pairs to insert in new contact.
257 * @param array $values The reformatted properties that we can use internally
258 * '
259 *
260 * @param bool $create
261 *
262 * @return array|CRM_Error
263 * @access public
264 */
265 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
266 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
267 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
268 return array();
269 }
270
271 /**
272 * Adjust Metadata for Transact action
273 *
274 * The metadata is used for setting defaults, documentation & validation
275 * @param array $params array or parameters determined by getfields
276 */
277 function _civicrm_api3_contribution_transact_spec(&$params) {
278 $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
279 $params = array_merge($params, $fields['values']);
280 $params['receive_date']['api.default'] = 'now';
281 }
282
283 /**
284 * Process a transaction and record it against the contact.
285 *
286 * @param array $params (reference ) input parameters
287 *
288 * @return array (reference ) contribution of created or updated record (or a civicrm error)
289 * @static void
290 * @access public
291 *
292 */
293 function civicrm_api3_contribution_transact($params) {
294 // Set some params specific to payment processing
295 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
296 $params['amount'] = $params['total_amount'];
297 if (!isset($params['net_amount'])) {
298 $params['net_amount'] = $params['amount'];
299 }
300 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
301 $params['invoiceID'] = $params['invoice_id'];
302 }
303
304 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
305 if (civicrm_error($paymentProcessor)) {
306 return $paymentProcessor;
307 }
308
309 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
310 if (civicrm_error($payment)) {
311 return $payment;
312 }
313
314 $transaction = $payment->doDirectPayment($params);
315 if (civicrm_error($transaction)) {
316 return $transaction;
317 }
318
319 // but actually, $payment->doDirectPayment() doesn't return a
320 // CRM_Core_Error by itself
321 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
322 $errs = $transaction->getErrors();
323 if (!empty($errs)) {
324 $last_error = array_shift($errs);
325 return CRM_Core_Error::createApiError($last_error['message']);
326 }
327 }
328 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
329 return civicrm_api('contribution', 'create', $params);
330 }
331
332 /**
333 * Send a contribution confirmation (receipt or invoice)
334 * The appropriate online template will be used (the existence of related objects
335 * (e.g. memberships ) will affect this selection
336 *
337 * @param array $params input parameters
338 * {@getfields Contribution_sendconfirmation}
339 *
340 * @throws Exception
341 * @return array Api result array
342 * @static void
343 * @access public
344 */
345 function civicrm_api3_contribution_sendconfirmation($params) {
346 $contribution = new CRM_Contribute_BAO_Contribution();
347 $contribution->id = $params['id'];
348 if (! $contribution->find(TRUE)) {
349 throw new Exception('Contribution does not exist');
350 }
351 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
352 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
353 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
354 }
355
356 /**
357 * Adjust Metadata for sendconfirmation action
358 *
359 * The metadata is used for setting defaults, documentation & validation
360 * @param array $params array or parameters determined by getfields
361 */
362 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
363 $params['id'] = array(
364 'api.required' => 1,
365 'title' => 'Contribution ID'
366 );
367 $params['receipt_from_email'] = array(
368 'api.required' =>1,
369 'title' => 'From Email address (string) required until someone provides a patch :-)',
370 );
371 $params['receipt_from_name'] = array(
372 'title' => 'From Name (string)',
373 );
374 $params['cc_receipt'] = array(
375 'title' => 'CC Email address (string)',
376 );
377 $params['bcc_receipt'] = array(
378 'title' => 'BCC Email address (string)',
379 );
380 $params['receipt_text'] = array(
381 'title' => 'Message (string)',
382 );
383 }
384
385 /**
386 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
387 * and taking any complete actions from the contribution page (e.g. send receipt)
388 *
389 * @todo - most of this should live in the BAO layer but as we want it to be an addition
390 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
391 *
392 * @param array $params input parameters
393 * {@getfields Contribution_completetransaction}
394 *
395 * @throws API_Exception
396 * @return array Api result array
397 * @static void
398 * @access public
399 */
400 function civicrm_api3_contribution_completetransaction(&$params) {
401
402 $input = $ids = array();
403 $contribution = new CRM_Contribute_BAO_Contribution();
404 $contribution->id = $params['id'];
405 $contribution->find(TRUE);
406 if(!$contribution->id == $params['id']){
407 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
408 }
409 try {
410 if(!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)){
411 throw new API_Exception('failed to load related objects');
412 }
413 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
414 throw new API_Exception(ts('Contribution already completed'));
415 }
416 $objects = $contribution->_relatedObjects;
417 $objects['contribution'] = &$contribution;
418 $input['component'] = $contribution->_component;
419 $input['is_test'] = $contribution->is_test;
420 $input['trxn_id']= !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
421 $input['amount'] = $contribution->total_amount;
422 if(isset($params['is_email_receipt'])){
423 $input['is_email_receipt'] = $params['is_email_receipt'];
424 }
425 // @todo required for base ipn but problematic as api layer handles this
426 $transaction = new CRM_Core_Transaction();
427 $ipn = new CRM_Core_Payment_BaseIPN();
428 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
429 }
430 catch(Exception $e) {
431 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
432 }
433 }
434
435 /**
436 * @param $params
437 */
438 function _civicrm_api3_contribution_completetransaction(&$params) {
439 $params['id'] = array(
440 'title' => 'Contribution ID',
441 'type' => CRM_Utils_Type::T_INT,
442 'api.required' => TRUE,
443 );
444 $params['trxn_id'] = array(
445 'title' => 'Transaction ID',
446 'type' => CRM_Utils_Type::T_STRING,
447 );
448 $params['is_email_receipt'] = array(
449 'title' => 'Send email Receipt?',
450 'type' => CRM_Utils_Type::T_BOOLEAN,
451 );
452 }