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