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->retrieve('x_subscription_id', 'String');
47 if (!$x_subscription_id) {
48 // Presence of the id means it is approved.
53 $input['component'] = 'contribute';
55 // load post vars in $input
56 $this->getInput($input);
58 // load post ids in $ids
59 $this->getIDs($ids, $input);
60 $paymentProcessorID = $this->getPaymentProcessorID();
62 // Check if the contribution exists
63 // make sure contribution exists and is valid
64 $contribution = new CRM_Contribute_BAO_Contribution();
65 $contribution->id
= $contributionID = $ids['contribution'];
66 if (!$contribution->find(TRUE)) {
67 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)]);
70 $ids['contributionPage'] = $contribution->contribution_page_id
;
72 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
73 $contributionRecur->id
= $ids['contributionRecur'];
74 if (!$contributionRecur->find(TRUE)) {
75 throw new CRM_Core_Exception("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
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(TRUE,
92 $contributionRecur->contact_id
,
93 $ids['contributionPage'],
95 (bool) $this->getMembershipID($contributionID, $contributionRecur->id
)
101 catch (CRM_Core_Exception
$e) {
102 Civi
::log()->debug($e->getMessage());
103 echo 'Invalid or missing data';
108 * @param array $input
109 * @param \CRM_Contribute_BAO_ContributionRecur $recur
110 * @param \CRM_Contribute_BAO_Contribution $contribution
114 * @throws \CRM_Core_Exception
115 * @throws \CiviCRM_API3_Exception
117 public function recur($input, $recur, $contribution, $first) {
119 // do a subscription check
120 if ($recur->processor_id
!= $input['subscription_id']) {
121 throw new CRM_Core_Exception('Unrecognized subscription.');
124 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
126 $now = date('YmdHis');
128 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
129 $contribution->total_amount
= $input['amount'];
130 $contribution->trxn_id
= $input['trxn_id'];
132 $isFirstOrLastRecurringPayment = FALSE;
133 if ($input['response_code'] == 1) {
136 $recur->start_date
= $now;
137 $recur->trxn_id
= $recur->processor_id
;
138 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
141 if (($recur->installments
> 0) &&
142 ($input['subscription_paynum'] >= $recur->installments
)
144 // this is the last payment
145 $recur->end_date
= $now;
146 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
147 // This end date update should occur in ContributionRecur::updateOnNewPayment
148 // testIPNPaymentRecurNoReceipt has test cover.
155 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
156 $recur->cancel_date
= $now;
159 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
160 CRM_Core_Error
::debug_log_message($message);
162 // the recurring contribution has declined a payment or has failed
163 // so we just fix the recurring contribution and not change any of
164 // the existing contributions
169 // check if contribution is already completed, if so we ignore this ipn
170 if ($contribution->contribution_status_id
== 1) {
171 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
172 echo 'Success: Contribution has already been handled<p>';
176 CRM_Contribute_BAO_Contribution
::completeOrder($input, [
177 'participant' => NULL,
178 'contributionRecur' => $recur->id
,
180 return $isFirstOrLastRecurringPayment;
184 * Get the input from passed in fields.
186 * @param array $input
188 * @throws \CRM_Core_Exception
190 public function getInput(&$input) {
191 $input['amount'] = $this->retrieve('x_amount', 'String');
192 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
193 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
194 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
195 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
196 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
197 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
198 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
199 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
201 if ($input['trxn_id']) {
202 $input['is_test'] = 0;
204 // Only assume trxn_id 'should' have been returned for success.
205 // Per CRM-17611 it would also not be passed back for a decline.
206 elseif ($input['response_code'] == 1) {
207 $input['is_test'] = 1;
208 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
211 $billingID = CRM_Core_BAO_LocationType
::getBilling();
213 'first_name' => 'x_first_name',
214 'last_name' => 'x_last_name',
215 "street_address-{$billingID}" => 'x_address',
216 "city-{$billingID}" => 'x_city',
217 "state-{$billingID}" => 'x_state',
218 "postal_code-{$billingID}" => 'x_zip',
219 "country-{$billingID}" => 'x_country',
220 "email-{$billingID}" => 'x_email',
222 foreach ($params as $civiName => $resName) {
223 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
228 * Get ids from input.
231 * @param array $input
233 * @throws \CRM_Core_Exception
235 public function getIDs(&$ids, $input) {
236 $ids['contribution'] = (int) $this->retrieve('x_invoice_num', 'Integer');
237 $contributionRecur = $this->getContributionRecurObject($input['subscription_id'], (int) $this->retrieve('x_cust_id', 'Integer', FALSE, 0), $ids['contribution']);
238 $ids['contributionRecur'] = (int) $contributionRecur->id
;
242 * @param string $name
244 * @param string $type
247 * Abort if not present.
248 * @param null $default
251 * @throws CRM_Core_Exception
254 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
255 $value = CRM_Utils_Type
::validate(
256 empty($this->_inputParameters
[$name]) ?
$default : $this->_inputParameters
[$name],
260 if ($abort && $value === NULL) {
261 throw new CRM_Core_Exception("Could not find an entry for $name");
267 * Get membership id, if any.
269 * @param int $contributionID
270 * @param int $contributionRecurID
274 protected function getMembershipID(int $contributionID, int $contributionRecurID): ?
int {
275 // Get membershipId. Join with membership payment table for additional checks
278 FROM civicrm_membership m
279 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$contributionID}
280 WHERE m.contribution_recur_id = {$contributionRecurID}
282 return CRM_Core_DAO
::singleValueQuery($sql);
286 * Get the recurring contribution object.
288 * @param string $processorID
289 * @param int $contactID
290 * @param int $contributionID
292 * @return \CRM_Core_DAO|\DB_Error|object
293 * @throws \CRM_Core_Exception
295 protected function getContributionRecurObject(string $processorID, int $contactID, int $contributionID) {
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 = '{$processorID}' AND
302 (cr.contact_id = $contactID OR co.id = $contributionID)
304 $contRecur = CRM_Core_DAO
::executeQuery($sql);
305 if (!$contRecur->fetch()) {
306 throw new CRM_Core_Exception('Could not find contributionRecur id');
308 if ($contactID != $contRecur->contact_id
) {
309 $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
]);
310 CRM_Core_Error
::debug_log_message($message);
316 * Get the payment processor id.
320 * @throws \API_Exception
321 * @throws \CRM_Core_Exception
322 * @throws \CiviCRM_API3_Exception
324 protected function getPaymentProcessorID(): int {
325 // Attempt to get payment processor ID from URL
326 if (!empty($this->_inputParameters
['processor_id']) &&
327 'AuthNet' === PaymentProcessor
::get(FALSE)
328 ->addSelect('payment_processor_type_id:name')
329 ->addWhere('id', '=', $this->_inputParameters
['processor_id'])
330 ->execute()->first()['payment_processor_type_id:name']
332 return (int) $this->_inputParameters
['processor_id'];
334 // This is an unreliable method as there could be more than one instance.
335 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
336 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
337 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
338 // & call completetransaction or call fail? (which may not exist yet).
339 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');
340 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
341 'AuthNet', 'id', 'name'
343 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
345 'options' => ['limit' => 1],
346 'payment_processor_type_id' => $paymentProcessorTypeID,