INFRA-132 - @param type fixes
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
0dbefed3 36
b5c2afd0 37 /**
100fef9d 38 * Constructor function
0dbefed3 39 *
5a4f6742
CW
40 * @param array $inputData
41 * contents of HTTP REQUEST.
0dbefed3
EM
42 *
43 * @throws CRM_Core_Exception
b5c2afd0 44 */
00be9182 45 public function __construct($inputData) {
0dbefed3 46 $this->setInputParameters($inputData);
6a488035
TO
47 parent::__construct();
48 }
49
6c786a9b
EM
50 /**
51 * @param string $component
52 *
53 * @return bool|void
54 */
00be9182 55 public function main($component = 'contribute') {
6a488035
TO
56
57 //we only get invoice num as a key player from payment gateway response.
58 //for ARB we get x_subscription_id and x_subscription_paynum
0dbefed3 59 $x_subscription_id = $this->retrieve('x_subscription_id', 'String');
6a488035
TO
60
61 if ($x_subscription_id) {
62 //Approved
63
64 $ids = $objects = array();
65 $input['component'] = $component;
66
67 // load post vars in $input
68 $this->getInput($input, $ids);
69
70 // load post ids in $ids
71 $this->getIDs($ids, $input);
72
73 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
74 'AuthNet', 'id', 'name'
75 );
76
77 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
78 return FALSE;
79 }
80
81 if ($component == 'contribute' && $ids['contributionRecur']) {
82 // check if first contribution is completed, else complete first contribution
83 $first = TRUE;
84 if ($objects['contribution']->contribution_status_id == 1) {
85 $first = FALSE;
86 }
87 return $this->recur($input, $ids, $objects, $first);
88 }
89 }
0dbefed3 90 return TRUE;
6a488035
TO
91 }
92
6c786a9b 93 /**
7a6073fd
EM
94 * @param array $input
95 * @param array $ids
0dbefed3 96 * @param array $objects
6c786a9b 97 * @param $first
7a6073fd
EM
98 *
99 * @return bool
6c786a9b 100 */
00be9182 101 public function recur(&$input, &$ids, &$objects, $first) {
937cf542 102 $this->_isRecurring = TRUE;
6a488035
TO
103 $recur = &$objects['contributionRecur'];
104
105 // do a subscription check
106 if ($recur->processor_id != $input['subscription_id']) {
107 CRM_Core_Error::debug_log_message("Unrecognized subscription.");
108 echo "Failure: Unrecognized subscription<p>";
109 return FALSE;
110 }
111
112 // At this point $object has first contribution loaded.
113 // Lets do a check to make sure this payment has the amount same as that of first contribution.
114 if ($objects['contribution']->total_amount != $input['amount']) {
115 CRM_Core_Error::debug_log_message("Subscription amount mismatch.");
116 echo "Failure: Subscription amount mismatch<p>";
117 return FALSE;
118 }
119
120 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
121
122 $transaction = new CRM_Core_Transaction();
123
124 $now = date('YmdHis');
125
126 // fix dates that already exist
127 $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
128 foreach ($dates as $name) {
129 if ($recur->$name) {
130 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
131 }
132 }
133
134 //load new contribution object if required.
135 if (!$first) {
136 // create a contribution and then get it processed
137 $contribution = new CRM_Contribute_BAO_Contribution();
138 $contribution->contact_id = $ids['contact'];
94d1bc8d 139 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
140 $contribution->contribution_page_id = $ids['contributionPage'];
141 $contribution->contribution_recur_id = $ids['contributionRecur'];
142 $contribution->receive_date = $now;
143 $contribution->currency = $objects['contribution']->currency;
144 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
145 $contribution->amount_level = $objects['contribution']->amount_level;
146 $contribution->address_id = $objects['contribution']->address_id;
94d1bc8d
PJ
147 $contribution->campaign_id = $objects['contribution']->campaign_id;
148
6a488035
TO
149 $objects['contribution'] = &$contribution;
150 }
151 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
152 $objects['contribution']->total_amount = $input['amount'];
153 $objects['contribution']->trxn_id = $input['trxn_id'];
154
155 // since we have processor loaded for sure at this point,
156 // check and validate gateway MD5 response if present
157 $this->checkMD5($ids, $input);
158
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;
937cf542 164 $this->_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;
937cf542 173 $this->_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
186 CRM_Core_Error::debug_log_message("Subscription payment failed - '{$input['response_reason_text']}'");
187
188 // the recurring contribution has declined a payment or has failed
189 // so we just fix the recurring contribution and not change any of
7a6073fd 190 // the existing contributions
6a488035
TO
191 // CRM-9036
192 return TRUE;
193 }
194
195 // check if contribution is already completed, if so we ignore this ipn
196 if ($objects['contribution']->contribution_status_id == 1) {
197 $transaction->commit();
198 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
199 echo "Success: Contribution has already been handled<p>";
200 return TRUE;
201 }
202
203 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
6a488035
TO
204 }
205
6c786a9b
EM
206 /**
207 * @param $input
208 * @param $ids
209 */
00be9182 210 public function getInput(&$input, &$ids) {
0dbefed3
EM
211 $input['amount'] = $this->retrieve('x_amount', 'String');
212 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
213 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
214 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
215 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
216 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
217 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
218 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
219
6a488035
TO
220 if ($input['trxn_id']) {
221 $input['is_test'] = 0;
222 }
223 else {
224 $input['is_test'] = 1;
225 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
226 }
227
228 if (!$this->getBillingID($ids)) {
229 return FALSE;
230 }
231 $billingID = $ids['billing'];
232 $params = array(
233 'first_name' => 'x_first_name',
234 'last_name' => 'x_last_name',
235 "street_address-{$billingID}" => 'x_address',
236 "city-{$billingID}" => 'x_city',
237 "state-{$billingID}" => 'x_state',
238 "postal_code-{$billingID}" => 'x_zip',
239 "country-{$billingID}" => 'x_country',
240 "email-{$billingID}" => 'x_email',
241 );
242 foreach ($params as $civiName => $resName) {
0dbefed3 243 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
6a488035
TO
244 }
245 }
246
6c786a9b
EM
247 /**
248 * @param $ids
249 * @param $input
250 */
00be9182 251 public function getIDs(&$ids, &$input) {
0dbefed3
EM
252 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
253 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
6a488035
TO
254
255 // joining with contribution table for extra checks
256 $sql = "
257 SELECT cr.id, cr.contact_id
258 FROM civicrm_contribution_recur cr
259INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
260 WHERE cr.processor_id = '{$input['subscription_id']}' AND
261 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
262 LIMIT 1";
263 $contRecur = CRM_Core_DAO::executeQuery($sql);
264 $contRecur->fetch();
265 $ids['contributionRecur'] = $contRecur->id;
9b873358 266 if ($ids['contact'] != $contRecur->contact_id) {
8753de39 267 CRM_Core_Error::debug_log_message("Recurring contribution appears to have been re-assigned from id {$ids['contact']} to {$contRecur->contact_id}
6a488035
TO
268 Continuing with {$contRecur->contact_id}
269 ");
8753de39 270 $ids['contact'] = $contRecur->contact_id;
6a488035
TO
271 }
272 if (!$ids['contributionRecur']) {
92fcb95f 273 CRM_Core_Error::debug_log_message("Could not find contributionRecur id: " . print_r($input, TRUE));
6a488035
TO
274 echo "Failure: Could not find contributionRecur<p>";
275 exit();
276 }
277
278 // get page id based on contribution id
279 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
280 $ids['contribution'],
281 'contribution_page_id'
282 );
283
284 if ($input['component'] == 'event') {
285 // FIXME: figure out fields for event
286 }
287 else {
288 // get the optional ids
289
290 // Get membershipId. Join with membership payment table for additional checks
291 $sql = "
292 SELECT m.id
293 FROM civicrm_membership m
294INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
295 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
296 LIMIT 1";
297 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
298 $ids['membership'] = $membershipId;
299 }
300
301 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
302 }
303 }
304
6c786a9b 305 /**
6a0b768e
TO
306 * @param string $name
307 * Parameter name.
308 * @param string $type
309 * Parameter type.
310 * @param bool $abort
311 * Abort if not present.
312 * @param null $default
313 * Default value.
6c786a9b 314 *
0dbefed3 315 * @throws CRM_Core_Exception
6c786a9b
EM
316 * @return mixed
317 */
00be9182 318 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
0dbefed3
EM
319 $value = CRM_Utils_Type::validate(
320 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
321 $type,
322 FALSE
6a488035
TO
323 );
324 if ($abort && $value === NULL) {
0dbefed3 325 throw new CRM_Core_Exception("Could not find an entry for $name");
6a488035
TO
326 }
327 return $value;
2aa397bc 328 }
6a488035 329
6c786a9b
EM
330 /**
331 * @param $ids
332 * @param $input
333 *
334 * @return bool
335 */
00be9182 336 public function checkMD5($ids, $input) {
6a488035
TO
337 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ids['paymentProcessor'],
338 $input['is_test'] ? 'test' : 'live'
339 );
340 $paymentObject = CRM_Core_Payment::singleton($input['is_test'] ? 'test' : 'live', $paymentProcessor);
341
342 if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
343 CRM_Core_Error::debug_log_message("MD5 Verification failed.");
344 echo "Failure: Security verification failed<p>";
345 exit();
346 }
347 return TRUE;
348 }
349}