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 * Class CRM_Core_Payment_BaseIPN.
31 class CRM_Core_Payment_BaseIPN
{
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
40 protected $_inputParameters = array();
42 protected $_isRecurring = FALSE;
44 protected $_isFirstOrLastRecurringPayment = FALSE;
49 public function __construct() {
50 self
::$_now = date('YmdHis');
54 * Store input array on the class.
56 * @param array $parameters
58 * @throws CRM_Core_Exception
60 public function setInputParameters($parameters) {
61 if (!is_array($parameters)) {
62 throw new CRM_Core_Exception('Invalid input parameters');
64 $this->_inputParameters
= $parameters;
68 * Validate incoming data.
70 * This function is intended to ensure that incoming data matches
71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
78 * Interpreted values from the values returned through the IPN.
80 * More interpreted values (ids) from the values returned through the IPN.
81 * @param array $objects
82 * An empty array that will be populated with loaded object.
83 * @param bool $required
84 * Boolean Return FALSE if the relevant objects don't exist.
85 * @param int $paymentProcessorID
86 * Id of the payment processor ID in use.
90 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
92 // make sure contact exists and is valid
93 $contact = new CRM_Contact_BAO_Contact();
94 $contact->id
= $ids['contact'];
95 if (!$contact->find(TRUE)) {
96 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
97 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
101 // make sure contribution exists and is valid
102 $contribution = new CRM_Contribute_BAO_Contribution();
103 $contribution->id
= $ids['contribution'];
104 if (!$contribution->find(TRUE)) {
105 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
106 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
109 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
111 $objects['contact'] = &$contact;
112 $objects['contribution'] = &$contribution;
113 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
116 //the process is that the loadObjects is kind of hacked by loading the objects for the original contribution and then somewhat inconsistently using them for the
117 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
118 //we don't want to fix this in the payment processor classes because we would have to fix all of them - so better to fix somewhere central
119 if (isset($objects['contributionRecur'])) {
120 $objects['first_contribution'] = $objects['contribution'];
126 * Load objects related to contribution.
128 * @input array information from Payment processor
132 * @param array $objects
133 * @param bool $required
134 * @param int $paymentProcessorID
135 * @param array $error_handling
139 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
140 if (empty($error_handling)) {
141 // default options are that we log an error & echo it out
142 // note that we should refactor this error handling into error code @ some point
143 // but for now setting up enough separation so we can do unit tests
144 $error_handling = array(
149 $ids['paymentProcessor'] = $paymentProcessorID;
150 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
151 $contribution = &$objects['contribution'];
154 //legacy support - functions are 'used' to be able to pass in a DAO
155 $contribution = new CRM_Contribute_BAO_Contribution();
156 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
157 $contribution->find(TRUE);
158 $objects['contribution'] = &$contribution;
161 $success = $contribution->loadRelatedObjects($input, $ids, $required);
163 catch (Exception
$e) {
165 if (!empty($error_handling['log_error'])) {
166 CRM_Core_Error
::debug_log_message($e->getMessage());
168 if (!empty($error_handling['echo_error'])) {
169 echo $e->getMessage();
171 if (!empty($error_handling['return_error'])) {
174 'error_message' => ($e->getMessage()),
178 $objects = array_merge($objects, $contribution->_relatedObjects
);
183 * Set contribution to failed.
185 * @param array $objects
186 * @param object $transaction
187 * @param array $input
191 public function failed(&$objects, &$transaction, $input = array()) {
192 $contribution = &$objects['contribution'];
193 $memberships = array();
194 if (!empty($objects['membership'])) {
195 $memberships = &$objects['membership'];
196 if (is_numeric($memberships)) {
197 $memberships = array($objects['membership']);
201 $addLineItems = FALSE;
202 if (empty($contribution->id
)) {
203 $addLineItems = TRUE;
205 $participant = &$objects['participant'];
208 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
209 'labelColumn' => 'name',
212 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
213 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
214 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
215 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
216 $contribution->save();
218 // Add line items for recurring payments.
219 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
220 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
223 //add new soft credit against current contribution id and
224 //copy initial contribution custom fields for recurring contributions
225 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
226 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
227 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
230 if (empty($input['skipComponentSync'])) {
231 if (!empty($memberships)) {
232 // if transaction is failed then set "Cancelled" as membership status
233 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array(
234 'labelColumn' => 'name',
237 foreach ($memberships as $membership) {
239 $membership->status_id
= $membershipStatuses['Cancelled'];
242 //update related Memberships.
243 $params = array('status_id' => $membershipStatuses['Cancelled']);
244 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
250 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
251 'labelColumn' => 'name',
254 $participant->status_id
= $participantStatuses['Cancelled'];
255 $participant->save();
259 $transaction->commit();
260 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
261 //echo "Success: Setting contribution status to failed<p>";
266 * Handled pending contribution status.
268 * @param array $objects
269 * @param object $transaction
273 public function pending(&$objects, &$transaction) {
274 $transaction->commit();
275 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
276 echo "Success: Returning since contribution status is pending<p>";
281 * Process cancelled payment outcome.
284 * @param $transaction
285 * @param array $input
289 public function cancelled(&$objects, &$transaction, $input = array()) {
290 $contribution = &$objects['contribution'];
291 $memberships = &$objects['membership'];
292 if (is_numeric($memberships)) {
293 $memberships = array($objects['membership']);
296 $participant = &$objects['participant'];
297 $addLineItems = FALSE;
298 if (empty($contribution->id
)) {
299 $addLineItems = TRUE;
301 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
302 'labelColumn' => 'name',
305 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
306 $contribution->cancel_date
= self
::$_now;
307 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
308 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
309 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
310 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
311 $contribution->save();
313 //add lineitems for recurring payments
314 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
315 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
318 //add new soft credit against current $contribution and
319 //copy initial contribution custom fields for recurring contributions
320 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
321 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
322 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
325 if (empty($input['skipComponentSync'])) {
326 if (!empty($memberships)) {
327 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array(
328 'labelColumn' => 'name',
331 foreach ($memberships as $membership) {
333 $membership->status_id
= $membershipStatuses['Cancelled'];
336 //update related Memberships.
337 $params = array('status_id' => $membershipStatuses['Cancelled']);
338 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
344 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
345 'labelColumn' => 'name',
348 $participant->status_id
= $participantStatuses['Cancelled'];
349 $participant->save();
352 $transaction->commit();
353 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
354 //echo "Success: Setting contribution status to cancelled<p>";
359 * Rollback unhandled outcomes.
362 * @param $transaction
366 public function unhandled(&$objects, &$transaction) {
367 $transaction->rollback();
368 CRM_Core_Error
::debug_log_message("returning since contribution status: is not handled");
369 echo "Failure: contribution status is not handled<p>";
374 * Jumbled up function.
376 * The purpose of this function is to transition a pending transaction to Completed including updating any
379 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
380 * updating related entities.
382 * It is recommended to avoid calling this function directly and call the api functions:
383 * - contribution.completetransaction
384 * - contribution.repeattransaction
386 * These functions are the focus of testing efforts and more accurately reflect the division of roles
387 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
388 * and from there it should be possible to pass off transaction management.)
390 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
391 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
393 * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo
394 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
395 * a shared function that updates related components.
397 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
398 * IPN class is better accessed through the api which de-jumbles it a bit.
400 * e.g the payment class can have a function like (based on Omnipay extension):
402 * public function handlePaymentNotification() {
403 * $response = $this->getValidatedOutcome();
404 * if ($response->isSuccessful()) {
406 * // @todo check if it is a repeat transaction & call repeattransaction instead.
407 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
409 * catch (CiviCRM_API3_Exception $e) {
410 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
411 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
412 * have occurred. Please check your receipt is correct');
413 * $this->redirectOrExit('success');
415 * elseif ($this->transaction_id) {
416 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
420 * @param array $input
422 * @param array $objects
423 * @param $transaction
426 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
427 $isRecurring = $this->_isRecurring
;
428 $isFirstOrLastRecurringPayment = $this->_isFirstOrLastRecurringPayment
;
429 $contribution = &$objects['contribution'];
431 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects, $transaction, $recur, $contribution,
432 $isRecurring, $isFirstOrLastRecurringPayment);
436 * Get site billing ID.
442 public function getBillingID(&$ids) {
443 // get the billing location type
444 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
445 // CRM-8108 remove the ts around the Billing location type
446 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
447 $ids['billing'] = array_search('Billing', $locationTypes);
448 if (!$ids['billing']) {
449 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
450 echo "Failure: Could not find billing location type<p>";
457 * Send receipt from contribution.
461 * Note that the compose message part has been moved to contribution
462 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
464 * @param array $input
465 * Incoming data from Payment processor.
467 * Related object IDs.
469 * @param array $values
470 * Values related to objects that have already been loaded.
472 * Is it part of a recurring contribution.
473 * @param bool $returnMessageText
474 * Should text be returned instead of sent. This.
475 * is because the function is also used to generate pdfs
479 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
480 return CRM_Contribute_BAO_Contribution
::sendMail($input, $ids, $objects, $values, $recur, $returnMessageText);