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 +--------------------------------------------------------------------+
12 use Civi\Api4\PaymentProcessor
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Core_Payment_AuthorizeNetIPN
extends CRM_Core_Payment_BaseIPN
{
22 * Constructor function.
24 * @param array $inputData
25 * contents of HTTP REQUEST.
27 * @throws CRM_Core_Exception
29 public function __construct($inputData) {
30 $this->setInputParameters($inputData);
31 parent
::__construct();
35 * Main IPN processing function.
39 * @throws \CiviCRM_API3_Exception
40 * @throws \API_Exception
42 public function main() {
44 //we only get invoice num as a key player from payment gateway response.
45 //for ARB we get x_subscription_id and x_subscription_paynum
46 $x_subscription_id = $this->getRecurProcessorID();
49 $input['component'] = 'contribute';
51 // load post vars in $input
52 $this->getInput($input);
54 // load post ids in $ids
55 $this->getIDs($ids, $input);
56 $paymentProcessorID = $this->getPaymentProcessorID();
58 // Check if the contribution exists
59 // make sure contribution exists and is valid
60 $contribution = new CRM_Contribute_BAO_Contribution();
61 $contribution->id
= $contributionID = $this->getContributionID();
62 if (!$contribution->find(TRUE)) {
63 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 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
69 $contributionRecur->id
= $ids['contributionRecur'];
70 if (!$contributionRecur->find(TRUE)) {
71 throw new CRM_Core_Exception("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
73 // do a subscription check
74 if ($contributionRecur->processor_id
!= $this->getRecurProcessorID()) {
75 throw new CRM_Core_Exception('Unrecognized subscription.');
78 // check if first contribution is completed, else complete first contribution
80 if ($contribution->contribution_status_id
== 1) {
82 //load new contribution object if required.
83 // create a contribution and then get it processed
84 $contribution = new CRM_Contribute_BAO_Contribution();
86 $input['payment_processor_id'] = $paymentProcessorID;
87 $isFirstOrLastRecurringPayment = $this->recur($input, $contributionRecur, $contribution, $first);
89 if ($isFirstOrLastRecurringPayment) {
90 //send recurring Notification email for user
91 CRM_Contribute_BAO_ContributionPage
::recurringNotify($contributionID, TRUE,
98 catch (CRM_Core_Exception
$e) {
99 Civi
::log()->debug($e->getMessage());
100 echo 'Invalid or missing data';
105 * @param array $input
106 * @param \CRM_Contribute_BAO_ContributionRecur $recur
107 * @param \CRM_Contribute_BAO_Contribution $contribution
111 * @throws \CRM_Core_Exception
112 * @throws \CiviCRM_API3_Exception
114 public function recur($input, $recur, $contribution, $first) {
116 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
118 $now = date('YmdHis');
120 $isFirstOrLastRecurringPayment = FALSE;
121 if ($input['response_code'] == 1) {
124 $recur->start_date
= $now;
125 $recur->trxn_id
= $recur->processor_id
;
126 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
129 if (($recur->installments
> 0) &&
130 ($input['subscription_paynum'] >= $recur->installments
)
132 // this is the last payment
133 $recur->end_date
= $now;
134 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
135 // This end date update should occur in ContributionRecur::updateOnNewPayment
136 // testIPNPaymentRecurNoReceipt has test cover.
143 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
144 $recur->cancel_date
= $now;
147 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
148 CRM_Core_Error
::debug_log_message($message);
150 // the recurring contribution has declined a payment or has failed
151 // so we just fix the recurring contribution and not change any of
152 // the existing contributions
157 CRM_Contribute_BAO_Contribution
::completeOrder($input, $recur->id
, $contribution->id ??
NULL);
158 return $isFirstOrLastRecurringPayment;
162 * Get the input from passed in fields.
164 * @param array $input
166 * @throws \CRM_Core_Exception
168 public function getInput(&$input) {
169 $input['amount'] = $this->retrieve('x_amount', 'String');
170 $input['subscription_id'] = $this->getRecurProcessorID();
171 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
172 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
173 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
174 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
175 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
176 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
178 if ($input['trxn_id']) {
179 $input['is_test'] = 0;
181 // Only assume trxn_id 'should' have been returned for success.
182 // Per CRM-17611 it would also not be passed back for a decline.
183 elseif ($input['response_code'] == 1) {
184 $input['is_test'] = 1;
185 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
188 $billingID = CRM_Core_BAO_LocationType
::getBilling();
190 'first_name' => 'x_first_name',
191 'last_name' => 'x_last_name',
192 "street_address-{$billingID}" => 'x_address',
193 "city-{$billingID}" => 'x_city',
194 "state-{$billingID}" => 'x_state',
195 "postal_code-{$billingID}" => 'x_zip',
196 "country-{$billingID}" => 'x_country',
197 "email-{$billingID}" => 'x_email',
199 foreach ($params as $civiName => $resName) {
200 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
205 * Get ids from input.
208 * @param array $input
210 * @throws \CRM_Core_Exception
212 public function getIDs(&$ids, $input) {
213 $ids['contribution'] = $this->getContributionID();
214 $contributionRecur = $this->getContributionRecurObject($this->getRecurProcessorID(), (int) $this->retrieve('x_cust_id', 'Integer', FALSE, 0), $this->getContributionID());
215 $ids['contributionRecur'] = (int) $contributionRecur->id
;
219 * @param string $name
221 * @param string $type
224 * Abort if not present.
225 * @param null $default
228 * @throws CRM_Core_Exception
231 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
232 $value = CRM_Utils_Type
::validate(
233 empty($this->_inputParameters
[$name]) ?
$default : $this->_inputParameters
[$name],
237 if ($abort && $value === NULL) {
238 throw new CRM_Core_Exception("Could not find an entry for $name");
244 * Get membership id, if any.
246 * @param int $contributionID
247 * @param int $contributionRecurID
251 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?
int {
252 // Get membershipId. Join with membership payment table for additional checks
255 FROM civicrm_membership m
256 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$contributionID}
257 WHERE m.contribution_recur_id = {$contributionRecurID}
259 return CRM_Core_DAO
::singleValueQuery($sql);
263 * Get the recurring contribution object.
265 * @param string $processorID
266 * @param int $contactID
267 * @param int $contributionID
269 * @return \CRM_Core_DAO|\DB_Error|object
270 * @throws \CRM_Core_Exception
272 protected function getContributionRecurObject(string $processorID, int $contactID, int $contributionID) {
273 // joining with contribution table for extra checks
275 SELECT cr.id, cr.contact_id
276 FROM civicrm_contribution_recur cr
277 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
278 WHERE cr.processor_id = '{$processorID}' AND
279 (cr.contact_id = $contactID OR co.id = $contributionID)
281 $contRecur = CRM_Core_DAO
::executeQuery($sql);
282 if (!$contRecur->fetch()) {
283 throw new CRM_Core_Exception('Could not find contributionRecur id');
285 if ($contactID != $contRecur->contact_id
) {
286 $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", [1 => $contactID, 2 => $contRecur->contact_id
]);
287 CRM_Core_Error
::debug_log_message($message);
293 * Get the payment processor id.
297 * @throws \API_Exception
298 * @throws \CRM_Core_Exception
299 * @throws \CiviCRM_API3_Exception
301 protected function getPaymentProcessorID(): int {
302 // Attempt to get payment processor ID from URL
303 if (!empty($this->_inputParameters
['processor_id']) &&
304 'AuthNet' === PaymentProcessor
::get(FALSE)
305 ->addSelect('payment_processor_type_id:name')
306 ->addWhere('id', '=', $this->_inputParameters
['processor_id'])
307 ->execute()->first()['payment_processor_type_id:name']
309 return (int) $this->_inputParameters
['processor_id'];
311 // This is an unreliable method as there could be more than one instance.
312 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
313 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
314 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
315 // & call completetransaction or call fail? (which may not exist yet).
316 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');
317 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
318 'AuthNet', 'id', 'name'
320 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
322 'options' => ['limit' => 1],
323 'payment_processor_type_id' => $paymentProcessorTypeID,
329 * Get the processor_id for the recurring.
331 * This is the value stored in civicrm_contribution_recur.processor_id,
332 * sometimes called subscription_id.
336 * @throws \CRM_Core_Exception
338 protected function getRecurProcessorID(): string {
339 return $this->retrieve('x_subscription_id', 'String');
343 * Get the contribution ID to be updated.
347 * @throws \CRM_Core_Exception
349 protected function getContributionID(): int {
350 return (int) $this->retrieve('x_invoice_num', 'Integer');