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 $ids = $objects = $input = [];
44 if ($x_subscription_id) {
45 // Presence of the id means it is approved.
46 $input['component'] = $component;
48 // load post vars in $input
49 $this->getInput($input, $ids);
51 // load post ids in $ids
52 $this->getIDs($ids, $input);
54 // Attempt to get payment processor ID from URL
55 if (!empty($this->_inputParameters
['processor_id'])) {
56 $paymentProcessorID = $this->_inputParameters
['processor_id'];
59 // This is an unreliable method as there could be more than one instance.
60 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
61 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
62 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
63 // & call completetransaction or call fail? (which may not exist yet).
64 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');
65 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
66 'AuthNet', 'id', 'name'
68 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
70 'options' => ['limit' => 1],
71 'payment_processor_type_id' => $paymentProcessorTypeID,
76 // Check if the contribution exists
77 // make sure contribution exists and is valid
78 $contribution = new CRM_Contribute_BAO_Contribution();
79 $contribution->id
= $ids['contribution'];
80 if (!$contribution->find(TRUE)) {
81 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 // make sure contact exists and is valid
85 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
86 $contact = new CRM_Contact_BAO_Contact();
87 $contact->id
= $contribution->contact_id
;
89 if ($contact->id
!= $ids['contact']) {
90 // 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
91 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");
92 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
93 $ids['contact'] = $contribution->contact_id
;
96 if (!empty($ids['contributionRecur'])) {
97 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
98 $contributionRecur->id
= $ids['contributionRecur'];
99 if (!$contributionRecur->find(TRUE)) {
100 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
101 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
106 $objects['contact'] = &$contact;
107 $objects['contribution'] = &$contribution;
109 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
110 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
111 // We don't need to worry if about removing contribution page id as it will be set later in
112 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
113 unset($ids['contributionPage']);
116 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
118 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id
!= $ids['paymentProcessor']) {
119 Civi
::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
122 if ($component == 'contribute' && $ids['contributionRecur']) {
123 // check if first contribution is completed, else complete first contribution
125 if ($objects['contribution']->contribution_status_id
== 1) {
127 //load new contribution object if required.
128 // create a contribution and then get it processed
129 $contribution = new CRM_Contribute_BAO_Contribution();
130 $contribution->contact_id
= $ids['contact'];
131 $contribution->financial_type_id
= $objects['contributionType']->id
;
132 $contribution->contribution_page_id
= $ids['contributionPage'];
133 $contribution->contribution_recur_id
= $ids['contributionRecur'];
134 $contribution->receive_date
= $input['receive_date'];
135 $contribution->currency
= $objects['contribution']->currency
;
136 $contribution->amount_level
= $objects['contribution']->amount_level
;
137 $contribution->address_id
= $objects['contribution']->address_id
;
138 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
139 $contribution->_relatedObjects
= $objects['contribution']->_relatedObjects
;
141 $objects['contribution'] = &$contribution;
143 $input['payment_processor_id'] = $paymentProcessorID;
144 return $this->recur($input, [
145 'related_contact' => $ids['related_contact'] ??
NULL,
146 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
147 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
148 'membership' => $ids['membership'] ??
NULL,
149 'contact' => $ids['contact'] ??
NULL,
150 'contributionPage' => $ids['contributionPage'] ??
NULL,
151 ], $objects, $first);
156 catch (CRM_Core_Exception
$e) {
157 Civi
::log()->debug($e->getMessage());
158 echo 'Invalid or missing data';
163 * @param array $input
165 * @param array $objects
169 * @throws \CRM_Core_Exception
170 * @throws \CiviCRM_API3_Exception
172 public function recur($input, $ids, $objects, $first) {
173 $recur = &$objects['contributionRecur'];
175 // do a subscription check
176 if ($recur->processor_id
!= $input['subscription_id']) {
177 throw new CRM_Core_Exception('Unrecognized subscription.');
180 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
182 $now = date('YmdHis');
184 $objects['contribution']->invoice_id
= md5(uniqid(rand(), TRUE));
185 $objects['contribution']->total_amount
= $input['amount'];
186 $objects['contribution']->trxn_id
= $input['trxn_id'];
188 $isFirstOrLastRecurringPayment = FALSE;
189 if ($input['response_code'] == 1) {
192 $recur->start_date
= $now;
193 $recur->trxn_id
= $recur->processor_id
;
194 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
197 if (($recur->installments
> 0) &&
198 ($input['subscription_paynum'] >= $recur->installments
)
200 // this is the last payment
201 $recur->end_date
= $now;
202 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
203 // This end date update should occur in ContributionRecur::updateOnNewPayment
204 // testIPNPaymentRecurNoReceipt has test cover.
211 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
212 $recur->cancel_date
= $now;
215 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
216 CRM_Core_Error
::debug_log_message($message);
218 // the recurring contribution has declined a payment or has failed
219 // so we just fix the recurring contribution and not change any of
220 // the existing contributions
225 // check if contribution is already completed, if so we ignore this ipn
226 if ($objects['contribution']->contribution_status_id
== 1) {
227 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
228 echo 'Success: Contribution has already been handled<p>';
232 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, ['contribution' => $objects['contribution']]);
234 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
235 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
236 // from isSentReceipt to an array of which receipts to send.
237 // Note that there is site-by-site opinions on which notifications are good to send.
238 if ($isFirstOrLastRecurringPayment) {
239 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
240 $isFirstOrLastRecurringPayment);
246 * Get the input from passed in fields.
248 * @param array $input
250 * @throws \CRM_Core_Exception
252 public function getInput(&$input) {
253 $input['amount'] = $this->retrieve('x_amount', 'String');
254 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
255 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
256 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
257 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
258 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
259 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
260 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
261 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
263 if ($input['trxn_id']) {
264 $input['is_test'] = 0;
266 // Only assume trxn_id 'should' have been returned for success.
267 // Per CRM-17611 it would also not be passed back for a decline.
268 elseif ($input['response_code'] == 1) {
269 $input['is_test'] = 1;
270 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
273 $billingID = CRM_Core_BAO_LocationType
::getBilling();
275 'first_name' => 'x_first_name',
276 'last_name' => 'x_last_name',
277 "street_address-{$billingID}" => 'x_address',
278 "city-{$billingID}" => 'x_city',
279 "state-{$billingID}" => 'x_state',
280 "postal_code-{$billingID}" => 'x_zip',
281 "country-{$billingID}" => 'x_country',
282 "email-{$billingID}" => 'x_email',
284 foreach ($params as $civiName => $resName) {
285 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
290 * Get ids from input.
293 * @param array $input
295 * @throws \CRM_Core_Exception
297 public function getIDs(&$ids, &$input) {
298 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
299 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
301 // joining with contribution table for extra checks
303 SELECT cr.id, cr.contact_id
304 FROM civicrm_contribution_recur cr
305 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
306 WHERE cr.processor_id = '{$input['subscription_id']}' AND
307 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
309 $contRecur = CRM_Core_DAO
::executeQuery($sql);
311 $ids['contributionRecur'] = $contRecur->id
;
312 if ($ids['contact'] != $contRecur->contact_id
) {
313 $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
]);
314 CRM_Core_Error
::debug_log_message($message);
315 $ids['contact'] = $contRecur->contact_id
;
317 if (!$ids['contributionRecur']) {
318 $message = ts("Could not find contributionRecur id");
319 $log = new CRM_Utils_SystemLogger();
320 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
321 throw new CRM_Core_Exception($message);
324 // get page id based on contribution id
325 $ids['contributionPage'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
326 $ids['contribution'],
327 'contribution_page_id'
330 if ($input['component'] == 'event') {
331 // FIXME: figure out fields for event
334 // Get membershipId. Join with membership payment table for additional checks
337 FROM civicrm_membership m
338 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
339 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
341 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql)) {
342 $ids['membership'] = $membershipId;
345 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
350 * @param string $name
352 * @param string $type
355 * Abort if not present.
356 * @param null $default
359 * @throws CRM_Core_Exception
362 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
363 $value = CRM_Utils_Type
::validate(
364 empty($this->_inputParameters
[$name]) ?
$default : $this->_inputParameters
[$name],
368 if ($abort && $value === NULL) {
369 throw new CRM_Core_Exception("Could not find an entry for $name");