Merge pull request #13374 from cividesk/dev-627
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 = [];
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 // Attempt to get payment processor ID from URL
71 if (!empty($this->_inputParameters['processor_id'])) {
72 $paymentProcessorID = $this->_inputParameters['processor_id'];
73 }
74 else {
75 // This is an unreliable method as there could be more than one instance.
76 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
77 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
78 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
79 // & call completetransaction or call fail? (which may not exist yet).
80 Civi::log()->warning('Unreliable method used to get payment_processor_id for AuthNet IPN - this will cause problems if you have more than one instance');
81 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
82 'AuthNet', 'id', 'name'
83 );
84 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
85 'is_test' => 0,
86 'options' => ['limit' => 1],
87 'payment_processor_type_id' => $paymentProcessorTypeID,
88 'return' => 'id',
89 ]);
90 }
91
92 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
93 return FALSE;
94 }
95 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id != $ids['paymentProcessor']) {
96 Civi::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
97 }
98
99 if ($component == 'contribute' && $ids['contributionRecur']) {
100 // check if first contribution is completed, else complete first contribution
101 $first = TRUE;
102 if ($objects['contribution']->contribution_status_id == 1) {
103 $first = FALSE;
104 }
105 return $this->recur($input, $ids, $objects, $first);
106 }
107 }
108 return TRUE;
109 }
110
111 /**
112 * @param array $input
113 * @param array $ids
114 * @param array $objects
115 * @param $first
116 *
117 * @return bool
118 */
119 public function recur(&$input, &$ids, &$objects, $first) {
120 $this->_isRecurring = TRUE;
121 $recur = &$objects['contributionRecur'];
122 $paymentProcessorObject = $objects['contribution']->_relatedObjects['paymentProcessor']['object'];
123
124 // do a subscription check
125 if ($recur->processor_id != $input['subscription_id']) {
126 CRM_Core_Error::debug_log_message("Unrecognized subscription.");
127 echo "Failure: Unrecognized subscription<p>";
128 return FALSE;
129 }
130
131 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
132
133 $transaction = new CRM_Core_Transaction();
134
135 $now = date('YmdHis');
136
137 // fix dates that already exist
138 $dates = ['create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date'];
139 foreach ($dates as $name) {
140 if ($recur->$name) {
141 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
142 }
143 }
144
145 //load new contribution object if required.
146 if (!$first) {
147 // create a contribution and then get it processed
148 $contribution = new CRM_Contribute_BAO_Contribution();
149 $contribution->contact_id = $ids['contact'];
150 $contribution->financial_type_id = $objects['contributionType']->id;
151 $contribution->contribution_page_id = $ids['contributionPage'];
152 $contribution->contribution_recur_id = $ids['contributionRecur'];
153 $contribution->receive_date = $input['receive_date'];
154 $contribution->currency = $objects['contribution']->currency;
155 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
156 $contribution->amount_level = $objects['contribution']->amount_level;
157 $contribution->address_id = $objects['contribution']->address_id;
158 $contribution->campaign_id = $objects['contribution']->campaign_id;
159 $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
160
161 $objects['contribution'] = &$contribution;
162 }
163 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
164 $objects['contribution']->total_amount = $input['amount'];
165 $objects['contribution']->trxn_id = $input['trxn_id'];
166
167 $isFirstOrLastRecurringPayment = FALSE;
168 if ($input['response_code'] == 1) {
169 // Approved
170 if ($first) {
171 $recur->start_date = $now;
172 $recur->trxn_id = $recur->processor_id;
173 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
174 }
175 $statusName = 'In Progress';
176 if (($recur->installments > 0) &&
177 ($input['subscription_paynum'] >= $recur->installments)
178 ) {
179 // this is the last payment
180 $statusName = 'Completed';
181 $recur->end_date = $now;
182 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
183 }
184 $recur->modified_date = $now;
185 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
186 $recur->save();
187 }
188 else {
189 // Declined
190 // failed status
191 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
192 $recur->cancel_date = $now;
193 $recur->save();
194
195 $message = ts("Subscription payment failed - %1", [1 => htmlspecialchars($input['response_reason_text'])]);
196 CRM_Core_Error::debug_log_message($message);
197
198 // the recurring contribution has declined a payment or has failed
199 // so we just fix the recurring contribution and not change any of
200 // the existing contributions
201 // CRM-9036
202 return TRUE;
203 }
204
205 // check if contribution is already completed, if so we ignore this ipn
206 if ($objects['contribution']->contribution_status_id == 1) {
207 $transaction->commit();
208 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
209 echo "Success: Contribution has already been handled<p>";
210 return TRUE;
211 }
212
213 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
214
215 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
216 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
217 // from isSentReceipt to an array of which receipts to send.
218 // Note that there is site-by-site opinions on which notifications are good to send.
219 if ($isFirstOrLastRecurringPayment) {
220 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
221 $isFirstOrLastRecurringPayment);
222 }
223
224 }
225
226 /**
227 * Get the input from passed in fields.
228 *
229 * @param array $input
230 * @param array $ids
231 *
232 * @return bool
233 */
234 public function getInput(&$input, &$ids) {
235 $input['amount'] = $this->retrieve('x_amount', 'String');
236 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
237 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
238 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
239 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
240 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
241 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
242 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
243 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
244 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, 'now');
245
246 if ($input['trxn_id']) {
247 $input['is_test'] = 0;
248 }
249 // Only assume trxn_id 'should' have been returned for success.
250 // Per CRM-17611 it would also not be passed back for a decline.
251 elseif ($input['response_code'] == 1) {
252 $input['is_test'] = 1;
253 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
254 }
255
256 if (!$this->getBillingID($ids)) {
257 return FALSE;
258 }
259 $billingID = $ids['billing'];
260 $params = [
261 'first_name' => 'x_first_name',
262 'last_name' => 'x_last_name',
263 "street_address-{$billingID}" => 'x_address',
264 "city-{$billingID}" => 'x_city',
265 "state-{$billingID}" => 'x_state',
266 "postal_code-{$billingID}" => 'x_zip',
267 "country-{$billingID}" => 'x_country',
268 "email-{$billingID}" => 'x_email',
269 ];
270 foreach ($params as $civiName => $resName) {
271 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
272 }
273 }
274
275 /**
276 * Get ids from input.
277 *
278 * @param array $ids
279 * @param array $input
280 *
281 * @throws \CRM_Core_Exception
282 */
283 public function getIDs(&$ids, &$input) {
284 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
285 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
286
287 // joining with contribution table for extra checks
288 $sql = "
289 SELECT cr.id, cr.contact_id
290 FROM civicrm_contribution_recur cr
291 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
292 WHERE cr.processor_id = '{$input['subscription_id']}' AND
293 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
294 LIMIT 1";
295 $contRecur = CRM_Core_DAO::executeQuery($sql);
296 $contRecur->fetch();
297 $ids['contributionRecur'] = $contRecur->id;
298 if ($ids['contact'] != $contRecur->contact_id) {
299 $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", [1 => $ids['contact'], 2 => $contRecur->contact_id]);
300 CRM_Core_Error::debug_log_message($message);
301 $ids['contact'] = $contRecur->contact_id;
302 }
303 if (!$ids['contributionRecur']) {
304 $message = ts("Could not find contributionRecur id");
305 $log = new CRM_Utils_SystemLogger();
306 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
307 throw new CRM_Core_Exception($message);
308 }
309
310 // get page id based on contribution id
311 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
312 $ids['contribution'],
313 'contribution_page_id'
314 );
315
316 if ($input['component'] == 'event') {
317 // FIXME: figure out fields for event
318 }
319 else {
320 // Get membershipId. Join with membership payment table for additional checks
321 $sql = "
322 SELECT m.id
323 FROM civicrm_membership m
324 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
325 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
326 LIMIT 1";
327 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
328 $ids['membership'] = $membershipId;
329 }
330
331 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
332 }
333 }
334
335 /**
336 * @param string $name
337 * Parameter name.
338 * @param string $type
339 * Parameter type.
340 * @param bool $abort
341 * Abort if not present.
342 * @param null $default
343 * Default value.
344 *
345 * @throws CRM_Core_Exception
346 * @return mixed
347 */
348 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
349 $value = CRM_Utils_Type::validate(
350 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
351 $type,
352 FALSE
353 );
354 if ($abort && $value === NULL) {
355 throw new CRM_Core_Exception("Could not find an entry for $name");
356 }
357 return $value;
358 }
359
360 }