Merge pull request #8526 from jitendrapurohit/CRM-18706
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
1d86918a 29 * Class CRM_Core_Payment_BaseIPN.
6a488035
TO
30 */
31class CRM_Core_Payment_BaseIPN {
32
33 static $_now = NULL;
8196c759 34
c8aa607b 35 /**
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
38 * @var array
39 */
40 protected $_inputParameters = array();
41
59cdadfc 42 /**
43 * Only used by AuthorizeNetIPN.
44 *
45 * @deprecated
46 *
47 * @var bool
48 */
937cf542
EM
49 protected $_isRecurring = FALSE;
50
59cdadfc 51 /**
52 * Only used by AuthorizeNetIPN.
53 *
54 * @deprecated
55 *
56 * @var bool
57 */
937cf542 58 protected $_isFirstOrLastRecurringPayment = FALSE;
353ffa53 59
8196c759 60 /**
fe482240 61 * Constructor.
8196c759 62 */
00be9182 63 public function __construct() {
6a488035
TO
64 self::$_now = date('YmdHis');
65 }
66
c8aa607b 67 /**
fe482240 68 * Store input array on the class.
77b97be7 69 *
c8aa607b 70 * @param array $parameters
77b97be7
EM
71 *
72 * @throws CRM_Core_Exception
c8aa607b 73 */
00be9182 74 public function setInputParameters($parameters) {
22e263ad 75 if (!is_array($parameters)) {
cc0c30cc 76 throw new CRM_Core_Exception('Invalid input parameters');
c8aa607b 77 }
78 $this->_inputParameters = $parameters;
79 }
353ffa53 80
8196c759 81 /**
1d86918a
EM
82 * Validate incoming data.
83 *
84 * This function is intended to ensure that incoming data matches
8196c759 85 * It provides a form of pseudo-authentication - by checking the calling fn already knows
86 * the correct contact id & contribution id (this can be problematic when that has changed in
87 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
88 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
89 * and didn't update your IPN URL.
90 *
6a0b768e
TO
91 * @param array $input
92 * Interpreted values from the values returned through the IPN.
93 * @param array $ids
94 * More interpreted values (ids) from the values returned through the IPN.
95 * @param array $objects
96 * An empty array that will be populated with loaded object.
97 * @param bool $required
98 * Boolean Return FALSE if the relevant objects don't exist.
99 * @param int $paymentProcessorID
100 * Id of the payment processor ID in use.
1d86918a 101 *
5c766a0b 102 * @return bool
8196c759 103 */
00be9182 104 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
6a488035
TO
105
106 // make sure contact exists and is valid
5a9c68ac 107 $contact = new CRM_Contact_BAO_Contact();
6a488035
TO
108 $contact->id = $ids['contact'];
109 if (!$contact->find(TRUE)) {
92fcb95f 110 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
6a488035
TO
111 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
112 return FALSE;
113 }
114
115 // make sure contribution exists and is valid
5a9c68ac 116 $contribution = new CRM_Contribute_BAO_Contribution();
6a488035
TO
117 $contribution->id = $ids['contribution'];
118 if (!$contribution->find(TRUE)) {
92fcb95f 119 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
6a488035
TO
120 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
121 return FALSE;
122 }
123 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
d9924163 124 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
6a488035
TO
125
126 $objects['contact'] = &$contact;
127 $objects['contribution'] = &$contribution;
128 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
129 return FALSE;
130 }
a284891b
EM
131 //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
132 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
133 //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
134 if (isset($objects['contributionRecur'])) {
135 $objects['first_contribution'] = $objects['contribution'];
136 }
6a488035
TO
137 return TRUE;
138 }
139
8196c759 140 /**
fe482240 141 * Load objects related to contribution.
6a488035
TO
142 *
143 * @input array information from Payment processor
dd244018 144 *
3aaa68fb 145 * @param array $input
8196c759 146 * @param array $ids
147 * @param array $objects
6a0b768e
TO
148 * @param bool $required
149 * @param int $paymentProcessorID
8196c759 150 * @param array $error_handling
dd244018 151 *
3aaa68fb 152 * @return bool|array
6a488035 153 */
00be9182 154 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
6a488035
TO
155 if (empty($error_handling)) {
156 // default options are that we log an error & echo it out
157 // note that we should refactor this error handling into error code @ some point
158 // but for now setting up enough separation so we can do unit tests
159 $error_handling = array(
160 'log_error' => 1,
161 'echo_error' => 1,
162 );
163 }
164 $ids['paymentProcessor'] = $paymentProcessorID;
165 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
166 $contribution = &$objects['contribution'];
167 }
168 else {
169 //legacy support - functions are 'used' to be able to pass in a DAO
170 $contribution = new CRM_Contribute_BAO_Contribution();
171 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
172 $contribution->find(TRUE);
173 $objects['contribution'] = &$contribution;
174 }
175 try {
276e3ec6 176 $success = $contribution->loadRelatedObjects($input, $ids);
177 if ($required && empty($contribution->_relatedObjects['paymentProcessor'])) {
178 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id);
179 }
6a488035 180 }
353ffa53 181 catch (Exception $e) {
cc0c30cc 182 $success = FALSE;
a7488080 183 if (!empty($error_handling['log_error'])) {
6a488035
TO
184 CRM_Core_Error::debug_log_message($e->getMessage());
185 }
a7488080 186 if (!empty($error_handling['echo_error'])) {
6c552737 187 echo $e->getMessage();
6a488035 188 }
a7488080 189 if (!empty($error_handling['return_error'])) {
6a488035
TO
190 return array(
191 'is_error' => 1,
192 'error_message' => ($e->getMessage()),
193 );
194 }
195 }
196 $objects = array_merge($objects, $contribution->_relatedObjects);
197 return $success;
198 }
199
8196c759 200 /**
fe482240 201 * Set contribution to failed.
28de42d1 202 *
8196c759 203 * @param array $objects
204 * @param object $transaction
205 * @param array $input
28de42d1 206 *
5c766a0b 207 * @return bool
8196c759 208 */
00be9182 209 public function failed(&$objects, &$transaction, $input = array()) {
6a488035
TO
210 $contribution = &$objects['contribution'];
211 $memberships = array();
a7488080 212 if (!empty($objects['membership'])) {
6a488035
TO
213 $memberships = &$objects['membership'];
214 if (is_numeric($memberships)) {
215 $memberships = array($objects['membership']);
216 }
217 }
218
219 $addLineItems = FALSE;
220 if (empty($contribution->id)) {
221 $addLineItems = TRUE;
222 }
223 $participant = &$objects['participant'];
224
3aaa68fb 225 // CRM-15546
353ffa53
TO
226 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
227 'labelColumn' => 'name',
af9b09df 228 'flip' => 1,
353ffa53 229 ));
5a9c68ac
PJ
230 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
231 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
232 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
71d085fe 233 $contribution->contribution_status_id = $contributionStatuses['Failed'];
6a488035
TO
234 $contribution->save();
235
28de42d1 236 // Add line items for recurring payments.
a7488080 237 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 238 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
239 }
240
8381af80 241 //add new soft credit against current contribution id and
6357981e 242 //copy initial contribution custom fields for recurring contributions
a7488080 243 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
e577770c
EM
244 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
245 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
246 }
247
0bad10e7 248 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
6a488035 249 if (!empty($memberships)) {
5968aa47 250 // if transaction is failed then set "Cancelled" as membership status
353ffa53
TO
251 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
252 'labelColumn' => 'name',
af9b09df 253 'flip' => 1,
353ffa53 254 ));
6a488035
TO
255 foreach ($memberships as $membership) {
256 if ($membership) {
71d085fe 257 $membership->status_id = $membershipStatuses['Cancelled'];
6a488035 258 $membership->save();
d63f4fc3 259
6a488035 260 //update related Memberships.
71d085fe 261 $params = array('status_id' => $membershipStatuses['Cancelled']);
6a488035
TO
262 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
263 }
264 }
265 }
d63f4fc3 266
6a488035 267 if ($participant) {
353ffa53
TO
268 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
269 'labelColumn' => 'name',
af9b09df 270 'flip' => 1,
353ffa53 271 ));
71d085fe 272 $participant->status_id = $participantStatuses['Cancelled'];
6a488035
TO
273 $participant->save();
274 }
275 }
276
277 $transaction->commit();
278 CRM_Core_Error::debug_log_message("Setting contribution status to failed");
279 //echo "Success: Setting contribution status to failed<p>";
280 return TRUE;
281 }
282
8196c759 283 /**
fe482240 284 * Handled pending contribution status.
1d86918a 285 *
8196c759 286 * @param array $objects
287 * @param object $transaction
1d86918a 288 *
5c766a0b 289 * @return bool
8196c759 290 */
00be9182 291 public function pending(&$objects, &$transaction) {
6a488035
TO
292 $transaction->commit();
293 CRM_Core_Error::debug_log_message("returning since contribution status is pending");
294 echo "Success: Returning since contribution status is pending<p>";
295 return TRUE;
296 }
297
6c786a9b 298 /**
1d86918a
EM
299 * Process cancelled payment outcome.
300 *
3aaa68fb 301 * @param array $objects
302 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
303 * @param array $input
304 *
305 * @return bool
306 */
00be9182 307 public function cancelled(&$objects, &$transaction, $input = array()) {
6a488035
TO
308 $contribution = &$objects['contribution'];
309 $memberships = &$objects['membership'];
310 if (is_numeric($memberships)) {
311 $memberships = array($objects['membership']);
312 }
313
314 $participant = &$objects['participant'];
315 $addLineItems = FALSE;
316 if (empty($contribution->id)) {
317 $addLineItems = TRUE;
318 }
353ffa53
TO
319 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
320 'labelColumn' => 'name',
af9b09df 321 'flip' => 1,
353ffa53 322 ));
71d085fe 323 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
6a488035
TO
324 $contribution->cancel_date = self::$_now;
325 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
326 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
327 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
328 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
329 $contribution->save();
330
331 //add lineitems for recurring payments
a7488080 332 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 333 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
334 }
335
8381af80 336 //add new soft credit against current $contribution and
6357981e 337 //copy initial contribution custom fields for recurring contributions
a7488080 338 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
e577770c
EM
339 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
340 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
341 }
342
0bad10e7 343 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
6a488035 344 if (!empty($memberships)) {
353ffa53
TO
345 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
346 'labelColumn' => 'name',
af9b09df 347 'flip' => 1,
353ffa53 348 ));
6a488035
TO
349 foreach ($memberships as $membership) {
350 if ($membership) {
71d085fe 351 $membership->status_id = $membershipStatuses['Cancelled'];
6a488035 352 $membership->save();
d63f4fc3 353
6a488035 354 //update related Memberships.
71d085fe 355 $params = array('status_id' => $membershipStatuses['Cancelled']);
6a488035
TO
356 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
357 }
358 }
359 }
d63f4fc3 360
6a488035 361 if ($participant) {
353ffa53
TO
362 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
363 'labelColumn' => 'name',
af9b09df 364 'flip' => 1,
353ffa53 365 ));
71d085fe 366 $participant->status_id = $participantStatuses['Cancelled'];
6a488035
TO
367 $participant->save();
368 }
369 }
370 $transaction->commit();
371 CRM_Core_Error::debug_log_message("Setting contribution status to cancelled");
372 //echo "Success: Setting contribution status to cancelled<p>";
373 return TRUE;
374 }
375
6c786a9b 376 /**
1d86918a
EM
377 * Rollback unhandled outcomes.
378 *
3aaa68fb 379 * @param array $objects
380 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
381 *
382 * @return bool
383 */
00be9182 384 public function unhandled(&$objects, &$transaction) {
6a488035 385 $transaction->rollback();
2d8851f6
EM
386 CRM_Core_Error::debug_log_message("returning since contribution status: is not handled");
387 echo "Failure: contribution status is not handled<p>";
6a488035
TO
388 return FALSE;
389 }
390
6c786a9b 391 /**
3ccde016 392 * Jumbled up function.
1d86918a 393 *
3ccde016
EM
394 * The purpose of this function is to transition a pending transaction to Completed including updating any
395 * related entities.
396 *
397 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
398 * updating related entities.
399 *
400 * It is recommended to avoid calling this function directly and call the api functions:
401 * - contribution.completetransaction
402 * - contribution.repeattransaction
403 *
404 * These functions are the focus of testing efforts and more accurately reflect the division of roles
405 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
406 * and from there it should be possible to pass off transaction management.)
407 *
408 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
409 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
410 *
411 * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo
412 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
413 * a shared function that updates related components.
414 *
415 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
416 * IPN class is better accessed through the api which de-jumbles it a bit.
417 *
418 * e.g the payment class can have a function like (based on Omnipay extension):
419 *
420 * public function handlePaymentNotification() {
421 * $response = $this->getValidatedOutcome();
422 * if ($response->isSuccessful()) {
423 * try {
424 * // @todo check if it is a repeat transaction & call repeattransaction instead.
425 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
426 * }
427 * catch (CiviCRM_API3_Exception $e) {
428 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
429 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
430 * have occurred. Please check your receipt is correct');
431 * $this->redirectOrExit('success');
432 * }
433 * elseif ($this->transaction_id) {
434 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
435 * 'Failed'));
436 * }
437 *
438 * @param array $input
439 * @param array $ids
440 * @param array $objects
3aaa68fb 441 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
442 * @param bool $recur
443 */
00be9182 444 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
db59bb73
EM
445 $isRecurring = $this->_isRecurring;
446 $isFirstOrLastRecurringPayment = $this->_isFirstOrLastRecurringPayment;
6a488035 447 $contribution = &$objects['contribution'];
a284891b 448
db59bb73
EM
449 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, $recur, $contribution,
450 $isRecurring, $isFirstOrLastRecurringPayment);
6a488035
TO
451 }
452
6c786a9b 453 /**
1d86918a
EM
454 * Get site billing ID.
455 *
456 * @param array $ids
6c786a9b
EM
457 *
458 * @return bool
459 */
00be9182 460 public function getBillingID(&$ids) {
b576d770 461 $ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
6a488035
TO
462 if (!$ids['billing']) {
463 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
464 echo "Failure: Could not find billing location type<p>";
465 return FALSE;
466 }
467 return TRUE;
468 }
469
c490a46a 470 /**
1d86918a
EM
471 * Send receipt from contribution.
472 *
db59bb73
EM
473 * @deprecated
474 *
1d86918a 475 * Note that the compose message part has been moved to contribution
6a488035
TO
476 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
477 *
6a0b768e
TO
478 * @param array $input
479 * Incoming data from Payment processor.
480 * @param array $ids
481 * Related object IDs.
3aaa68fb 482 * @param array $objects
6a0b768e
TO
483 * @param array $values
484 * Values related to objects that have already been loaded.
485 * @param bool $recur
486 * Is it part of a recurring contribution.
487 * @param bool $returnMessageText
488 * Should text be returned instead of sent. This.
16b10e64 489 * is because the function is also used to generate pdfs
6c786a9b 490 *
c490a46a 491 * @return array
6c786a9b 492 */
00be9182 493 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
ec7e3954 494 return CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values, $recur,
3425da09 495 $returnMessageText);
6a488035
TO
496 }
497
b2b0530a 498}