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);
56 // Attempt to get payment processor ID from URL
57 if (!empty($this->_inputParameters
['processor_id'])) {
58 $paymentProcessorID = $this->_inputParameters
['processor_id'];
61 // This is an unreliable method as there could be more than one instance.
62 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
63 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
64 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
65 // & call completetransaction or call fail? (which may not exist yet).
66 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');
67 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
68 'AuthNet', 'id', 'name'
70 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
72 'options' => ['limit' => 1],
73 'payment_processor_type_id' => $paymentProcessorTypeID,
78 // Check if the contribution exists
79 // make sure contribution exists and is valid
80 $contribution = new CRM_Contribute_BAO_Contribution();
81 $contribution->id
= $ids['contribution'];
82 if (!$contribution->find(TRUE)) {
83 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)]);
85 $ids['contributionPage'] = $contribution->contribution_page_id
;
87 // make sure contact exists and is valid
88 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
89 $contact = new CRM_Contact_BAO_Contact();
90 $contact->id
= $contribution->contact_id
;
92 if ($contact->id
!= $ids['contact']) {
93 // 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
94 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");
95 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
96 $ids['contact'] = $contribution->contact_id
;
99 if (!empty($ids['contributionRecur'])) {
100 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
101 $contributionRecur->id
= $ids['contributionRecur'];
102 if (!$contributionRecur->find(TRUE)) {
103 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
104 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
109 $objects['contact'] = &$contact;
110 $objects['contribution'] = &$contribution;
112 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
114 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id
!= $ids['paymentProcessor']) {
115 Civi
::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
118 if ($component == 'contribute' && $ids['contributionRecur']) {
119 // check if first contribution is completed, else complete first contribution
121 if ($objects['contribution']->contribution_status_id
== 1) {
123 //load new contribution object if required.
124 // create a contribution and then get it processed
125 $contribution = new CRM_Contribute_BAO_Contribution();
126 $contribution->contact_id
= $ids['contact'];
127 $contribution->financial_type_id
= $objects['contributionType']->id
;
128 $contribution->contribution_page_id
= $ids['contributionPage'];
129 $contribution->contribution_recur_id
= $ids['contributionRecur'];
130 $contribution->receive_date
= $input['receive_date'];
131 $contribution->currency
= $objects['contribution']->currency
;
132 $contribution->amount_level
= $objects['contribution']->amount_level
;
133 $contribution->address_id
= $objects['contribution']->address_id
;
134 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
135 $contribution->_relatedObjects
= $objects['contribution']->_relatedObjects
;
137 $objects['contribution'] = &$contribution;
139 $input['payment_processor_id'] = $paymentProcessorID;
140 return $this->recur($input, [
141 'related_contact' => $ids['related_contact'] ??
NULL,
142 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
143 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
144 'contact' => $ids['contact'] ??
NULL,
145 'contributionPage' => $ids['contributionPage'] ??
NULL,
146 ], $objects['contributionRecur'], $objects['contribution'], $first);
151 catch (CRM_Core_Exception
$e) {
152 Civi
::log()->debug($e->getMessage());
153 echo 'Invalid or missing data';
158 * @param array $input
160 * @param \CRM_Contribute_BAO_ContributionRecur $recur
161 * @param \CRM_Contribute_BAO_Contribution $contribution
165 * @throws \CRM_Core_Exception
166 * @throws \CiviCRM_API3_Exception
168 public function recur($input, $ids, $recur, $contribution, $first) {
170 // do a subscription check
171 if ($recur->processor_id
!= $input['subscription_id']) {
172 throw new CRM_Core_Exception('Unrecognized subscription.');
175 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
177 $now = date('YmdHis');
179 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
180 $contribution->total_amount
= $input['amount'];
181 $contribution->trxn_id
= $input['trxn_id'];
183 $isFirstOrLastRecurringPayment = FALSE;
184 if ($input['response_code'] == 1) {
187 $recur->start_date
= $now;
188 $recur->trxn_id
= $recur->processor_id
;
189 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
192 if (($recur->installments
> 0) &&
193 ($input['subscription_paynum'] >= $recur->installments
)
195 // this is the last payment
196 $recur->end_date
= $now;
197 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
198 // This end date update should occur in ContributionRecur::updateOnNewPayment
199 // testIPNPaymentRecurNoReceipt has test cover.
206 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
207 $recur->cancel_date
= $now;
210 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
211 CRM_Core_Error
::debug_log_message($message);
213 // the recurring contribution has declined a payment or has failed
214 // so we just fix the recurring contribution and not change any of
215 // the existing contributions
220 // check if contribution is already completed, if so we ignore this ipn
221 if ($contribution->contribution_status_id
== 1) {
222 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
223 echo 'Success: Contribution has already been handled<p>';
227 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $contribution);
229 if ($isFirstOrLastRecurringPayment) {
230 //send recurring Notification email for user
231 CRM_Contribute_BAO_ContributionPage
::recurringNotify(TRUE,
233 $ids['contributionPage'],
235 (bool) $this->getMembershipID($contribution->id
, $recur->id
)
241 * Get the input from passed in fields.
243 * @param array $input
245 * @throws \CRM_Core_Exception
247 public function getInput(&$input) {
248 $input['amount'] = $this->retrieve('x_amount', 'String');
249 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
250 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
251 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
252 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
253 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
254 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
255 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
256 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
258 if ($input['trxn_id']) {
259 $input['is_test'] = 0;
261 // Only assume trxn_id 'should' have been returned for success.
262 // Per CRM-17611 it would also not be passed back for a decline.
263 elseif ($input['response_code'] == 1) {
264 $input['is_test'] = 1;
265 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
268 $billingID = CRM_Core_BAO_LocationType
::getBilling();
270 'first_name' => 'x_first_name',
271 'last_name' => 'x_last_name',
272 "street_address-{$billingID}" => 'x_address',
273 "city-{$billingID}" => 'x_city',
274 "state-{$billingID}" => 'x_state',
275 "postal_code-{$billingID}" => 'x_zip',
276 "country-{$billingID}" => 'x_country',
277 "email-{$billingID}" => 'x_email',
279 foreach ($params as $civiName => $resName) {
280 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
285 * Get ids from input.
288 * @param array $input
290 * @throws \CRM_Core_Exception
292 public function getIDs(&$ids, &$input) {
293 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
294 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
296 // joining with contribution table for extra checks
298 SELECT cr.id, cr.contact_id
299 FROM civicrm_contribution_recur cr
300 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
301 WHERE cr.processor_id = '{$input['subscription_id']}' AND
302 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
304 $contRecur = CRM_Core_DAO
::executeQuery($sql);
306 $ids['contributionRecur'] = (int) $contRecur->id
;
307 if ($ids['contact'] != $contRecur->contact_id
) {
308 $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
]);
309 CRM_Core_Error
::debug_log_message($message);
310 $ids['contact'] = $contRecur->contact_id
;
312 if (!$ids['contributionRecur']) {
313 $message = ts("Could not find contributionRecur id");
314 $log = new CRM_Utils_SystemLogger();
315 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
316 throw new CRM_Core_Exception($message);
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);