Merge pull request #18829 from eileenmcnaughton/aip
[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 if (!$x_subscription_id) {
43 // Presence of the id means it is approved.
44 return TRUE;
45 }
46 $ids = $objects = $input = [];
47
48 $input['component'] = $component;
49
50 // load post vars in $input
51 $this->getInput($input, $ids);
52
53 // load post ids in $ids
54 $this->getIDs($ids, $input);
55 $paymentProcessorID = $this->getPaymentProcessorID();
56
57 // Check if the contribution exists
58 // make sure contribution exists and is valid
59 $contribution = new CRM_Contribute_BAO_Contribution();
60 $contribution->id = $ids['contribution'];
61 if (!$contribution->find(TRUE)) {
62 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)]);
63 }
64 $ids['contributionPage'] = $contribution->contribution_page_id;
65
66 // make sure contact exists and is valid
67 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
68 $contact = new CRM_Contact_BAO_Contact();
69 $contact->id = $contribution->contact_id;
70 $contact->find(TRUE);
71 if ($contact->id != $ids['contact']) {
72 // 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
73 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");
74 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
75 $ids['contact'] = $contribution->contact_id;
76 }
77
78 if (!empty($ids['contributionRecur'])) {
79 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
80 $contributionRecur->id = $ids['contributionRecur'];
81 if (!$contributionRecur->find(TRUE)) {
82 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
83 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
84 return FALSE;
85 }
86 }
87
88 $objects['contact'] = &$contact;
89 $objects['contribution'] = &$contribution;
90
91 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
92
93 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id != $ids['paymentProcessor']) {
94 Civi::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
95 }
96
97 if ($component == 'contribute' && $ids['contributionRecur']) {
98 // check if first contribution is completed, else complete first contribution
99 $first = TRUE;
100 if ($objects['contribution']->contribution_status_id == 1) {
101 $first = FALSE;
102 //load new contribution object if required.
103 // create a contribution and then get it processed
104 $contribution = new CRM_Contribute_BAO_Contribution();
105 $contribution->contact_id = $ids['contact'];
106 $contribution->financial_type_id = $objects['contributionType']->id;
107 $contribution->contribution_page_id = $ids['contributionPage'];
108 $contribution->contribution_recur_id = $ids['contributionRecur'];
109 $contribution->receive_date = $input['receive_date'];
110 $contribution->currency = $objects['contribution']->currency;
111 $contribution->amount_level = $objects['contribution']->amount_level;
112 $contribution->address_id = $objects['contribution']->address_id;
113 $contribution->campaign_id = $objects['contribution']->campaign_id;
114 $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
115
116 $objects['contribution'] = &$contribution;
117 }
118 $input['payment_processor_id'] = $paymentProcessorID;
119 return $this->recur($input, [
120 'related_contact' => $ids['related_contact'] ?? NULL,
121 'participant' => !empty($objects['participant']) ? $objects['participant']->id : NULL,
122 'contributionRecur' => !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
123 'contact' => $ids['contact'] ?? NULL,
124 'contributionPage' => $ids['contributionPage'] ?? NULL,
125 ], $objects['contributionRecur'], $objects['contribution'], $first);
126 }
127
128 return TRUE;
129 }
130 catch (CRM_Core_Exception $e) {
131 Civi::log()->debug($e->getMessage());
132 echo 'Invalid or missing data';
133 }
134 }
135
136 /**
137 * @param array $input
138 * @param array $ids
139 * @param \CRM_Contribute_BAO_ContributionRecur $recur
140 * @param \CRM_Contribute_BAO_Contribution $contribution
141 * @param bool $first
142 *
143 * @return bool
144 * @throws \CRM_Core_Exception
145 * @throws \CiviCRM_API3_Exception
146 */
147 public function recur($input, $ids, $recur, $contribution, $first) {
148
149 // do a subscription check
150 if ($recur->processor_id != $input['subscription_id']) {
151 throw new CRM_Core_Exception('Unrecognized subscription.');
152 }
153
154 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
155
156 $now = date('YmdHis');
157
158 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
159 $contribution->total_amount = $input['amount'];
160 $contribution->trxn_id = $input['trxn_id'];
161
162 $isFirstOrLastRecurringPayment = FALSE;
163 if ($input['response_code'] == 1) {
164 // Approved
165 if ($first) {
166 $recur->start_date = $now;
167 $recur->trxn_id = $recur->processor_id;
168 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
169 }
170
171 if (($recur->installments > 0) &&
172 ($input['subscription_paynum'] >= $recur->installments)
173 ) {
174 // this is the last payment
175 $recur->end_date = $now;
176 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
177 // This end date update should occur in ContributionRecur::updateOnNewPayment
178 // testIPNPaymentRecurNoReceipt has test cover.
179 $recur->save();
180 }
181 }
182 else {
183 // Declined
184 // failed status
185 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
186 $recur->cancel_date = $now;
187 $recur->save();
188
189 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
190 CRM_Core_Error::debug_log_message($message);
191
192 // the recurring contribution has declined a payment or has failed
193 // so we just fix the recurring contribution and not change any of
194 // the existing contributions
195 // CRM-9036
196 return TRUE;
197 }
198
199 // check if contribution is already completed, if so we ignore this ipn
200 if ($contribution->contribution_status_id == 1) {
201 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
202 echo 'Success: Contribution has already been handled<p>';
203 return TRUE;
204 }
205
206 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $contribution);
207
208 if ($isFirstOrLastRecurringPayment) {
209 //send recurring Notification email for user
210 CRM_Contribute_BAO_ContributionPage::recurringNotify(TRUE,
211 $ids['contact'],
212 $ids['contributionPage'],
213 $recur,
214 (bool) $this->getMembershipID($contribution->id, $recur->id)
215 );
216 }
217 }
218
219 /**
220 * Get the input from passed in fields.
221 *
222 * @param array $input
223 *
224 * @throws \CRM_Core_Exception
225 */
226 public function getInput(&$input) {
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['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
236
237 if ($input['trxn_id']) {
238 $input['is_test'] = 0;
239 }
240 // Only assume trxn_id 'should' have been returned for success.
241 // Per CRM-17611 it would also not be passed back for a decline.
242 elseif ($input['response_code'] == 1) {
243 $input['is_test'] = 1;
244 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
245 }
246
247 $billingID = CRM_Core_BAO_LocationType::getBilling();
248 $params = [
249 'first_name' => 'x_first_name',
250 'last_name' => 'x_last_name',
251 "street_address-{$billingID}" => 'x_address',
252 "city-{$billingID}" => 'x_city',
253 "state-{$billingID}" => 'x_state',
254 "postal_code-{$billingID}" => 'x_zip',
255 "country-{$billingID}" => 'x_country',
256 "email-{$billingID}" => 'x_email',
257 ];
258 foreach ($params as $civiName => $resName) {
259 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
260 }
261 }
262
263 /**
264 * Get ids from input.
265 *
266 * @param array $ids
267 * @param array $input
268 *
269 * @throws \CRM_Core_Exception
270 */
271 public function getIDs(&$ids, $input) {
272 $ids['contact'] = (int) $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
273 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
274 $contributionRecur = $this->getContributionRecurObject($input['subscription_id'], $ids['contact'], $ids['contribution']);
275 $ids['contributionRecur'] = (int) $contributionRecur->id;
276 $ids['contact'] = $contributionRecur->contact_id;
277 }
278
279 /**
280 * @param string $name
281 * Parameter name.
282 * @param string $type
283 * Parameter type.
284 * @param bool $abort
285 * Abort if not present.
286 * @param null $default
287 * Default value.
288 *
289 * @throws CRM_Core_Exception
290 * @return mixed
291 */
292 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
293 $value = CRM_Utils_Type::validate(
294 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
295 $type,
296 FALSE
297 );
298 if ($abort && $value === NULL) {
299 throw new CRM_Core_Exception("Could not find an entry for $name");
300 }
301 return $value;
302 }
303
304 /**
305 * Get membership id, if any.
306 *
307 * @param int $contributionID
308 * @param int $contributionRecurID
309 *
310 * @return int|null
311 */
312 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?int {
313 // Get membershipId. Join with membership payment table for additional checks
314 $sql = "
315 SELECT m.id
316 FROM civicrm_membership m
317 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$contributionID}
318 WHERE m.contribution_recur_id = {$contributionRecurID}
319 LIMIT 1";
320 return CRM_Core_DAO::singleValueQuery($sql);
321 }
322
323 /**
324 * Get the recurring contribution object.
325 *
326 * @param string $processorID
327 * @param int $contactID
328 * @param int $contributionID
329 *
330 * @return \CRM_Core_DAO|\DB_Error|object
331 * @throws \CRM_Core_Exception
332 */
333 protected function getContributionRecurObject(string $processorID, int $contactID, int $contributionID) {
334 // joining with contribution table for extra checks
335 $sql = "
336 SELECT cr.id, cr.contact_id
337 FROM civicrm_contribution_recur cr
338 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
339 WHERE cr.processor_id = '{$processorID}' AND
340 (cr.contact_id = $contactID OR co.id = $contributionID)
341 LIMIT 1";
342 $contRecur = CRM_Core_DAO::executeQuery($sql);
343 if (!$contRecur->fetch()) {
344 throw new CRM_Core_Exception('Could not find contributionRecur id');
345 }
346 if ($contactID != $contRecur->contact_id) {
347 $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]);
348 CRM_Core_Error::debug_log_message($message);
349 }
350 return $contRecur;
351 }
352
353 /**
354 * Get the payment processor id.
355 *
356 * @return int
357 *
358 * @throws \CRM_Core_Exception
359 * @throws \CiviCRM_API3_Exception
360 */
361 protected function getPaymentProcessorID(): int {
362 // Attempt to get payment processor ID from URL
363 if (!empty($this->_inputParameters['processor_id'])) {
364 return (int) $this->_inputParameters['processor_id'];
365 }
366 // This is an unreliable method as there could be more than one instance.
367 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
368 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
369 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
370 // & call completetransaction or call fail? (which may not exist yet).
371 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');
372 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
373 'AuthNet', 'id', 'name'
374 );
375 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
376 'is_test' => 0,
377 'options' => ['limit' => 1],
378 'payment_processor_type_id' => $paymentProcessorTypeID,
379 'return' => 'id',
380 ]);
381 }
382
383 }