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 * Main IPN processing function.
37 * @throws \CiviCRM_API3_Exception
39 public function main() {
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.
48 $ids = $objects = $input = [];
50 $input['component'] = 'contribute';
52 // load post vars in $input
53 $this->getInput($input, $ids);
55 // load post ids in $ids
56 $this->getIDs($ids, $input);
57 $paymentProcessorID = $this->getPaymentProcessorID();
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)]);
66 $ids['contributionPage'] = $contribution->contribution_page_id
;
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
;
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
;
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));
86 $objects['contact'] = &$contact;
87 $objects['contribution'] = &$contribution;
89 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
91 // check if first contribution is completed, else complete first contribution
93 if ($objects['contribution']->contribution_status_id
== 1) {
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'];
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);
110 if ($isFirstOrLastRecurringPayment) {
111 //send recurring Notification email for user
112 CRM_Contribute_BAO_ContributionPage
::recurringNotify(TRUE,
114 $ids['contributionPage'],
116 (bool) $this->getMembershipID($contribution->id
, $contributionRecur->id
)
122 catch (CRM_Core_Exception
$e) {
123 Civi
::log()->debug($e->getMessage());
124 echo 'Invalid or missing data';
129 * @param array $input
131 * @param \CRM_Contribute_BAO_ContributionRecur $recur
132 * @param \CRM_Contribute_BAO_Contribution $contribution
136 * @throws \CRM_Core_Exception
137 * @throws \CiviCRM_API3_Exception
139 public function recur($input, $ids, $recur, $contribution, $first) {
141 // do a subscription check
142 if ($recur->processor_id
!= $input['subscription_id']) {
143 throw new CRM_Core_Exception('Unrecognized subscription.');
146 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
148 $now = date('YmdHis');
150 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
151 $contribution->total_amount
= $input['amount'];
152 $contribution->trxn_id
= $input['trxn_id'];
154 $isFirstOrLastRecurringPayment = FALSE;
155 if ($input['response_code'] == 1) {
158 $recur->start_date
= $now;
159 $recur->trxn_id
= $recur->processor_id
;
160 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
163 if (($recur->installments
> 0) &&
164 ($input['subscription_paynum'] >= $recur->installments
)
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.
177 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
178 $recur->cancel_date
= $now;
181 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
182 CRM_Core_Error
::debug_log_message($message);
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
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>';
198 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $contribution);
199 return $isFirstOrLastRecurringPayment;
203 * Get the input from passed in fields.
205 * @param array $input
207 * @throws \CRM_Core_Exception
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')));
220 if ($input['trxn_id']) {
221 $input['is_test'] = 0;
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));
230 $billingID = CRM_Core_BAO_LocationType
::getBilling();
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',
241 foreach ($params as $civiName => $resName) {
242 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
247 * Get ids from input.
250 * @param array $input
252 * @throws \CRM_Core_Exception
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
;
263 * @param string $name
265 * @param string $type
268 * Abort if not present.
269 * @param null $default
272 * @throws CRM_Core_Exception
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],
281 if ($abort && $value === NULL) {
282 throw new CRM_Core_Exception("Could not find an entry for $name");
288 * Get membership id, if any.
290 * @param int $contributionID
291 * @param int $contributionRecurID
295 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?
int {
296 // Get membershipId. Join with membership payment table for additional checks
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}
303 return CRM_Core_DAO
::singleValueQuery($sql);
307 * Get the recurring contribution object.
309 * @param string $processorID
310 * @param int $contactID
311 * @param int $contributionID
313 * @return \CRM_Core_DAO|\DB_Error|object
314 * @throws \CRM_Core_Exception
316 protected function getContributionRecurObject(string $processorID, int $contactID, int $contributionID) {
317 // joining with contribution table for extra checks
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)
325 $contRecur = CRM_Core_DAO
::executeQuery($sql);
326 if (!$contRecur->fetch()) {
327 throw new CRM_Core_Exception('Could not find contributionRecur id');
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);
337 * Get the payment processor id.
341 * @throws \CRM_Core_Exception
342 * @throws \CiviCRM_API3_Exception
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'];
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'
358 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
360 'options' => ['limit' => 1],
361 'payment_processor_type_id' => $paymentProcessorTypeID,