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