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