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