83697bd338fa7f7da2e3aa99bbc420a78e136ae7
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNetIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
18
19 /**
20 * Constructor function.
21 *
22 * @param array $inputData
23 * contents of HTTP REQUEST.
24 *
25 * @throws CRM_Core_Exception
26 */
27 public function __construct($inputData) {
28 $this->setInputParameters($inputData);
29 parent::__construct();
30 }
31
32 /**
33 * @param string $component
34 *
35 * @return bool|void
36 */
37 public function main($component = 'contribute') {
38
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 = [];
43
44 if ($x_subscription_id) {
45 // Presence of the id means it is approved.
46 $input['component'] = $component;
47
48 // load post vars in $input
49 $this->getInput($input, $ids);
50
51 // load post ids in $ids
52 $this->getIDs($ids, $input);
53
54 // Attempt to get payment processor ID from URL
55 if (!empty($this->_inputParameters['processor_id'])) {
56 $paymentProcessorID = $this->_inputParameters['processor_id'];
57 }
58 else {
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'
67 );
68 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', [
69 'is_test' => 0,
70 'options' => ['limit' => 1],
71 'payment_processor_type_id' => $paymentProcessorTypeID,
72 'return' => 'id',
73 ]);
74 }
75
76 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
77 return FALSE;
78 }
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']);
81 }
82
83 if ($component == 'contribute' && $ids['contributionRecur']) {
84 // check if first contribution is completed, else complete first contribution
85 $first = TRUE;
86 if ($objects['contribution']->contribution_status_id == 1) {
87 $first = FALSE;
88 }
89 return $this->recur($input, $ids, $objects, $first);
90 }
91 }
92 return TRUE;
93 }
94
95 /**
96 * @param array $input
97 * @param array $ids
98 * @param array $objects
99 * @param $first
100 *
101 * @return bool
102 */
103 public function recur($input, $ids, $objects, $first) {
104 $this->_isRecurring = TRUE;
105 $recur = &$objects['contributionRecur'];
106 $paymentProcessorObject = $objects['contribution']->_relatedObjects['paymentProcessor']['object'];
107
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>';
112 return FALSE;
113 }
114
115 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
116
117 $now = date('YmdHis');
118
119 //load new contribution object if required.
120 if (!$first) {
121 // create a contribution and then get it processed
122 $contribution = new CRM_Contribute_BAO_Contribution();
123 $contribution->contact_id = $ids['contact'];
124 $contribution->financial_type_id = $objects['contributionType']->id;
125 $contribution->contribution_page_id = $ids['contributionPage'];
126 $contribution->contribution_recur_id = $ids['contributionRecur'];
127 $contribution->receive_date = $input['receive_date'];
128 $contribution->currency = $objects['contribution']->currency;
129 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
130 $contribution->amount_level = $objects['contribution']->amount_level;
131 $contribution->address_id = $objects['contribution']->address_id;
132 $contribution->campaign_id = $objects['contribution']->campaign_id;
133 $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
134
135 $objects['contribution'] = &$contribution;
136 }
137 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
138 $objects['contribution']->total_amount = $input['amount'];
139 $objects['contribution']->trxn_id = $input['trxn_id'];
140
141 $isFirstOrLastRecurringPayment = FALSE;
142 if ($input['response_code'] == 1) {
143 // Approved
144 if ($first) {
145 $recur->start_date = $now;
146 $recur->trxn_id = $recur->processor_id;
147 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
148 }
149
150 if (($recur->installments > 0) &&
151 ($input['subscription_paynum'] >= $recur->installments)
152 ) {
153 // this is the last payment
154 $recur->end_date = $now;
155 $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
156 // This end date update should occur in ContributionRecur::updateOnNewPayment
157 // testIPNPaymentRecurNoReceipt has test cover.
158 $recur->save();
159 }
160 }
161 else {
162 // Declined
163 // failed status
164 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
165 $recur->cancel_date = $now;
166 $recur->save();
167
168 $message = ts('Subscription payment failed - %1', [1 => htmlspecialchars($input['response_reason_text'])]);
169 CRM_Core_Error::debug_log_message($message);
170
171 // the recurring contribution has declined a payment or has failed
172 // so we just fix the recurring contribution and not change any of
173 // the existing contributions
174 // CRM-9036
175 return TRUE;
176 }
177
178 // check if contribution is already completed, if so we ignore this ipn
179 if ($objects['contribution']->contribution_status_id == 1) {
180 CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
181 echo 'Success: Contribution has already been handled<p>';
182 return TRUE;
183 }
184
185 $this->completeTransaction($input, $ids, $objects);
186
187 // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors
188 // to do this we should make it available via the api, e.g as a parameter, changing the nuance
189 // from isSentReceipt to an array of which receipts to send.
190 // Note that there is site-by-site opinions on which notifications are good to send.
191 if ($isFirstOrLastRecurringPayment) {
192 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
193 $isFirstOrLastRecurringPayment);
194 }
195
196 }
197
198 /**
199 * Get the input from passed in fields.
200 *
201 * @param array $input
202 *
203 * @throws \CRM_Core_Exception
204 */
205 public function getInput(&$input) {
206 $input['amount'] = $this->retrieve('x_amount', 'String');
207 $input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
208 $input['response_code'] = $this->retrieve('x_response_code', 'Integer');
209 $input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
210 $input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
211 $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
212 $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
213 $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
214 $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now')));
215
216 if ($input['trxn_id']) {
217 $input['is_test'] = 0;
218 }
219 // Only assume trxn_id 'should' have been returned for success.
220 // Per CRM-17611 it would also not be passed back for a decline.
221 elseif ($input['response_code'] == 1) {
222 $input['is_test'] = 1;
223 $input['trxn_id'] = md5(uniqid(rand(), TRUE));
224 }
225
226 $billingID = CRM_Core_BAO_LocationType::getBilling();
227 $params = [
228 'first_name' => 'x_first_name',
229 'last_name' => 'x_last_name',
230 "street_address-{$billingID}" => 'x_address',
231 "city-{$billingID}" => 'x_city',
232 "state-{$billingID}" => 'x_state',
233 "postal_code-{$billingID}" => 'x_zip',
234 "country-{$billingID}" => 'x_country',
235 "email-{$billingID}" => 'x_email',
236 ];
237 foreach ($params as $civiName => $resName) {
238 $input[$civiName] = $this->retrieve($resName, 'String', FALSE);
239 }
240 }
241
242 /**
243 * Get ids from input.
244 *
245 * @param array $ids
246 * @param array $input
247 *
248 * @throws \CRM_Core_Exception
249 */
250 public function getIDs(&$ids, &$input) {
251 $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
252 $ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
253
254 // joining with contribution table for extra checks
255 $sql = "
256 SELECT cr.id, cr.contact_id
257 FROM civicrm_contribution_recur cr
258 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
259 WHERE cr.processor_id = '{$input['subscription_id']}' AND
260 (cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
261 LIMIT 1";
262 $contRecur = CRM_Core_DAO::executeQuery($sql);
263 $contRecur->fetch();
264 $ids['contributionRecur'] = $contRecur->id;
265 if ($ids['contact'] != $contRecur->contact_id) {
266 $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]);
267 CRM_Core_Error::debug_log_message($message);
268 $ids['contact'] = $contRecur->contact_id;
269 }
270 if (!$ids['contributionRecur']) {
271 $message = ts("Could not find contributionRecur id");
272 $log = new CRM_Utils_SystemLogger();
273 $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
274 throw new CRM_Core_Exception($message);
275 }
276
277 // get page id based on contribution id
278 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
279 $ids['contribution'],
280 'contribution_page_id'
281 );
282
283 if ($input['component'] == 'event') {
284 // FIXME: figure out fields for event
285 }
286 else {
287 // Get membershipId. Join with membership payment table for additional checks
288 $sql = "
289 SELECT m.id
290 FROM civicrm_membership m
291 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
292 WHERE m.contribution_recur_id = {$ids['contributionRecur']}
293 LIMIT 1";
294 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
295 $ids['membership'] = $membershipId;
296 }
297
298 // FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
299 }
300 }
301
302 /**
303 * @param string $name
304 * Parameter name.
305 * @param string $type
306 * Parameter type.
307 * @param bool $abort
308 * Abort if not present.
309 * @param null $default
310 * Default value.
311 *
312 * @throws CRM_Core_Exception
313 * @return mixed
314 */
315 public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
316 $value = CRM_Utils_Type::validate(
317 empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
318 $type,
319 FALSE
320 );
321 if ($abort && $value === NULL) {
322 throw new CRM_Core_Exception("Could not find an entry for $name");
323 }
324 return $value;
325 }
326
327 }