Merge pull request #18742 from jitendrapurohit/merge-uid
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
18
19 /**
20 * Constructor function.
21 *
22 * @param array $inputData
23 * contents of HTTP REQUEST.
24 *
25 * @throws CRM_Core_Exception
26 */
27 public function __construct($inputData) {
28 $this->setInputParameters($inputData);
29 parent::__construct();
30 }
31
32 /**
33 * @param string $component
34 *
35 * @return bool|void
36 */
37 public function main($component = 'contribute') {
38 try {
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
41 $x_subscription_id = $this->retrieve('x_subscription_id', 'String');
42 $ids = $objects = $input = [];
43
44 if ($x_subscription_id) {
45 // Presence of the id means it is approved.
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
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).
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');
65 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
66 'AuthNet', 'id', 'name'
67 );
68 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
69 'is_test' => 0,
70 'options' => ['limit' => 1],
71 'payment_processor_type_id' => $paymentProcessorTypeID,
72 'return' => 'id',
73 ]);
74 }
75
76 // Check if the contribution exists
77 // make sure contribution exists and is valid
78 $contribution = new CRM_Contribute_BAO_Contribution();
79 $contribution->id = $ids['contribution'];
80 if (!$contribution->find(TRUE)) {
81 throw new CRM_Core_Exception('Failure: Could not find contribution record for ' . (int) $contribution->id, NULL, ['context' => "Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE)]);
82 }
83 $ids['contributionPage'] = $contribution->contribution_page_id;
84
85 // make sure contact exists and is valid
86 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
87 $contact = new CRM_Contact_BAO_Contact();
88 $contact->id = $contribution->contact_id;
89 $contact->find(TRUE);
90 if ($contact->id != $ids['contact']) {
91 // If the ids do not match then it is possible the contact id in the IPN has been merged into another contact which is why we use the contact_id from the contribution
92 CRM_Core_Error::debug_log_message("Contact ID in IPN {$ids['contact']} not found but contact_id found in contribution {$contribution->contact_id} used instead");
93 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
94 $ids['contact'] = $contribution->contact_id;
95 }
96
97 if (!empty($ids['contributionRecur'])) {
98 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
99 $contributionRecur->id = $ids['contributionRecur'];
100 if (!$contributionRecur->find(TRUE)) {
101 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
102 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
103 return FALSE;
104 }
105 }
106
107 $objects['contact'] = &$contact;
108 $objects['contribution'] = &$contribution;
109
110 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
111
112 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id != $ids['paymentProcessor']) {
113 Civi::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
114 }
115
116 if ($component == 'contribute' && $ids['contributionRecur']) {
117 // check if first contribution is completed, else complete first contribution
118 $first = TRUE;
119 if ($objects['contribution']->contribution_status_id == 1) {
120 $first = FALSE;
121 //load new contribution object if required.
122 // create a contribution and then get it processed
123 $contribution = new CRM_Contribute_BAO_Contribution();
124 $contribution->contact_id = $ids['contact'];
125 $contribution->financial_type_id = $objects['contributionType']->id;
126 $contribution->contribution_page_id = $ids['contributionPage'];
127 $contribution->contribution_recur_id = $ids['contributionRecur'];
128 $contribution->receive_date = $input['receive_date'];
129 $contribution->currency = $objects['contribution']->currency;
130 $contribution->amount_level = $objects['contribution']->amount_level;
131 $contribution->address_id = $objects['contribution']->address_id;
132 $contribution->campaign_id = $objects['contribution']->campaign_id;
133 $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
134
135 $objects['contribution'] = &$contribution;
136 }
137 $input['payment_processor_id'] = $paymentProcessorID;
138 return $this->recur($input, [
139 'related_contact' => $ids['related_contact'] ?? NULL,
140 'participant' => !empty($objects['participant']) ? $objects['participant']->id : NULL,
141 'contributionRecur' => !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
142 'contact' => $ids['contact'] ?? NULL,
143 'contributionPage' => $ids['contributionPage'] ?? NULL,
144 ], $objects, $first);
145 }
146 }
147 return TRUE;
148 }
149 catch (CRM_Core_Exception $e) {
150 Civi::log()->debug($e->getMessage());
151 echo 'Invalid or missing data';
152 }
153 }
154
155 /**
156 * @param array $input
157 * @param array $ids
158 * @param array $objects
159 * @param $first
160 *
161 * @return bool
162 * @throws \CRM_Core_Exception
163 * @throws \CiviCRM_API3_Exception
164 */
165 public function recur($input, $ids, $objects, $first) {
166 $recur = &$objects['contributionRecur'];
167 $contribution = &$objects['contribution'];
168
169 // do a subscription check
170 if ($recur->processor_id != $input['subscription_id']) {
171 throw new CRM_Core_Exception('Unrecognized subscription.');
172 }
173
174 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
175
176 $now = date('YmdHis');
177
178 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
179 $objects['contribution']->total_amount = $input['amount'];
180 $objects['contribution']->trxn_id = $input['trxn_id'];
181
182 $isFirstOrLastRecurringPayment = FALSE;
183 if ($input['response_code'] == 1) {
184 // Approved
185 if ($first) {
186 $recur->start_date = $now;
187 $recur->trxn_id = $recur->processor_id;
188 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
189 }
190
191 if (($recur->installments > 0) &&
192 ($input['subscription_paynum'] >= $recur->installments)
193 ) {
194 // this is the last payment
195 $recur->end_date = $now;
196 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
197 // This end date update should occur in ContributionRecur::updateOnNewPayment
198 // testIPNPaymentRecurNoReceipt has test cover.
199 $recur->save();
200 }
201 }
202 else {
203 // Declined
204 // failed status
205 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
206 $recur->cancel_date = $now;
207 $recur->save();
208
209 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
210 CRM_Core_Error::debug_log_message($message);
211
212 // the recurring contribution has declined a payment or has failed
213 // so we just fix the recurring contribution and not change any of
214 // the existing contributions
215 // CRM-9036
216 return TRUE;
217 }
218
219 // check if contribution is already completed, if so we ignore this ipn
220 if ($objects['contribution']->contribution_status_id == 1) {
221 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
222 echo 'Success: Contribution has already been handled<p>';
223 return TRUE;
224 }
225
226 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects['contribution']);
227
228 if ($isFirstOrLastRecurringPayment) {
229 //send recurring Notification email for user
230 CRM_Contribute_BAO_ContributionPage::recurringNotify(TRUE,
231 $ids['contact'],
232 $ids['contributionPage'],
233 $recur,
234 (bool) $this->getMembershipID($contribution->id, $recur->id)
235 );
236 }
237 }
238
239 /**
240 * Get the input from passed in fields.
241 *
242 * @param array $input
243 *
244 * @throws \CRM_Core_Exception
245 */
246 public function getInput(&$input) {
247 $input['amount'] = $this->retrieve('x_amount', 'String');
248 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
249 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
250 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
251 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
252 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
253 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
254 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
255 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
256
257 if ($input['trxn_id']) {
258 $input['is_test'] = 0;
259 }
260 // Only assume trxn_id 'should' have been returned for success.
261 // Per CRM-17611 it would also not be passed back for a decline.
262 elseif ($input['response_code'] == 1) {
263 $input['is_test'] = 1;
264 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
265 }
266
267 $billingID = CRM_Core_BAO_LocationType::getBilling();
268 $params = [
269 'first_name' => 'x_first_name',
270 'last_name' => 'x_last_name',
271 "street_address-{$billingID}" => 'x_address',
272 "city-{$billingID}" => 'x_city',
273 "state-{$billingID}" => 'x_state',
274 "postal_code-{$billingID}" => 'x_zip',
275 "country-{$billingID}" => 'x_country',
276 "email-{$billingID}" => 'x_email',
277 ];
278 foreach ($params as $civiName => $resName) {
279 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
280 }
281 }
282
283 /**
284 * Get ids from input.
285 *
286 * @param array $ids
287 * @param array $input
288 *
289 * @throws \CRM_Core_Exception
290 */
291 public function getIDs(&$ids, &$input) {
292 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
293 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
294
295 // joining with contribution table for extra checks
296 $sql = "
297 SELECT cr.id, cr.contact_id
298 FROM civicrm_contribution_recur cr
299 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
300 WHERE cr.processor_id = '{$input['subscription_id']}' AND
301 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
302 LIMIT 1";
303 $contRecur = CRM_Core_DAO::executeQuery($sql);
304 $contRecur->fetch();
305 $ids['contributionRecur'] = (int) $contRecur->id;
306 if ($ids['contact'] != $contRecur->contact_id) {
307 $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]);
308 CRM_Core_Error::debug_log_message($message);
309 $ids['contact'] = $contRecur->contact_id;
310 }
311 if (!$ids['contributionRecur']) {
312 $message = ts("Could not find contributionRecur id");
313 $log = new CRM_Utils_SystemLogger();
314 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
315 throw new CRM_Core_Exception($message);
316 }
317 }
318
319 /**
320 * @param string $name
321 * Parameter name.
322 * @param string $type
323 * Parameter type.
324 * @param bool $abort
325 * Abort if not present.
326 * @param null $default
327 * Default value.
328 *
329 * @throws CRM_Core_Exception
330 * @return mixed
331 */
332 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
333 $value = CRM_Utils_Type::validate(
334 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
335 $type,
336 FALSE
337 );
338 if ($abort && $value === NULL) {
339 throw new CRM_Core_Exception("Could not find an entry for $name");
340 }
341 return $value;
342 }
343
344 /**
345 * Get membership id, if any.
346 *
347 * @param int $contributionID
348 * @param int $contributionRecurID
349 *
350 * @return int|null
351 */
352 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?int {
353 // Get membershipId. Join with membership payment table for additional checks
354 $sql = "
355 SELECT m.id
356 FROM civicrm_membership m
357 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$contributionID}
358 WHERE m.contribution_recur_id = {$contributionRecurID}
359 LIMIT 1";
360 return CRM_Core_DAO::singleValueQuery($sql);
361 }
362
363 }