Merge pull request #11862 from mukeshcompucorp/fix-template-structure-issues
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33 class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
34
35 /**
36 * Constructor function.
37 *
38 * @param array $inputData
39 * contents of HTTP REQUEST.
40 *
41 * @throws CRM_Core_Exception
42 */
43 public function __construct($inputData) {
44 $this->setInputParameters($inputData);
45 parent::__construct();
46 }
47
48 /**
49 * @param string $component
50 *
51 * @return bool|void
52 */
53 public function main($component = 'contribute') {
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
57 $x_subscription_id = $this->retrieve('x_subscription_id', 'String');
58 $ids = $objects = $input = array();
59
60 if ($x_subscription_id) {
61 // Presence of the id means it is approved.
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
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',
76 'AuthNet', 'id', 'name'
77 );
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 ));
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 }
98 return TRUE;
99 }
100
101 /**
102 * @param array $input
103 * @param array $ids
104 * @param array $objects
105 * @param $first
106 *
107 * @return bool
108 */
109 public function recur(&$input, &$ids, &$objects, $first) {
110 $this->_isRecurring = TRUE;
111 $recur = &$objects['contributionRecur'];
112 $paymentProcessorObject = $objects['contribution']->_relatedObjects['paymentProcessor']['object'];
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 $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 = $input['receive_date'];
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 $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
150
151 $objects['contribution'] = &$contribution;
152 }
153 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
154 $objects['contribution']->total_amount = $input['amount'];
155 $objects['contribution']->trxn_id = $input['trxn_id'];
156
157 $this->checkMD5($paymentProcessorObject, $input);
158
159 $isFirstOrLastRecurringPayment = FALSE;
160 if ($input['response_code'] == 1) {
161 // Approved
162 if ($first) {
163 $recur->start_date = $now;
164 $recur->trxn_id = $recur->processor_id;
165 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
166 }
167 $statusName = 'In Progress';
168 if (($recur->installments > 0) &&
169 ($input['subscription_paynum'] >= $recur->installments)
170 ) {
171 // this is the last payment
172 $statusName = 'Completed';
173 $recur->end_date = $now;
174 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
175 }
176 $recur->modified_date = $now;
177 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
178 $recur->save();
179 }
180 else {
181 // Declined
182 // failed status
183 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
184 $recur->cancel_date = $now;
185 $recur->save();
186
187 $message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text'])));
188 CRM_Core_Error::debug_log_message($message);
189
190 // the recurring contribution has declined a payment or has failed
191 // so we just fix the recurring contribution and not change any of
192 // the existing contributions
193 // CRM-9036
194 return TRUE;
195 }
196
197 // check if contribution is already completed, if so we ignore this ipn
198 if ($objects['contribution']->contribution_status_id == 1) {
199 $transaction->commit();
200 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
201 echo "Success: Contribution has already been handled<p>";
202 return TRUE;
203 }
204
205 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
206
207 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
208 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
209 // from isSentReceipt to an array of which receipts to send.
210 // Note that there is site-by-site opinions on which notifications are good to send.
211 if ($isFirstOrLastRecurringPayment) {
212 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
213 $isFirstOrLastRecurringPayment);
214 }
215
216 }
217
218 /**
219 * Get the input from passed in fields.
220 *
221 * @param array $input
222 * @param array $ids
223 *
224 * @return bool
225 */
226 public function getInput(&$input, &$ids) {
227 $input['amount'] = $this->retrieve('x_amount', 'String');
228 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
229 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
230 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
231 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
232 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
233 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
234 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
235 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
236 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, 'now');
237
238 if ($input['trxn_id']) {
239 $input['is_test'] = 0;
240 }
241 // Only assume trxn_id 'should' have been returned for success.
242 // Per CRM-17611 it would also not be passed back for a decline.
243 elseif ($input['response_code'] == 1) {
244 $input['is_test'] = 1;
245 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
246 }
247
248 if (!$this->getBillingID($ids)) {
249 return FALSE;
250 }
251 $billingID = $ids['billing'];
252 $params = array(
253 'first_name' => 'x_first_name',
254 'last_name' => 'x_last_name',
255 "street_address-{$billingID}" => 'x_address',
256 "city-{$billingID}" => 'x_city',
257 "state-{$billingID}" => 'x_state',
258 "postal_code-{$billingID}" => 'x_zip',
259 "country-{$billingID}" => 'x_country',
260 "email-{$billingID}" => 'x_email',
261 );
262 foreach ($params as $civiName => $resName) {
263 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
264 }
265 }
266
267 /**
268 * Get ids from input.
269 *
270 * @param array $ids
271 * @param array $input
272 *
273 * @throws \CRM_Core_Exception
274 */
275 public function getIDs(&$ids, &$input) {
276 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
277 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
278
279 // joining with contribution table for extra checks
280 $sql = "
281 SELECT cr.id, cr.contact_id
282 FROM civicrm_contribution_recur cr
283 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
284 WHERE cr.processor_id = '{$input['subscription_id']}' AND
285 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
286 LIMIT 1";
287 $contRecur = CRM_Core_DAO::executeQuery($sql);
288 $contRecur->fetch();
289 $ids['contributionRecur'] = $contRecur->id;
290 if ($ids['contact'] != $contRecur->contact_id) {
291 $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));
292 CRM_Core_Error::debug_log_message($message);
293 $ids['contact'] = $contRecur->contact_id;
294 }
295 if (!$ids['contributionRecur']) {
296 $message = ts("Could not find contributionRecur id");
297 $log = new CRM_Utils_SystemLogger();
298 $log->error('payment_notification', array('message' => $message, 'ids' => $ids, 'input' => $input));
299 throw new CRM_Core_Exception($message);
300 }
301
302 // get page id based on contribution id
303 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
304 $ids['contribution'],
305 'contribution_page_id'
306 );
307
308 if ($input['component'] == 'event') {
309 // FIXME: figure out fields for event
310 }
311 else {
312 // Get membershipId. Join with membership payment table for additional checks
313 $sql = "
314 SELECT m.id
315 FROM civicrm_membership m
316 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
317 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
318 LIMIT 1";
319 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
320 $ids['membership'] = $membershipId;
321 }
322
323 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
324 }
325 }
326
327 /**
328 * @param string $name
329 * Parameter name.
330 * @param string $type
331 * Parameter type.
332 * @param bool $abort
333 * Abort if not present.
334 * @param null $default
335 * Default value.
336 *
337 * @throws CRM_Core_Exception
338 * @return mixed
339 */
340 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
341 $value = CRM_Utils_Type::validate(
342 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
343 $type,
344 FALSE
345 );
346 if ($abort && $value === NULL) {
347 throw new CRM_Core_Exception("Could not find an entry for $name");
348 }
349 return $value;
350 }
351
352 /**
353 * Check and validate gateway MD5 response if present.
354 *
355 * @param CRM_Core_Payment_AuthorizeNet $paymentObject
356 * @param array $input
357 *
358 * @throws CRM_Core_Exception
359 */
360 public function checkMD5($paymentObject, $input) {
361 if (empty($input['trxn_id'])) {
362 // For decline we have nothing to check against.
363 return;
364 }
365 if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
366 $message = "Failure: Security verification failed";
367 $log = new CRM_Utils_SystemLogger();
368 $log->error('payment_notification', array('message' => $message, 'input' => $input));
369 throw new CRM_Core_Exception($message);
370 }
371 }
372
373 }