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