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 $ids = $objects = $input = [];
44 if ($x_subscription_id) {
45 // Presence of the id means it is approved.
46 $input['component'] = $component;
48 // load post vars in $input
49 $this->getInput($input, $ids);
51 // load post ids in $ids
52 $this->getIDs($ids, $input);
54 // Attempt to get payment processor ID from URL
55 if (!empty($this->_inputParameters
['processor_id'])) {
56 $paymentProcessorID = $this->_inputParameters
['processor_id'];
59 // This is an unreliable method as there could be more than one instance.
60 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
61 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
62 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
63 // & call completetransaction or call fail? (which may not exist yet).
64 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');
65 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
66 'AuthNet', 'id', 'name'
68 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
70 'options' => ['limit' => 1],
71 'payment_processor_type_id' => $paymentProcessorTypeID,
76 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
79 if (!empty($ids['paymentProcessor']) && $objects['contributionRecur']->payment_processor_id
!= $ids['paymentProcessor']) {
80 Civi
::log()->warning('Payment Processor does not match the recurring processor id.', ['civi.tag' => 'deprecated']);
83 if ($component == 'contribute' && $ids['contributionRecur']) {
84 // check if first contribution is completed, else complete first contribution
86 if ($objects['contribution']->contribution_status_id
== 1) {
89 return $this->recur($input, $ids, $objects, $first);
98 * @param array $objects
103 public function recur(&$input, &$ids, &$objects, $first) {
104 $this->_isRecurring
= TRUE;
105 $recur = &$objects['contributionRecur'];
106 $paymentProcessorObject = $objects['contribution']->_relatedObjects
['paymentProcessor']['object'];
108 // do a subscription check
109 if ($recur->processor_id
!= $input['subscription_id']) {
110 CRM_Core_Error
::debug_log_message("Unrecognized subscription.");
111 echo "Failure: Unrecognized subscription<p>";
115 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
117 $transaction = new CRM_Core_Transaction();
119 $now = date('YmdHis');
121 //load new contribution object if required.
123 // create a contribution and then get it processed
124 $contribution = new CRM_Contribute_BAO_Contribution();
125 $contribution->contact_id
= $ids['contact'];
126 $contribution->financial_type_id
= $objects['contributionType']->id
;
127 $contribution->contribution_page_id
= $ids['contributionPage'];
128 $contribution->contribution_recur_id
= $ids['contributionRecur'];
129 $contribution->receive_date
= $input['receive_date'];
130 $contribution->currency
= $objects['contribution']->currency
;
131 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
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 $objects['contribution']->invoice_id
= md5(uniqid(rand(), TRUE));
140 $objects['contribution']->total_amount
= $input['amount'];
141 $objects['contribution']->trxn_id
= $input['trxn_id'];
143 $isFirstOrLastRecurringPayment = FALSE;
144 if ($input['response_code'] == 1) {
147 $recur->start_date
= $now;
148 $recur->trxn_id
= $recur->processor_id
;
149 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
151 $statusName = 'In Progress';
152 if (($recur->installments
> 0) &&
153 ($input['subscription_paynum'] >= $recur->installments
)
155 // this is the last payment
156 $statusName = 'Completed';
157 $recur->end_date
= $now;
158 $isFirstOrLastRecurringPayment = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
160 $recur->modified_date
= $now;
161 $recur->contribution_status_id
= array_search($statusName, $contributionStatus);
167 $recur->contribution_status_id
= array_search('Failed', $contributionStatus);
168 $recur->cancel_date
= $now;
171 $message = ts("Subscription payment failed - %1", [1 => htmlspecialchars($input['response_reason_text'])]);
172 CRM_Core_Error
::debug_log_message($message);
174 // the recurring contribution has declined a payment or has failed
175 // so we just fix the recurring contribution and not change any of
176 // the existing contributions
181 // check if contribution is already completed, if so we ignore this ipn
182 if ($objects['contribution']->contribution_status_id
== 1) {
183 $transaction->commit();
184 CRM_Core_Error
::debug_log_message("Returning since contribution has already been handled.");
185 echo "Success: Contribution has already been handled<p>";
189 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
191 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
192 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
193 // from isSentReceipt to an array of which receipts to send.
194 // Note that there is site-by-site opinions on which notifications are good to send.
195 if ($isFirstOrLastRecurringPayment) {
196 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
197 $isFirstOrLastRecurringPayment);
203 * Get the input from passed in fields.
205 * @param array $input
209 * @throws \CRM_Core_Exception
211 public function getInput(&$input, &$ids) {
212 $input['amount'] = $this->retrieve('x_amount', 'String');
213 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
214 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
215 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
216 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
217 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
218 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
219 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
220 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
221 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
223 if ($input['trxn_id']) {
224 $input['is_test'] = 0;
226 // Only assume trxn_id 'should' have been returned for success.
227 // Per CRM-17611 it would also not be passed back for a decline.
228 elseif ($input['response_code'] == 1) {
229 $input['is_test'] = 1;
230 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
233 if (!$this->getBillingID($ids)) {
236 $billingID = $ids['billing'];
238 'first_name' => 'x_first_name',
239 'last_name' => 'x_last_name',
240 "street_address-{$billingID}" => 'x_address',
241 "city-{$billingID}" => 'x_city',
242 "state-{$billingID}" => 'x_state',
243 "postal_code-{$billingID}" => 'x_zip',
244 "country-{$billingID}" => 'x_country',
245 "email-{$billingID}" => 'x_email',
247 foreach ($params as $civiName => $resName) {
248 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
253 * Get ids from input.
256 * @param array $input
258 * @throws \CRM_Core_Exception
260 public function getIDs(&$ids, &$input) {
261 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
262 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
264 // joining with contribution table for extra checks
266 SELECT cr.id, cr.contact_id
267 FROM civicrm_contribution_recur cr
268 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
269 WHERE cr.processor_id = '{$input['subscription_id']}' AND
270 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
272 $contRecur = CRM_Core_DAO
::executeQuery($sql);
274 $ids['contributionRecur'] = $contRecur->id
;
275 if ($ids['contact'] != $contRecur->contact_id
) {
276 $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
]);
277 CRM_Core_Error
::debug_log_message($message);
278 $ids['contact'] = $contRecur->contact_id
;
280 if (!$ids['contributionRecur']) {
281 $message = ts("Could not find contributionRecur id");
282 $log = new CRM_Utils_SystemLogger();
283 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
284 throw new CRM_Core_Exception($message);
287 // get page id based on contribution id
288 $ids['contributionPage'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
289 $ids['contribution'],
290 'contribution_page_id'
293 if ($input['component'] == 'event') {
294 // FIXME: figure out fields for event
297 // Get membershipId. Join with membership payment table for additional checks
300 FROM civicrm_membership m
301 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
302 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
304 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql)) {
305 $ids['membership'] = $membershipId;
308 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
313 * @param string $name
315 * @param string $type
318 * Abort if not present.
319 * @param null $default
322 * @throws CRM_Core_Exception
325 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
326 $value = CRM_Utils_Type
::validate(
327 empty($this->_inputParameters
[$name]) ?
$default : $this->_inputParameters
[$name],
331 if ($abort && $value === NULL) {
332 throw new CRM_Core_Exception("Could not find an entry for $name");