Merge pull request #11760 from mattwire/CRM-21391_grant_task
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
0dbefed3 34
b5c2afd0 35 /**
fe482240 36 * Constructor function.
0dbefed3 37 *
5a4f6742
CW
38 * @param array $inputData
39 * contents of HTTP REQUEST.
0dbefed3
EM
40 *
41 * @throws CRM_Core_Exception
b5c2afd0 42 */
00be9182 43 public function __construct($inputData) {
0dbefed3 44 $this->setInputParameters($inputData);
6a488035
TO
45 parent::__construct();
46 }
47
6c786a9b
EM
48 /**
49 * @param string $component
50 *
51 * @return bool|void
52 */
00be9182 53 public function main($component = 'contribute') {
6a488035
TO
54
55 //we only get invoice num as a key player from payment gateway response.
56 //for ARB we get x_subscription_id and x_subscription_paynum
0dbefed3 57 $x_subscription_id = $this->retrieve('x_subscription_id', 'String');
b6b59c64 58 $ids = $objects = $input = array();
6a488035
TO
59
60 if ($x_subscription_id) {
dbb0d30b 61 // Presence of the id means it is approved.
6a488035
TO
62 $input['component'] = $component;
63
64 // load post vars in $input
65 $this->getInput($input, $ids);
66
67 // load post ids in $ids
68 $this->getIDs($ids, $input);
69
11c03c08 70 // This is an unreliable method as there could be more than one instance.
71 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
72 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
73 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
74 // & call completetransaction or call fail? (which may not exist yet).
75 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
6a488035
TO
76 'AuthNet', 'id', 'name'
77 );
11c03c08 78 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', array(
79 'is_test' => 0,
80 'options' => array('limit' => 1),
81 'payment_processor_type_id' => $paymentProcessorTypeID,
82 'return' => 'id',
83 ));
6a488035
TO
84
85 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
86 return FALSE;
87 }
88
89 if ($component == 'contribute' && $ids['contributionRecur']) {
90 // check if first contribution is completed, else complete first contribution
91 $first = TRUE;
92 if ($objects['contribution']->contribution_status_id == 1) {
93 $first = FALSE;
94 }
95 return $this->recur($input, $ids, $objects, $first);
96 }
97 }
0dbefed3 98 return TRUE;
6a488035
TO
99 }
100
6c786a9b 101 /**
7a6073fd
EM
102 * @param array $input
103 * @param array $ids
0dbefed3 104 * @param array $objects
6c786a9b 105 * @param $first
7a6073fd
EM
106 *
107 * @return bool
6c786a9b 108 */
00be9182 109 public function recur(&$input, &$ids, &$objects, $first) {
937cf542 110 $this->_isRecurring = TRUE;
6a488035 111 $recur = &$objects['contributionRecur'];
d6944518 112 $paymentProcessorObject = $objects['contribution']->_relatedObjects['paymentProcessor']['object'];
6a488035
TO
113
114 // do a subscription check
115 if ($recur->processor_id != $input['subscription_id']) {
116 CRM_Core_Error::debug_log_message("Unrecognized subscription.");
117 echo "Failure: Unrecognized subscription<p>";
118 return FALSE;
119 }
120
6a488035
TO
121 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
122
123 $transaction = new CRM_Core_Transaction();
124
125 $now = date('YmdHis');
126
127 // fix dates that already exist
128 $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
129 foreach ($dates as $name) {
130 if ($recur->$name) {
131 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
132 }
133 }
134
135 //load new contribution object if required.
136 if (!$first) {
137 // create a contribution and then get it processed
138 $contribution = new CRM_Contribute_BAO_Contribution();
139 $contribution->contact_id = $ids['contact'];
353ffa53 140 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
141 $contribution->contribution_page_id = $ids['contributionPage'];
142 $contribution->contribution_recur_id = $ids['contributionRecur'];
4a1ba425 143 $contribution->receive_date = $input['receive_date'];
6a488035
TO
144 $contribution->currency = $objects['contribution']->currency;
145 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
146 $contribution->amount_level = $objects['contribution']->amount_level;
147 $contribution->address_id = $objects['contribution']->address_id;
94d1bc8d
PJ
148 $contribution->campaign_id = $objects['contribution']->campaign_id;
149
6a488035
TO
150 $objects['contribution'] = &$contribution;
151 }
152 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
153 $objects['contribution']->total_amount = $input['amount'];
154 $objects['contribution']->trxn_id = $input['trxn_id'];
155
d6944518 156 $this->checkMD5($paymentProcessorObject, $input);
6a488035 157
4086637a 158 $isFirstOrLastRecurringPayment = FALSE;
6a488035
TO
159 if ($input['response_code'] == 1) {
160 // Approved
161 if ($first) {
162 $recur->start_date = $now;
163 $recur->trxn_id = $recur->processor_id;
4086637a 164 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
6a488035
TO
165 }
166 $statusName = 'In Progress';
167 if (($recur->installments > 0) &&
168 ($input['subscription_paynum'] >= $recur->installments)
169 ) {
170 // this is the last payment
171 $statusName = 'Completed';
172 $recur->end_date = $now;
4086637a 173 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
6a488035
TO
174 }
175 $recur->modified_date = $now;
176 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
177 $recur->save();
178 }
179 else {
180 // Declined
181 // failed status
182 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
183 $recur->cancel_date = $now;
184 $recur->save();
185
267353f4
CB
186 $message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text'])));
187 CRM_Core_Error::debug_log_message($message);
6a488035
TO
188
189 // the recurring contribution has declined a payment or has failed
190 // so we just fix the recurring contribution and not change any of
7a6073fd 191 // the existing contributions
6a488035
TO
192 // CRM-9036
193 return TRUE;
194 }
195
196 // check if contribution is already completed, if so we ignore this ipn
197 if ($objects['contribution']->contribution_status_id == 1) {
198 $transaction->commit();
267353f4 199 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
6a488035
TO
200 echo "Success: Contribution has already been handled<p>";
201 return TRUE;
202 }
203
204 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
4086637a 205
206 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
207 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
208 // from isSentReceipt to an array of which receipts to send.
209 // Note that there is site-by-site opinions on which notifications are good to send.
210 if ($isFirstOrLastRecurringPayment) {
211 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
212 $isFirstOrLastRecurringPayment);
213 }
214
6a488035
TO
215 }
216
6c786a9b 217 /**
dbb0d30b 218 * Get the input from passed in fields.
219 *
220 * @param array $input
221 * @param array $ids
7a9ab499
EM
222 *
223 * @return bool
6c786a9b 224 */
00be9182 225 public function getInput(&$input, &$ids) {
0dbefed3
EM
226 $input['amount'] = $this->retrieve('x_amount', 'String');
227 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
228 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
229 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
230 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
231 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
232 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
233 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
4a1ba425 234 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
235 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, 'now');
0dbefed3 236
6a488035
TO
237 if ($input['trxn_id']) {
238 $input['is_test'] = 0;
239 }
5c6c7e76 240 // Only assume trxn_id 'should' have been returned for success.
241 // Per CRM-17611 it would also not be passed back for a decline.
242 elseif ($input['response_code'] == 1) {
6a488035
TO
243 $input['is_test'] = 1;
244 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
245 }
246
247 if (!$this->getBillingID($ids)) {
248 return FALSE;
249 }
250 $billingID = $ids['billing'];
251 $params = array(
252 'first_name' => 'x_first_name',
253 'last_name' => 'x_last_name',
254 "street_address-{$billingID}" => 'x_address',
255 "city-{$billingID}" => 'x_city',
256 "state-{$billingID}" => 'x_state',
257 "postal_code-{$billingID}" => 'x_zip',
258 "country-{$billingID}" => 'x_country',
259 "email-{$billingID}" => 'x_email',
260 );
261 foreach ($params as $civiName => $resName) {
0dbefed3 262 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
6a488035
TO
263 }
264 }
265
6c786a9b 266 /**
dbb0d30b 267 * Get ids from input.
268 *
269 * @param array $ids
270 * @param array $input
271 *
272 * @throws \CRM_Core_Exception
6c786a9b 273 */
00be9182 274 public function getIDs(&$ids, &$input) {
0dbefed3
EM
275 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
276 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
6a488035
TO
277
278 // joining with contribution table for extra checks
279 $sql = "
280 SELECT cr.id, cr.contact_id
281 FROM civicrm_contribution_recur cr
282INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
283 WHERE cr.processor_id = '{$input['subscription_id']}' AND
284 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
285 LIMIT 1";
286 $contRecur = CRM_Core_DAO::executeQuery($sql);
287 $contRecur->fetch();
288 $ids['contributionRecur'] = $contRecur->id;
9b873358 289 if ($ids['contact'] != $contRecur->contact_id) {
267353f4
CB
290 $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", array(1 => $ids['contact'], 2 => $contRecur->contact_id));
291 CRM_Core_Error::debug_log_message($message);
8753de39 292 $ids['contact'] = $contRecur->contact_id;
6a488035
TO
293 }
294 if (!$ids['contributionRecur']) {
4346da4b 295 $message = ts("Could not find contributionRecur id");
296 $log = new CRM_Utils_SystemLogger();
297 $log->error('payment_notification', array('message' => $message, 'ids' => $ids, 'input' => $input));
298 throw new CRM_Core_Exception($message);
6a488035
TO
299 }
300
301 // get page id based on contribution id
302 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
303 $ids['contribution'],
304 'contribution_page_id'
305 );
306
307 if ($input['component'] == 'event') {
308 // FIXME: figure out fields for event
309 }
310 else {
6a488035
TO
311 // Get membershipId. Join with membership payment table for additional checks
312 $sql = "
313 SELECT m.id
314 FROM civicrm_membership m
315INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
316 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
317 LIMIT 1";
318 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
319 $ids['membership'] = $membershipId;
320 }
321
322 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
323 }
324 }
325
6c786a9b 326 /**
6a0b768e
TO
327 * @param string $name
328 * Parameter name.
329 * @param string $type
330 * Parameter type.
331 * @param bool $abort
332 * Abort if not present.
333 * @param null $default
334 * Default value.
6c786a9b 335 *
0dbefed3 336 * @throws CRM_Core_Exception
6c786a9b
EM
337 * @return mixed
338 */
00be9182 339 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
0dbefed3
EM
340 $value = CRM_Utils_Type::validate(
341 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
342 $type,
343 FALSE
6a488035
TO
344 );
345 if ($abort && $value === NULL) {
0dbefed3 346 throw new CRM_Core_Exception("Could not find an entry for $name");
6a488035
TO
347 }
348 return $value;
2aa397bc 349 }
6a488035 350
6c786a9b 351 /**
d6944518
EM
352 * Check and validate gateway MD5 response if present.
353 *
354 * @param CRM_Core_Payment_AuthorizeNet $paymentObject
355 * @param array $input
6c786a9b 356 *
4346da4b 357 * @throws CRM_Core_Exception
6c786a9b 358 */
d6944518 359 public function checkMD5($paymentObject, $input) {
5c6c7e76 360 if (empty($input['trxn_id'])) {
361 // For decline we have nothing to check against.
362 return;
363 }
6a488035 364 if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
4346da4b 365 $message = "Failure: Security verification failed";
366 $log = new CRM_Utils_SystemLogger();
11a1ad01 367 $log->error('payment_notification', array('message' => $message, 'input' => $input));
4346da4b 368 throw new CRM_Core_Exception($message);
6a488035 369 }
6a488035 370 }
96025800 371
6a488035 372}