CRM-19597 allow receive_date to be passed in for A.net
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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
121 // At this point $object has first contribution loaded.
122 // Lets do a check to make sure this payment has the amount same as that of first contribution.
123 if ($objects['contribution']->total_amount != $input['amount']) {
124 CRM_Core_Error::debug_log_message("Subscription amount mismatch.");
125 echo "Failure: Subscription amount mismatch<p>";
126 return FALSE;
127 }
128
129 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
130
131 $transaction = new CRM_Core_Transaction();
132
133 $now = date('YmdHis');
134
135 // fix dates that already exist
136 $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
137 foreach ($dates as $name) {
138 if ($recur->$name) {
139 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
140 }
141 }
142
143 //load new contribution object if required.
144 if (!$first) {
145 // create a contribution and then get it processed
146 $contribution = new CRM_Contribute_BAO_Contribution();
147 $contribution->contact_id = $ids['contact'];
353ffa53 148 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
149 $contribution->contribution_page_id = $ids['contributionPage'];
150 $contribution->contribution_recur_id = $ids['contributionRecur'];
4a1ba425 151 $contribution->receive_date = $input['receive_date'];
6a488035
TO
152 $contribution->currency = $objects['contribution']->currency;
153 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
154 $contribution->amount_level = $objects['contribution']->amount_level;
155 $contribution->address_id = $objects['contribution']->address_id;
94d1bc8d
PJ
156 $contribution->campaign_id = $objects['contribution']->campaign_id;
157
6a488035
TO
158 $objects['contribution'] = &$contribution;
159 }
160 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
161 $objects['contribution']->total_amount = $input['amount'];
162 $objects['contribution']->trxn_id = $input['trxn_id'];
163
d6944518 164 $this->checkMD5($paymentProcessorObject, $input);
6a488035 165
6a488035
TO
166 if ($input['response_code'] == 1) {
167 // Approved
168 if ($first) {
169 $recur->start_date = $now;
170 $recur->trxn_id = $recur->processor_id;
937cf542 171 $this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
6a488035
TO
172 }
173 $statusName = 'In Progress';
174 if (($recur->installments > 0) &&
175 ($input['subscription_paynum'] >= $recur->installments)
176 ) {
177 // this is the last payment
178 $statusName = 'Completed';
179 $recur->end_date = $now;
937cf542 180 $this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
6a488035
TO
181 }
182 $recur->modified_date = $now;
183 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
184 $recur->save();
185 }
186 else {
187 // Declined
188 // failed status
189 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
190 $recur->cancel_date = $now;
191 $recur->save();
192
267353f4
CB
193 $message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text'])));
194 CRM_Core_Error::debug_log_message($message);
6a488035
TO
195
196 // the recurring contribution has declined a payment or has failed
197 // so we just fix the recurring contribution and not change any of
7a6073fd 198 // the existing contributions
6a488035
TO
199 // CRM-9036
200 return TRUE;
201 }
202
203 // check if contribution is already completed, if so we ignore this ipn
204 if ($objects['contribution']->contribution_status_id == 1) {
205 $transaction->commit();
267353f4 206 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
6a488035
TO
207 echo "Success: Contribution has already been handled<p>";
208 return TRUE;
209 }
210
211 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
6a488035
TO
212 }
213
6c786a9b 214 /**
dbb0d30b 215 * Get the input from passed in fields.
216 *
217 * @param array $input
218 * @param array $ids
7a9ab499
EM
219 *
220 * @return bool
6c786a9b 221 */
00be9182 222 public function getInput(&$input, &$ids) {
0dbefed3
EM
223 $input['amount'] = $this->retrieve('x_amount', 'String');
224 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
225 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
226 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
227 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
228 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
229 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
230 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
4a1ba425 231 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
232 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, 'now');
0dbefed3 233
6a488035
TO
234 if ($input['trxn_id']) {
235 $input['is_test'] = 0;
236 }
5c6c7e76 237 // Only assume trxn_id 'should' have been returned for success.
238 // Per CRM-17611 it would also not be passed back for a decline.
239 elseif ($input['response_code'] == 1) {
6a488035
TO
240 $input['is_test'] = 1;
241 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
242 }
243
244 if (!$this->getBillingID($ids)) {
245 return FALSE;
246 }
247 $billingID = $ids['billing'];
248 $params = array(
249 'first_name' => 'x_first_name',
250 'last_name' => 'x_last_name',
251 "street_address-{$billingID}" => 'x_address',
252 "city-{$billingID}" => 'x_city',
253 "state-{$billingID}" => 'x_state',
254 "postal_code-{$billingID}" => 'x_zip',
255 "country-{$billingID}" => 'x_country',
256 "email-{$billingID}" => 'x_email',
257 );
258 foreach ($params as $civiName => $resName) {
0dbefed3 259 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
6a488035
TO
260 }
261 }
262
6c786a9b 263 /**
dbb0d30b 264 * Get ids from input.
265 *
266 * @param array $ids
267 * @param array $input
268 *
269 * @throws \CRM_Core_Exception
6c786a9b 270 */
00be9182 271 public function getIDs(&$ids, &$input) {
0dbefed3
EM
272 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
273 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
6a488035
TO
274
275 // joining with contribution table for extra checks
276 $sql = "
277 SELECT cr.id, cr.contact_id
278 FROM civicrm_contribution_recur cr
279INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
280 WHERE cr.processor_id = '{$input['subscription_id']}' AND
281 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
282 LIMIT 1";
283 $contRecur = CRM_Core_DAO::executeQuery($sql);
284 $contRecur->fetch();
285 $ids['contributionRecur'] = $contRecur->id;
9b873358 286 if ($ids['contact'] != $contRecur->contact_id) {
267353f4
CB
287 $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));
288 CRM_Core_Error::debug_log_message($message);
8753de39 289 $ids['contact'] = $contRecur->contact_id;
6a488035
TO
290 }
291 if (!$ids['contributionRecur']) {
4346da4b 292 $message = ts("Could not find contributionRecur id");
293 $log = new CRM_Utils_SystemLogger();
294 $log->error('payment_notification', array('message' => $message, 'ids' => $ids, 'input' => $input));
295 throw new CRM_Core_Exception($message);
6a488035
TO
296 }
297
298 // get page id based on contribution id
299 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
300 $ids['contribution'],
301 'contribution_page_id'
302 );
303
304 if ($input['component'] == 'event') {
305 // FIXME: figure out fields for event
306 }
307 else {
6a488035
TO
308 // Get membershipId. Join with membership payment table for additional checks
309 $sql = "
310 SELECT m.id
311 FROM civicrm_membership m
312INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
313 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
314 LIMIT 1";
315 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
316 $ids['membership'] = $membershipId;
317 }
318
319 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
320 }
321 }
322
6c786a9b 323 /**
6a0b768e
TO
324 * @param string $name
325 * Parameter name.
326 * @param string $type
327 * Parameter type.
328 * @param bool $abort
329 * Abort if not present.
330 * @param null $default
331 * Default value.
6c786a9b 332 *
0dbefed3 333 * @throws CRM_Core_Exception
6c786a9b
EM
334 * @return mixed
335 */
00be9182 336 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
0dbefed3
EM
337 $value = CRM_Utils_Type::validate(
338 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
339 $type,
340 FALSE
6a488035
TO
341 );
342 if ($abort && $value === NULL) {
0dbefed3 343 throw new CRM_Core_Exception("Could not find an entry for $name");
6a488035
TO
344 }
345 return $value;
2aa397bc 346 }
6a488035 347
6c786a9b 348 /**
d6944518
EM
349 * Check and validate gateway MD5 response if present.
350 *
351 * @param CRM_Core_Payment_AuthorizeNet $paymentObject
352 * @param array $input
6c786a9b 353 *
4346da4b 354 * @throws CRM_Core_Exception
6c786a9b 355 */
d6944518 356 public function checkMD5($paymentObject, $input) {
5c6c7e76 357 if (empty($input['trxn_id'])) {
358 // For decline we have nothing to check against.
359 return;
360 }
6a488035 361 if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
4346da4b 362 $message = "Failure: Security verification failed";
363 $log = new CRM_Utils_SystemLogger();
11a1ad01 364 $log->error('payment_notification', array('message' => $message, 'input' => $input));
4346da4b 365 throw new CRM_Core_Exception($message);
6a488035 366 }
6a488035 367 }
96025800 368
6a488035 369}