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