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 if (!empty($ids['contributionRecur'])) {
79 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
80 $contributionRecur->id
= $ids['contributionRecur'];
81 if (!$contributionRecur->find(TRUE)) {
82 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
83 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
88 $objects['contact'] = &$contact;
89 $objects['contribution'] = &$contribution;
91 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
93 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id
!= $ids['paymentProcessor']) {
94 Civi
::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
97 if ($component == 'contribute' && $ids['contributionRecur']) {
98 // check if first contribution is completed, else complete first contribution
100 if ($objects['contribution']->contribution_status_id
== 1) {
102 //load new contribution object if required.
103 // create a contribution and then get it processed
104 $contribution = new CRM_Contribute_BAO_Contribution();
105 $contribution->contact_id
= $ids['contact'];
106 $contribution->financial_type_id
= $objects['contributionType']->id
;
107 $contribution->contribution_page_id
= $ids['contributionPage'];
108 $contribution->contribution_recur_id
= $ids['contributionRecur'];
109 $contribution->receive_date
= $input['receive_date'];
110 $contribution->currency
= $objects['contribution']->currency
;
111 $contribution->amount_level
= $objects['contribution']->amount_level
;
112 $contribution->address_id
= $objects['contribution']->address_id
;
113 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
114 $contribution->_relatedObjects
= $objects['contribution']->_relatedObjects
;
116 $objects['contribution'] = &$contribution;
118 $input['payment_processor_id'] = $paymentProcessorID;
119 return $this->recur($input, [
120 'related_contact' => $ids['related_contact'] ??
NULL,
121 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
122 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
123 'contact' => $ids['contact'] ??
NULL,
124 'contributionPage' => $ids['contributionPage'] ??
NULL,
125 ], $objects['contributionRecur'], $objects['contribution'], $first);
130 catch (CRM_Core_Exception
$e) {
131 Civi
::log()->debug($e->getMessage());
132 echo 'Invalid or missing data';
137 * @param array $input
139 * @param \CRM_Contribute_BAO_ContributionRecur $recur
140 * @param \CRM_Contribute_BAO_Contribution $contribution
144 * @throws \CRM_Core_Exception
145 * @throws \CiviCRM_API3_Exception
147 public function recur($input, $ids, $recur, $contribution, $first) {
149 // do a subscription check
150 if ($recur->processor_id
!= $input['subscription_id']) {
151 throw new CRM_Core_Exception('Unrecognized subscription.');
154 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
156 $now = date('YmdHis');
158 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
159 $contribution->total_amount
= $input['amount'];
160 $contribution->trxn_id
= $input['trxn_id'];
162 $isFirstOrLastRecurringPayment = FALSE;
163 if ($input['response_code'] == 1) {
166 $recur->start_date
= $now;
167 $recur->trxn_id
= $recur->processor_id
;
168 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
171 if (($recur->installments
> 0) &&
172 ($input['subscription_paynum'] >= $recur->installments
)
174 // this is the last payment
175 $recur->end_date
= $now;
176 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
177 // This end date update should occur in ContributionRecur::updateOnNewPayment
178 // testIPNPaymentRecurNoReceipt has test cover.
185 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
186 $recur->cancel_date
= $now;
189 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
190 CRM_Core_Error
::debug_log_message($message);
192 // the recurring contribution has declined a payment or has failed
193 // so we just fix the recurring contribution and not change any of
194 // the existing contributions
199 // check if contribution is already completed, if so we ignore this ipn
200 if ($contribution->contribution_status_id
== 1) {
201 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
202 echo 'Success: Contribution has already been handled<p>';
206 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $contribution);
208 if ($isFirstOrLastRecurringPayment) {
209 //send recurring Notification email for user
210 CRM_Contribute_BAO_ContributionPage
::recurringNotify(TRUE,
212 $ids['contributionPage'],
214 (bool) $this->getMembershipID($contribution->id
, $recur->id
)
220 * Get the input from passed in fields.
222 * @param array $input
224 * @throws \CRM_Core_Exception
226 public function getInput(&$input) {
227 $input['amount'] = $this->retrieve('x_amount', 'String');
228 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
229 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
230 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
231 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
232 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
233 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
234 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
235 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
237 if ($input['trxn_id']) {
238 $input['is_test'] = 0;
240 // Only assume trxn_id 'should' have been returned for success.
241 // Per CRM-17611 it would also not be passed back for a decline.
242 elseif ($input['response_code'] == 1) {
243 $input['is_test'] = 1;
244 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
247 $billingID = CRM_Core_BAO_LocationType
::getBilling();
249 'first_name' => 'x_first_name',
250 'last_name' => 'x_last_name',
251 "street_address-{$billingID}" => 'x_address',
252 "city-{$billingID}" => 'x_city',
253 "state-{$billingID}" => 'x_state',
254 "postal_code-{$billingID}" => 'x_zip',
255 "country-{$billingID}" => 'x_country',
256 "email-{$billingID}" => 'x_email',
258 foreach ($params as $civiName => $resName) {
259 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
264 * Get ids from input.
267 * @param array $input
269 * @throws \CRM_Core_Exception
271 public function getIDs(&$ids, $input) {
272 $ids['contact'] = (int) $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
273 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
274 $contributionRecur = $this->getContributionRecurObject($input['subscription_id'], $ids['contact'], $ids['contribution']);
275 $ids['contributionRecur'] = (int) $contributionRecur->id
;
276 $ids['contact'] = $contributionRecur->contact_id
;
280 * @param string $name
282 * @param string $type
285 * Abort if not present.
286 * @param null $default
289 * @throws CRM_Core_Exception
292 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
293 $value = CRM_Utils_Type
::validate(
294 empty($this->_inputParameters
[$name]) ?
$default : $this->_inputParameters
[$name],
298 if ($abort && $value === NULL) {
299 throw new CRM_Core_Exception("Could not find an entry for $name");
305 * Get membership id, if any.
307 * @param int $contributionID
308 * @param int $contributionRecurID
312 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?
int {
313 // Get membershipId. Join with membership payment table for additional checks
316 FROM civicrm_membership m
317 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$contributionID}
318 WHERE m.contribution_recur_id = {$contributionRecurID}
320 return CRM_Core_DAO
::singleValueQuery($sql);
324 * Get the recurring contribution object.
326 * @param string $processorID
327 * @param int $contactID
328 * @param int $contributionID
330 * @return \CRM_Core_DAO|\DB_Error|object
331 * @throws \CRM_Core_Exception
333 protected function getContributionRecurObject(string $processorID, int $contactID, int $contributionID) {
334 // joining with contribution table for extra checks
336 SELECT cr.id, cr.contact_id
337 FROM civicrm_contribution_recur cr
338 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
339 WHERE cr.processor_id = '{$processorID}' AND
340 (cr.contact_id = $contactID OR co.id = $contributionID)
342 $contRecur = CRM_Core_DAO
::executeQuery($sql);
343 if (!$contRecur->fetch()) {
344 throw new CRM_Core_Exception('Could not find contributionRecur id');
346 if ($contactID != $contRecur->contact_id
) {
347 $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
]);
348 CRM_Core_Error
::debug_log_message($message);
354 * Get the payment processor id.
358 * @throws \CRM_Core_Exception
359 * @throws \CiviCRM_API3_Exception
361 protected function getPaymentProcessorID(): int {
362 // Attempt to get payment processor ID from URL
363 if (!empty($this->_inputParameters
['processor_id'])) {
364 return (int) $this->_inputParameters
['processor_id'];
366 // This is an unreliable method as there could be more than one instance.
367 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
368 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
369 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
370 // & call completetransaction or call fail? (which may not exist yet).
371 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');
372 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
373 'AuthNet', 'id', 'name'
375 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
377 'options' => ['limit' => 1],
378 'payment_processor_type_id' => $paymentProcessorTypeID,