Merge pull request #17719 from civicrm/5.27
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
0dbefed3 18
b5c2afd0 19 /**
fe482240 20 * Constructor function.
0dbefed3 21 *
5a4f6742
CW
22 * @param array $inputData
23 * contents of HTTP REQUEST.
0dbefed3
EM
24 *
25 * @throws CRM_Core_Exception
b5c2afd0 26 */
00be9182 27 public function __construct($inputData) {
0dbefed3 28 $this->setInputParameters($inputData);
6a488035
TO
29 parent::__construct();
30 }
31
6c786a9b
EM
32 /**
33 * @param string $component
34 *
35 * @return bool|void
36 */
00be9182 37 public function main($component = 'contribute') {
6a488035
TO
38
39 //we only get invoice num as a key player from payment gateway response.
40 //for ARB we get x_subscription_id and x_subscription_paynum
0dbefed3 41 $x_subscription_id = $this->retrieve('x_subscription_id', 'String');
be2fb01f 42 $ids = $objects = $input = [];
6a488035
TO
43
44 if ($x_subscription_id) {
dbb0d30b 45 // Presence of the id means it is approved.
6a488035
TO
46 $input['component'] = $component;
47
48 // load post vars in $input
49 $this->getInput($input, $ids);
50
51 // load post ids in $ids
52 $this->getIDs($ids, $input);
53
c5cf3602
JP
54 // Attempt to get payment processor ID from URL
55 if (!empty($this->_inputParameters['processor_id'])) {
56 $paymentProcessorID = $this->_inputParameters['processor_id'];
57 }
58 else {
59 // This is an unreliable method as there could be more than one instance.
60 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
61 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
62 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
63 // & call completetransaction or call fail? (which may not exist yet).
d2803851 64 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');
c5cf3602
JP
65 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
66 'AuthNet', 'id', 'name'
67 );
be2fb01f 68 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
c5cf3602 69 'is_test' => 0,
be2fb01f 70 'options' => ['limit' => 1],
c5cf3602 71 'payment_processor_type_id' => $paymentProcessorTypeID,
518fa0ee 72 'return' => 'id',
be2fb01f 73 ]);
c5cf3602 74 }
6a488035
TO
75
76 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
77 return FALSE;
78 }
f4aff12e 79 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id != $ids['paymentProcessor']) {
be2fb01f 80 Civi::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
f4aff12e 81 }
6a488035
TO
82
83 if ($component == 'contribute' && $ids['contributionRecur']) {
84 // check if first contribution is completed, else complete first contribution
85 $first = TRUE;
86 if ($objects['contribution']->contribution_status_id == 1) {
87 $first = FALSE;
88 }
89 return $this->recur($input, $ids, $objects, $first);
90 }
91 }
0dbefed3 92 return TRUE;
6a488035
TO
93 }
94
6c786a9b 95 /**
7a6073fd
EM
96 * @param array $input
97 * @param array $ids
0dbefed3 98 * @param array $objects
6c786a9b 99 * @param $first
7a6073fd
EM
100 *
101 * @return bool
6c786a9b 102 */
00be9182 103 public function recur(&$input, &$ids, &$objects, $first) {
937cf542 104 $this->_isRecurring = TRUE;
6a488035 105 $recur = &$objects['contributionRecur'];
d6944518 106 $paymentProcessorObject = $objects['contribution']->_relatedObjects['paymentProcessor']['object'];
6a488035
TO
107
108 // do a subscription check
109 if ($recur->processor_id != $input['subscription_id']) {
110 CRM_Core_Error::debug_log_message("Unrecognized subscription.");
111 echo "Failure: Unrecognized subscription<p>";
112 return FALSE;
113 }
114
6a488035
TO
115 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
116
117 $transaction = new CRM_Core_Transaction();
118
119 $now = date('YmdHis');
120
6a488035
TO
121 //load new contribution object if required.
122 if (!$first) {
123 // create a contribution and then get it processed
124 $contribution = new CRM_Contribute_BAO_Contribution();
125 $contribution->contact_id = $ids['contact'];
353ffa53 126 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
127 $contribution->contribution_page_id = $ids['contributionPage'];
128 $contribution->contribution_recur_id = $ids['contributionRecur'];
4a1ba425 129 $contribution->receive_date = $input['receive_date'];
6a488035
TO
130 $contribution->currency = $objects['contribution']->currency;
131 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
132 $contribution->amount_level = $objects['contribution']->amount_level;
133 $contribution->address_id = $objects['contribution']->address_id;
94d1bc8d 134 $contribution->campaign_id = $objects['contribution']->campaign_id;
9bee639f 135 $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
94d1bc8d 136
6a488035
TO
137 $objects['contribution'] = &$contribution;
138 }
139 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
140 $objects['contribution']->total_amount = $input['amount'];
141 $objects['contribution']->trxn_id = $input['trxn_id'];
142
4086637a 143 $isFirstOrLastRecurringPayment = FALSE;
6a488035
TO
144 if ($input['response_code'] == 1) {
145 // Approved
146 if ($first) {
147 $recur->start_date = $now;
148 $recur->trxn_id = $recur->processor_id;
4086637a 149 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
6a488035
TO
150 }
151 $statusName = 'In Progress';
152 if (($recur->installments > 0) &&
153 ($input['subscription_paynum'] >= $recur->installments)
154 ) {
155 // this is the last payment
156 $statusName = 'Completed';
157 $recur->end_date = $now;
4086637a 158 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
6a488035
TO
159 }
160 $recur->modified_date = $now;
161 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
162 $recur->save();
163 }
164 else {
165 // Declined
166 // failed status
167 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
168 $recur->cancel_date = $now;
169 $recur->save();
170
be2fb01f 171 $message = ts("Subscription payment failed - %1", [1 => htmlspecialchars($input['response_reason_text'])]);
267353f4 172 CRM_Core_Error::debug_log_message($message);
6a488035
TO
173
174 // the recurring contribution has declined a payment or has failed
175 // so we just fix the recurring contribution and not change any of
7a6073fd 176 // the existing contributions
6a488035
TO
177 // CRM-9036
178 return TRUE;
179 }
180
181 // check if contribution is already completed, if so we ignore this ipn
182 if ($objects['contribution']->contribution_status_id == 1) {
183 $transaction->commit();
267353f4 184 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
6a488035
TO
185 echo "Success: Contribution has already been handled<p>";
186 return TRUE;
187 }
188
189 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
4086637a 190
191 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
192 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
193 // from isSentReceipt to an array of which receipts to send.
194 // Note that there is site-by-site opinions on which notifications are good to send.
195 if ($isFirstOrLastRecurringPayment) {
196 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
197 $isFirstOrLastRecurringPayment);
198 }
199
6a488035
TO
200 }
201
6c786a9b 202 /**
dbb0d30b 203 * Get the input from passed in fields.
204 *
205 * @param array $input
206 * @param array $ids
7a9ab499 207 *
23cfc7a6 208 * @throws \CRM_Core_Exception
6c786a9b 209 */
00be9182 210 public function getInput(&$input, &$ids) {
0dbefed3
EM
211 $input['amount'] = $this->retrieve('x_amount', 'String');
212 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
213 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
214 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
215 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
216 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
217 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
218 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
4a1ba425 219 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
23cfc7a6 220 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
0dbefed3 221
6a488035
TO
222 if ($input['trxn_id']) {
223 $input['is_test'] = 0;
224 }
5c6c7e76 225 // Only assume trxn_id 'should' have been returned for success.
226 // Per CRM-17611 it would also not be passed back for a decline.
227 elseif ($input['response_code'] == 1) {
6a488035
TO
228 $input['is_test'] = 1;
229 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
230 }
231
e9a11021 232 $billingID = $ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
be2fb01f 233 $params = [
6a488035
TO
234 'first_name' => 'x_first_name',
235 'last_name' => 'x_last_name',
236 "street_address-{$billingID}" => 'x_address',
237 "city-{$billingID}" => 'x_city',
238 "state-{$billingID}" => 'x_state',
239 "postal_code-{$billingID}" => 'x_zip',
240 "country-{$billingID}" => 'x_country',
241 "email-{$billingID}" => 'x_email',
be2fb01f 242 ];
6a488035 243 foreach ($params as $civiName => $resName) {
0dbefed3 244 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
6a488035
TO
245 }
246 }
247
6c786a9b 248 /**
dbb0d30b 249 * Get ids from input.
250 *
251 * @param array $ids
252 * @param array $input
253 *
254 * @throws \CRM_Core_Exception
6c786a9b 255 */
00be9182 256 public function getIDs(&$ids, &$input) {
0dbefed3
EM
257 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
258 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
6a488035
TO
259
260 // joining with contribution table for extra checks
261 $sql = "
262 SELECT cr.id, cr.contact_id
263 FROM civicrm_contribution_recur cr
264INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
265 WHERE cr.processor_id = '{$input['subscription_id']}' AND
266 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
267 LIMIT 1";
268 $contRecur = CRM_Core_DAO::executeQuery($sql);
269 $contRecur->fetch();
270 $ids['contributionRecur'] = $contRecur->id;
9b873358 271 if ($ids['contact'] != $contRecur->contact_id) {
be2fb01f 272 $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]);
267353f4 273 CRM_Core_Error::debug_log_message($message);
8753de39 274 $ids['contact'] = $contRecur->contact_id;
6a488035
TO
275 }
276 if (!$ids['contributionRecur']) {
4346da4b 277 $message = ts("Could not find contributionRecur id");
278 $log = new CRM_Utils_SystemLogger();
be2fb01f 279 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
4346da4b 280 throw new CRM_Core_Exception($message);
6a488035
TO
281 }
282
283 // get page id based on contribution id
284 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
285 $ids['contribution'],
286 'contribution_page_id'
287 );
288
289 if ($input['component'] == 'event') {
290 // FIXME: figure out fields for event
291 }
292 else {
6a488035
TO
293 // Get membershipId. Join with membership payment table for additional checks
294 $sql = "
295 SELECT m.id
296 FROM civicrm_membership m
297INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
298 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
299 LIMIT 1";
300 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
301 $ids['membership'] = $membershipId;
302 }
303
304 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
305 }
306 }
307
6c786a9b 308 /**
6a0b768e
TO
309 * @param string $name
310 * Parameter name.
311 * @param string $type
312 * Parameter type.
313 * @param bool $abort
314 * Abort if not present.
315 * @param null $default
316 * Default value.
6c786a9b 317 *
0dbefed3 318 * @throws CRM_Core_Exception
6c786a9b
EM
319 * @return mixed
320 */
00be9182 321 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
0dbefed3
EM
322 $value = CRM_Utils_Type::validate(
323 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
324 $type,
325 FALSE
6a488035
TO
326 );
327 if ($abort && $value === NULL) {
0dbefed3 328 throw new CRM_Core_Exception("Could not find an entry for $name");
6a488035
TO
329 }
330 return $value;
2aa397bc 331 }
6a488035 332
6a488035 333}