3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_Payment_AuthorizeNetIPN
extends CRM_Core_Payment_BaseIPN
{
20 * Constructor function.
22 * @param array $inputData
23 * contents of HTTP REQUEST.
25 * @throws CRM_Core_Exception
27 public function __construct($inputData) {
28 $this->setInputParameters($inputData);
29 parent
::__construct();
33 * @param string $component
37 public function main($component = 'contribute') {
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.
46 $ids = $objects = $input = [];
48 $input['component'] = $component;
50 // load post vars in $input
51 $this->getInput($input, $ids);
53 // load post ids in $ids
54 $this->getIDs($ids, $input);
55 $paymentProcessorID = $this->getPaymentProcessorID();
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)]);
64 $ids['contributionPage'] = $contribution->contribution_page_id
;
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
;
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
;
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));
84 $objects['contact'] = &$contact;
85 $objects['contribution'] = &$contribution;
87 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
89 if (!empty($ids['paymentProcessor']) && $contributionRecur->payment_processor_id
!= $ids['paymentProcessor']) {
90 Civi
::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
93 if ($component == 'contribute') {
94 // check if first contribution is completed, else complete first contribution
96 if ($objects['contribution']->contribution_status_id
== 1) {
98 //load new contribution object if required.
99 // create a contribution and then get it processed
100 $contribution = new CRM_Contribute_BAO_Contribution();
101 $contribution->contact_id
= $ids['contact'];
102 $contribution->financial_type_id
= $objects['contributionType']->id
;
103 $contribution->contribution_page_id
= $ids['contributionPage'];
104 $contribution->contribution_recur_id
= $ids['contributionRecur'];
105 $contribution->receive_date
= $input['receive_date'];
106 $contribution->currency
= $objects['contribution']->currency
;
107 $contribution->amount_level
= $objects['contribution']->amount_level
;
108 $contribution->address_id
= $objects['contribution']->address_id
;
109 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
110 $contribution->_relatedObjects
= $objects['contribution']->_relatedObjects
;
112 $objects['contribution'] = &$contribution;
114 $input['payment_processor_id'] = $paymentProcessorID;
115 return $this->recur($input, [
116 'related_contact' => $ids['related_contact'] ??
NULL,
117 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
118 'contributionRecur' => $contributionRecur->id
,
119 'contact' => $ids['contact'] ??
NULL,
120 'contributionPage' => $ids['contributionPage'] ??
NULL,
121 ], $objects['contributionRecur'], $objects['contribution'], $first);
126 catch (CRM_Core_Exception
$e) {
127 Civi
::log()->debug($e->getMessage());
128 echo 'Invalid or missing data';
133 * @param array $input
135 * @param \CRM_Contribute_BAO_ContributionRecur $recur
136 * @param \CRM_Contribute_BAO_Contribution $contribution
140 * @throws \CRM_Core_Exception
141 * @throws \CiviCRM_API3_Exception
143 public function recur($input, $ids, $recur, $contribution, $first) {
145 // do a subscription check
146 if ($recur->processor_id
!= $input['subscription_id']) {
147 throw new CRM_Core_Exception('Unrecognized subscription.');
150 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
152 $now = date('YmdHis');
154 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
155 $contribution->total_amount
= $input['amount'];
156 $contribution->trxn_id
= $input['trxn_id'];
158 $isFirstOrLastRecurringPayment = FALSE;
159 if ($input['response_code'] == 1) {
162 $recur->start_date
= $now;
163 $recur->trxn_id
= $recur->processor_id
;
164 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
167 if (($recur->installments
> 0) &&
168 ($input['subscription_paynum'] >= $recur->installments
)
170 // this is the last payment
171 $recur->end_date
= $now;
172 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
173 // This end date update should occur in ContributionRecur::updateOnNewPayment
174 // testIPNPaymentRecurNoReceipt has test cover.
181 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
182 $recur->cancel_date
= $now;
185 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
186 CRM_Core_Error
::debug_log_message($message);
188 // the recurring contribution has declined a payment or has failed
189 // so we just fix the recurring contribution and not change any of
190 // the existing contributions
195 // check if contribution is already completed, if so we ignore this ipn
196 if ($contribution->contribution_status_id
== 1) {
197 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
198 echo 'Success: Contribution has already been handled<p>';
202 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $contribution);
204 if ($isFirstOrLastRecurringPayment) {
205 //send recurring Notification email for user
206 CRM_Contribute_BAO_ContributionPage
::recurringNotify(TRUE,
208 $ids['contributionPage'],
210 (bool) $this->getMembershipID($contribution->id
, $recur->id
)
216 * Get the input from passed in fields.
218 * @param array $input
220 * @throws \CRM_Core_Exception
222 public function getInput(&$input) {
223 $input['amount'] = $this->retrieve('x_amount', 'String');
224 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
225 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
226 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
227 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
228 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
229 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
230 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
231 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
233 if ($input['trxn_id']) {
234 $input['is_test'] = 0;
236 // Only assume trxn_id 'should' have been returned for success.
237 // Per CRM-17611 it would also not be passed back for a decline.
238 elseif ($input['response_code'] == 1) {
239 $input['is_test'] = 1;
240 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
243 $billingID = CRM_Core_BAO_LocationType
::getBilling();
245 'first_name' => 'x_first_name',
246 'last_name' => 'x_last_name',
247 "street_address-{$billingID}" => 'x_address',
248 "city-{$billingID}" => 'x_city',
249 "state-{$billingID}" => 'x_state',
250 "postal_code-{$billingID}" => 'x_zip',
251 "country-{$billingID}" => 'x_country',
252 "email-{$billingID}" => 'x_email',
254 foreach ($params as $civiName => $resName) {
255 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
260 * Get ids from input.
263 * @param array $input
265 * @throws \CRM_Core_Exception
267 public function getIDs(&$ids, $input) {
268 $ids['contact'] = (int) $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
269 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
270 $contributionRecur = $this->getContributionRecurObject($input['subscription_id'], $ids['contact'], $ids['contribution']);
271 $ids['contributionRecur'] = (int) $contributionRecur->id
;
272 $ids['contact'] = $contributionRecur->contact_id
;
276 * @param string $name
278 * @param string $type
281 * Abort if not present.
282 * @param null $default
285 * @throws CRM_Core_Exception
288 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
289 $value = CRM_Utils_Type
::validate(
290 empty($this->_inputParameters
[$name]) ?
$default : $this->_inputParameters
[$name],
294 if ($abort && $value === NULL) {
295 throw new CRM_Core_Exception("Could not find an entry for $name");
301 * Get membership id, if any.
303 * @param int $contributionID
304 * @param int $contributionRecurID
308 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?
int {
309 // Get membershipId. Join with membership payment table for additional checks
312 FROM civicrm_membership m
313 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$contributionID}
314 WHERE m.contribution_recur_id = {$contributionRecurID}
316 return CRM_Core_DAO
::singleValueQuery($sql);
320 * Get the recurring contribution object.
322 * @param string $processorID
323 * @param int $contactID
324 * @param int $contributionID
326 * @return \CRM_Core_DAO|\DB_Error|object
327 * @throws \CRM_Core_Exception
329 protected function getContributionRecurObject(string $processorID, int $contactID, int $contributionID) {
330 // joining with contribution table for extra checks
332 SELECT cr.id, cr.contact_id
333 FROM civicrm_contribution_recur cr
334 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
335 WHERE cr.processor_id = '{$processorID}' AND
336 (cr.contact_id = $contactID OR co.id = $contributionID)
338 $contRecur = CRM_Core_DAO
::executeQuery($sql);
339 if (!$contRecur->fetch()) {
340 throw new CRM_Core_Exception('Could not find contributionRecur id');
342 if ($contactID != $contRecur->contact_id
) {
343 $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
]);
344 CRM_Core_Error
::debug_log_message($message);
350 * Get the payment processor id.
354 * @throws \CRM_Core_Exception
355 * @throws \CiviCRM_API3_Exception
357 protected function getPaymentProcessorID(): int {
358 // Attempt to get payment processor ID from URL
359 if (!empty($this->_inputParameters
['processor_id'])) {
360 return (int) $this->_inputParameters
['processor_id'];
362 // This is an unreliable method as there could be more than one instance.
363 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
364 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
365 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
366 // & call completetransaction or call fail? (which may not exist yet).
367 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');
368 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
369 'AuthNet', 'id', 'name'
371 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
373 'options' => ['limit' => 1],
374 'payment_processor_type_id' => $paymentProcessorTypeID,