8caa61c67d4b72b9256c2618003d277425418c58
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
36
37 /**
38 * Constructor function.
39 *
40 * @param array $inputData
41 * contents of HTTP REQUEST.
42 *
43 * @throws CRM_Core_Exception
44 */
45 public function __construct($inputData) {
46 $this->setInputParameters($inputData);
47 parent::__construct();
48 }
49
50 /**
51 * @param string $component
52 *
53 * @return bool|void
54 */
55 public function main($component = 'contribute') {
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
59 $x_subscription_id = $this->retrieve('x_subscription_id', 'String');
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 }
90 return TRUE;
91 }
92
93 /**
94 * @param array $input
95 * @param array $ids
96 * @param array $objects
97 * @param $first
98 *
99 * @return bool
100 */
101 public function recur(&$input, &$ids, &$objects, $first) {
102 $this->_isRecurring = TRUE;
103 $recur = &$objects['contributionRecur'];
104 $paymentProcessorObject = $objects['contribution']->_relatedObjects['paymentProcessor']['object'];
105
106 // do a subscription check
107 if ($recur->processor_id != $input['subscription_id']) {
108 CRM_Core_Error::debug_log_message("Unrecognized subscription.");
109 echo "Failure: Unrecognized subscription<p>";
110 return FALSE;
111 }
112
113 // At this point $object has first contribution loaded.
114 // Lets do a check to make sure this payment has the amount same as that of first contribution.
115 if ($objects['contribution']->total_amount != $input['amount']) {
116 CRM_Core_Error::debug_log_message("Subscription amount mismatch.");
117 echo "Failure: Subscription amount mismatch<p>";
118 return FALSE;
119 }
120
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'];
140 $contribution->financial_type_id = $objects['contributionType']->id;
141 $contribution->contribution_page_id = $ids['contributionPage'];
142 $contribution->contribution_recur_id = $ids['contributionRecur'];
143 $contribution->receive_date = $now;
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;
148 $contribution->campaign_id = $objects['contribution']->campaign_id;
149
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
156 $this->checkMD5($paymentProcessorObject, $input);
157
158 if ($input['response_code'] == 1) {
159 // Approved
160 if ($first) {
161 $recur->start_date = $now;
162 $recur->trxn_id = $recur->processor_id;
163 $this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
164 }
165 $statusName = 'In Progress';
166 if (($recur->installments > 0) &&
167 ($input['subscription_paynum'] >= $recur->installments)
168 ) {
169 // this is the last payment
170 $statusName = 'Completed';
171 $recur->end_date = $now;
172 $this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
173 }
174 $recur->modified_date = $now;
175 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
176 $recur->save();
177 }
178 else {
179 // Declined
180 // failed status
181 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
182 $recur->cancel_date = $now;
183 $recur->save();
184
185 $message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text'])));
186 CRM_Core_Error::debug_log_message($message);
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
190 // the existing contributions
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);
204 }
205
206 /**
207 * @param $input
208 * @param $ids
209 *
210 * @return bool
211 */
212 public function getInput(&$input, &$ids) {
213 $input['amount'] = $this->retrieve('x_amount', 'String');
214 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
215 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
216 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
217 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
218 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
219 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
220 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
221
222 if ($input['trxn_id']) {
223 $input['is_test'] = 0;
224 }
225 else {
226 $input['is_test'] = 1;
227 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
228 }
229
230 if (!$this->getBillingID($ids)) {
231 return FALSE;
232 }
233 $billingID = $ids['billing'];
234 $params = array(
235 'first_name' => 'x_first_name',
236 'last_name' => 'x_last_name',
237 "street_address-{$billingID}" => 'x_address',
238 "city-{$billingID}" => 'x_city',
239 "state-{$billingID}" => 'x_state',
240 "postal_code-{$billingID}" => 'x_zip',
241 "country-{$billingID}" => 'x_country',
242 "email-{$billingID}" => 'x_email',
243 );
244 foreach ($params as $civiName => $resName) {
245 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
246 }
247 }
248
249 /**
250 * @param $ids
251 * @param $input
252 */
253 public function getIDs(&$ids, &$input) {
254 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
255 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
256
257 // joining with contribution table for extra checks
258 $sql = "
259 SELECT cr.id, cr.contact_id
260 FROM civicrm_contribution_recur cr
261 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
262 WHERE cr.processor_id = '{$input['subscription_id']}' AND
263 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
264 LIMIT 1";
265 $contRecur = CRM_Core_DAO::executeQuery($sql);
266 $contRecur->fetch();
267 $ids['contributionRecur'] = $contRecur->id;
268 if ($ids['contact'] != $contRecur->contact_id) {
269 $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));
270 CRM_Core_Error::debug_log_message($message);
271 $ids['contact'] = $contRecur->contact_id;
272 }
273 if (!$ids['contributionRecur']) {
274 $message = ts("Could not find contributionRecur id: %1", array(1 => htmlspecialchars(print_r($input, TRUE))));
275 CRM_Core_Error::debug_log_message($message);
276 echo "Failure: $message<p>";
277 exit();
278 }
279
280 // get page id based on contribution id
281 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
282 $ids['contribution'],
283 'contribution_page_id'
284 );
285
286 if ($input['component'] == 'event') {
287 // FIXME: figure out fields for event
288 }
289 else {
290 // get the optional ids
291
292 // Get membershipId. Join with membership payment table for additional checks
293 $sql = "
294 SELECT m.id
295 FROM civicrm_membership m
296 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
297 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
298 LIMIT 1";
299 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
300 $ids['membership'] = $membershipId;
301 }
302
303 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
304 }
305 }
306
307 /**
308 * @param string $name
309 * Parameter name.
310 * @param string $type
311 * Parameter type.
312 * @param bool $abort
313 * Abort if not present.
314 * @param null $default
315 * Default value.
316 *
317 * @throws CRM_Core_Exception
318 * @return mixed
319 */
320 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
321 $value = CRM_Utils_Type::validate(
322 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
323 $type,
324 FALSE
325 );
326 if ($abort && $value === NULL) {
327 throw new CRM_Core_Exception("Could not find an entry for $name");
328 }
329 return $value;
330 }
331
332 /**
333 * Check and validate gateway MD5 response if present.
334 *
335 * @param CRM_Core_Payment_AuthorizeNet $paymentObject
336 * @param array $input
337 *
338 * @return bool
339 */
340 public function checkMD5($paymentObject, $input) {
341 if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
342 CRM_Core_Error::debug_log_message("MD5 Verification failed.");
343 echo "Failure: Security verification failed<p>";
344 exit();
345 }
346 return TRUE;
347 }
348
349 }