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)]);
83 $ids['contributionPage'] = $contribution->contribution_page_id
;
85 // make sure contact exists and is valid
86 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
87 $contact = new CRM_Contact_BAO_Contact();
88 $contact->id
= $contribution->contact_id
;
90 if ($contact->id
!= $ids['contact']) {
91 // 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
92 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");
93 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
94 $ids['contact'] = $contribution->contact_id
;
97 if (!empty($ids['contributionRecur'])) {
98 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
99 $contributionRecur->id
= $ids['contributionRecur'];
100 if (!$contributionRecur->find(TRUE)) {
101 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
102 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
107 $objects['contact'] = &$contact;
108 $objects['contribution'] = &$contribution;
110 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
112 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id
!= $ids['paymentProcessor']) {
113 Civi
::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
116 if ($component == 'contribute' && $ids['contributionRecur']) {
117 // check if first contribution is completed, else complete first contribution
119 if ($objects['contribution']->contribution_status_id
== 1) {
121 //load new contribution object if required.
122 // create a contribution and then get it processed
123 $contribution = new CRM_Contribute_BAO_Contribution();
124 $contribution->contact_id
= $ids['contact'];
125 $contribution->financial_type_id
= $objects['contributionType']->id
;
126 $contribution->contribution_page_id
= $ids['contributionPage'];
127 $contribution->contribution_recur_id
= $ids['contributionRecur'];
128 $contribution->receive_date
= $input['receive_date'];
129 $contribution->currency
= $objects['contribution']->currency
;
130 $contribution->amount_level
= $objects['contribution']->amount_level
;
131 $contribution->address_id
= $objects['contribution']->address_id
;
132 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
133 $contribution->_relatedObjects
= $objects['contribution']->_relatedObjects
;
135 $objects['contribution'] = &$contribution;
137 $input['payment_processor_id'] = $paymentProcessorID;
138 return $this->recur($input, [
139 'related_contact' => $ids['related_contact'] ??
NULL,
140 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
141 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
142 'membership' => $ids['membership'] ??
NULL,
143 'contact' => $ids['contact'] ??
NULL,
144 'contributionPage' => $ids['contributionPage'] ??
NULL,
145 ], $objects, $first);
150 catch (CRM_Core_Exception
$e) {
151 Civi
::log()->debug($e->getMessage());
152 echo 'Invalid or missing data';
157 * @param array $input
159 * @param array $objects
163 * @throws \CRM_Core_Exception
164 * @throws \CiviCRM_API3_Exception
166 public function recur($input, $ids, $objects, $first) {
167 $recur = &$objects['contributionRecur'];
169 // do a subscription check
170 if ($recur->processor_id
!= $input['subscription_id']) {
171 throw new CRM_Core_Exception('Unrecognized subscription.');
174 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
176 $now = date('YmdHis');
178 $objects['contribution']->invoice_id
= md5(uniqid(rand(), TRUE));
179 $objects['contribution']->total_amount
= $input['amount'];
180 $objects['contribution']->trxn_id
= $input['trxn_id'];
182 $isFirstOrLastRecurringPayment = FALSE;
183 if ($input['response_code'] == 1) {
186 $recur->start_date
= $now;
187 $recur->trxn_id
= $recur->processor_id
;
188 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
191 if (($recur->installments
> 0) &&
192 ($input['subscription_paynum'] >= $recur->installments
)
194 // this is the last payment
195 $recur->end_date
= $now;
196 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
197 // This end date update should occur in ContributionRecur::updateOnNewPayment
198 // testIPNPaymentRecurNoReceipt has test cover.
205 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
206 $recur->cancel_date
= $now;
209 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
210 CRM_Core_Error
::debug_log_message($message);
212 // the recurring contribution has declined a payment or has failed
213 // so we just fix the recurring contribution and not change any of
214 // the existing contributions
219 // check if contribution is already completed, if so we ignore this ipn
220 if ($objects['contribution']->contribution_status_id
== 1) {
221 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
222 echo 'Success: Contribution has already been handled<p>';
226 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects['contribution']);
228 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
229 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
230 // from isSentReceipt to an array of which receipts to send.
231 // Note that there is site-by-site opinions on which notifications are good to send.
232 if ($isFirstOrLastRecurringPayment) {
233 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
234 $isFirstOrLastRecurringPayment);
240 * Get the input from passed in fields.
242 * @param array $input
244 * @throws \CRM_Core_Exception
246 public function getInput(&$input) {
247 $input['amount'] = $this->retrieve('x_amount', 'String');
248 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
249 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
250 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
251 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
252 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
253 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
254 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
255 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
257 if ($input['trxn_id']) {
258 $input['is_test'] = 0;
260 // Only assume trxn_id 'should' have been returned for success.
261 // Per CRM-17611 it would also not be passed back for a decline.
262 elseif ($input['response_code'] == 1) {
263 $input['is_test'] = 1;
264 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
267 $billingID = CRM_Core_BAO_LocationType
::getBilling();
269 'first_name' => 'x_first_name',
270 'last_name' => 'x_last_name',
271 "street_address-{$billingID}" => 'x_address',
272 "city-{$billingID}" => 'x_city',
273 "state-{$billingID}" => 'x_state',
274 "postal_code-{$billingID}" => 'x_zip',
275 "country-{$billingID}" => 'x_country',
276 "email-{$billingID}" => 'x_email',
278 foreach ($params as $civiName => $resName) {
279 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
284 * Get ids from input.
287 * @param array $input
289 * @throws \CRM_Core_Exception
291 public function getIDs(&$ids, &$input) {
292 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
293 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
295 // joining with contribution table for extra checks
297 SELECT cr.id, cr.contact_id
298 FROM civicrm_contribution_recur cr
299 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
300 WHERE cr.processor_id = '{$input['subscription_id']}' AND
301 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
303 $contRecur = CRM_Core_DAO
::executeQuery($sql);
305 $ids['contributionRecur'] = (int) $contRecur->id
;
306 if ($ids['contact'] != $contRecur->contact_id
) {
307 $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
]);
308 CRM_Core_Error
::debug_log_message($message);
309 $ids['contact'] = $contRecur->contact_id
;
311 if (!$ids['contributionRecur']) {
312 $message = ts("Could not find contributionRecur id");
313 $log = new CRM_Utils_SystemLogger();
314 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
315 throw new CRM_Core_Exception($message);
317 $ids['membership'] = $this->getMembershipID($ids['contribution'], $ids['contributionRecur']);
321 * @param string $name
323 * @param string $type
326 * Abort if not present.
327 * @param null $default
330 * @throws CRM_Core_Exception
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],
339 if ($abort && $value === NULL) {
340 throw new CRM_Core_Exception("Could not find an entry for $name");
346 * Get membership id, if any.
348 * @param int $contributionID
349 * @param int $contributionRecurID
353 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?
int {
354 // Get membershipId. Join with membership payment table for additional checks
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}
361 return CRM_Core_DAO
::singleValueQuery($sql);