Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | * Copyright (C) 2007 | |
4 | * Licensed to CiviCRM under the Academic Free License version 3.0. | |
5 | * | |
6 | * Written and contributed by Ideal Solution, LLC (http://www.idealso.com) | |
7 | * | |
8 | */ | |
9 | ||
10 | /** | |
11 | * | |
12 | * @package CRM | |
13 | * @author Marshal Newrock <marshal@idealso.com> | |
14 | */ | |
15 | ||
c866eb5f TO |
16 | /** |
17 | * NOTE: | |
6a488035 TO |
18 | * When looking up response codes in the Authorize.Net API, they |
19 | * begin at one, so always delete one from the "Position in Response" | |
20 | */ | |
21 | class CRM_Core_Payment_AuthorizeNet extends CRM_Core_Payment { | |
7da04cde TO |
22 | const CHARSET = 'iso-8859-1'; |
23 | const AUTH_APPROVED = 1; | |
24 | const AUTH_DECLINED = 2; | |
25 | const AUTH_ERROR = 3; | |
16106615 | 26 | const AUTH_REVIEW = 4; |
7da04cde | 27 | const TIMEZONE = 'America/Denver'; |
6a488035 TO |
28 | |
29 | protected $_mode = NULL; | |
30 | ||
be2fb01f | 31 | protected $_params = []; |
6a488035 TO |
32 | |
33 | /** | |
34 | * We only need one instance of this object. So we use the singleton | |
35 | * pattern and cache the instance in this variable | |
36 | * | |
37 | * @var object | |
6a488035 TO |
38 | */ |
39 | static private $_singleton = NULL; | |
40 | ||
41 | /** | |
fe482240 | 42 | * Constructor. |
6a488035 | 43 | * |
6a0b768e TO |
44 | * @param string $mode |
45 | * The mode of operation: live or test. | |
6a488035 | 46 | * |
77b97be7 EM |
47 | * @param $paymentProcessor |
48 | * | |
49 | * @return \CRM_Core_Payment_AuthorizeNet | |
6a488035 | 50 | */ |
00be9182 | 51 | public function __construct($mode, &$paymentProcessor) { |
6a488035 TO |
52 | $this->_mode = $mode; |
53 | $this->_paymentProcessor = $paymentProcessor; | |
54 | $this->_processorName = ts('Authorize.net'); | |
55 | ||
6a488035 TO |
56 | $this->_setParam('apiLogin', $paymentProcessor['user_name']); |
57 | $this->_setParam('paymentKey', $paymentProcessor['password']); | |
58 | $this->_setParam('paymentType', 'AIM'); | |
83e84b04 | 59 | $this->_setParam('md5Hash', CRM_Utils_Array::value('signature', $paymentProcessor)); |
6a488035 | 60 | |
6a488035 TO |
61 | $this->_setParam('timestamp', time()); |
62 | srand(time()); | |
63 | $this->_setParam('sequence', rand(1, 1000)); | |
64 | } | |
65 | ||
fbcb6fba | 66 | /** |
d09edf64 | 67 | * Should the first payment date be configurable when setting up back office recurring payments. |
fbcb6fba EM |
68 | * In the case of Authorize.net this is an option |
69 | * @return bool | |
70 | */ | |
d8ce0d68 | 71 | protected function supportsFutureRecurStartDate() { |
fbcb6fba EM |
72 | return TRUE; |
73 | } | |
74 | ||
677fe56c EM |
75 | /** |
76 | * Can recurring contributions be set against pledges. | |
77 | * | |
78 | * In practice all processors that use the baseIPN function to finish transactions or | |
79 | * call the completetransaction api support this by looking up previous contributions in the | |
80 | * series and, if there is a prior contribution against a pledge, and the pledge is not complete, | |
81 | * adding the new payment to the pledge. | |
82 | * | |
83 | * However, only enabling for processors it has been tested against. | |
84 | * | |
85 | * @return bool | |
86 | */ | |
87 | protected function supportsRecurContributionsForPledges() { | |
88 | return TRUE; | |
89 | } | |
90 | ||
6a488035 | 91 | /** |
fe482240 | 92 | * Submit a payment using Advanced Integration Method. |
6a488035 | 93 | * |
6a0b768e TO |
94 | * @param array $params |
95 | * Assoc array of input parameters for this transaction. | |
6a488035 | 96 | * |
a6c01b45 CW |
97 | * @return array |
98 | * the result in a nice formatted array (or an error object) | |
6a488035 | 99 | */ |
00be9182 | 100 | public function doDirectPayment(&$params) { |
6a488035 TO |
101 | if (!defined('CURLOPT_SSLCERT')) { |
102 | return self::error(9001, 'Authorize.Net requires curl with SSL support'); | |
103 | } | |
104 | ||
105 | /* | |
b44e3f84 | 106 | * recurpayment function does not compile an array & then process it - |
6a488035 TO |
107 | * - the tpl does the transformation so adding call to hook here |
108 | * & giving it a change to act on the params array | |
109 | */ | |
110 | $newParams = $params; | |
cd125a40 | 111 | if (!empty($params['is_recur']) && !empty($params['contributionRecurID'])) { |
6a488035 TO |
112 | CRM_Utils_Hook::alterPaymentProcessorParams($this, |
113 | $params, | |
114 | $newParams | |
115 | ); | |
116 | } | |
117 | foreach ($newParams as $field => $value) { | |
118 | $this->_setParam($field, $value); | |
119 | } | |
120 | ||
cd125a40 | 121 | if (!empty($params['is_recur']) && !empty($params['contributionRecurID'])) { |
6a488035 TO |
122 | $result = $this->doRecurPayment(); |
123 | if (is_a($result, 'CRM_Core_Error')) { | |
124 | return $result; | |
125 | } | |
126 | return $params; | |
127 | } | |
128 | ||
be2fb01f | 129 | $postFields = []; |
6a488035 TO |
130 | $authorizeNetFields = $this->_getAuthorizeNetFields(); |
131 | ||
132 | // Set up our call for hook_civicrm_paymentProcessor, | |
133 | // since we now have our parameters as assigned for the AIM back end. | |
134 | CRM_Utils_Hook::alterPaymentProcessorParams($this, | |
135 | $params, | |
136 | $authorizeNetFields | |
137 | ); | |
138 | ||
139 | foreach ($authorizeNetFields as $field => $value) { | |
140 | // CRM-7419, since double quote is used as enclosure while doing csv parsing | |
141 | $value = ($field == 'x_description') ? str_replace('"', "'", $value) : $value; | |
142 | $postFields[] = $field . '=' . urlencode($value); | |
143 | } | |
144 | ||
145 | // Authorize.Net will not refuse duplicates, so we should check if the user already submitted this transaction | |
d253aeb8 | 146 | if ($this->checkDupe($authorizeNetFields['x_invoice_num'], CRM_Utils_Array::value('contributionID', $params))) { |
6a488035 TO |
147 | return self::error(9004, 'It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. Check your email for a receipt from Authorize.net. If you do not receive a receipt within 2 hours you can try your transaction again. If you continue to have problems please contact the site administrator.'); |
148 | } | |
149 | ||
150 | $submit = curl_init($this->_paymentProcessor['url_site']); | |
151 | ||
152 | if (!$submit) { | |
153 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
154 | } | |
155 | ||
156 | curl_setopt($submit, CURLOPT_POST, TRUE); | |
157 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, TRUE); | |
158 | curl_setopt($submit, CURLOPT_POSTFIELDS, implode('&', $postFields)); | |
aaffa79f | 159 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
160 | |
161 | $response = curl_exec($submit); | |
162 | ||
163 | if (!$response) { | |
164 | return self::error(curl_errno($submit), curl_error($submit)); | |
165 | } | |
166 | ||
167 | curl_close($submit); | |
168 | ||
169 | $response_fields = $this->explode_csv($response); | |
48e3da59 | 170 | |
171 | // fetch available contribution statuses | |
172 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
173 | ||
6a488035 TO |
174 | // check for application errors |
175 | // TODO: | |
176 | // AVS, CVV2, CAVV, and other verification results | |
16106615 | 177 | switch ($response_fields[0]) { |
d167bea8 | 178 | case self::AUTH_REVIEW: |
16106615 | 179 | $params['payment_status_id'] = array_search('Pending', $contributionStatus); |
180 | break; | |
181 | ||
d167bea8 | 182 | case self::AUTH_ERROR: |
16106615 | 183 | $params['payment_status_id'] = array_search('Failed', $contributionStatus); |
d15a29b5 | 184 | $errormsg = $response_fields[2] . ' ' . $response_fields[3]; |
185 | return self::error($response_fields[1], $errormsg); | |
16106615 | 186 | |
d167bea8 | 187 | case self::AUTH_DECLINED: |
16106615 | 188 | $errormsg = $response_fields[2] . ' ' . $response_fields[3]; |
189 | return self::error($response_fields[1], $errormsg); | |
190 | ||
191 | default: | |
192 | // Success | |
193 | ||
194 | // test mode always returns trxn_id = 0 | |
195 | // also live mode in CiviCRM with test mode set in | |
196 | // Authorize.Net return $response_fields[6] = 0 | |
197 | // hence treat that also as test mode transaction | |
198 | // fix for CRM-2566 | |
199 | if (($this->_mode == 'test') || $response_fields[6] == 0) { | |
200 | $query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id RLIKE 'test[0-9]+'"; | |
be2fb01f | 201 | $p = []; |
16106615 | 202 | $trxn_id = strval(CRM_Core_DAO::singleValueQuery($query, $p)); |
203 | $trxn_id = str_replace('test', '', $trxn_id); | |
204 | $trxn_id = intval($trxn_id) + 1; | |
205 | $params['trxn_id'] = sprintf('test%08d', $trxn_id); | |
206 | } | |
207 | else { | |
208 | $params['trxn_id'] = $response_fields[6]; | |
209 | } | |
210 | $params['gross_amount'] = $response_fields[9]; | |
211 | break; | |
6a488035 | 212 | } |
6a488035 TO |
213 | // TODO: include authorization code? |
214 | ||
215 | return $params; | |
216 | } | |
217 | ||
218 | /** | |
fe482240 | 219 | * Submit an Automated Recurring Billing subscription. |
6a488035 | 220 | */ |
00be9182 | 221 | public function doRecurPayment() { |
6a488035 TO |
222 | $template = CRM_Core_Smarty::singleton(); |
223 | ||
224 | $intervalLength = $this->_getParam('frequency_interval'); | |
225 | $intervalUnit = $this->_getParam('frequency_unit'); | |
226 | if ($intervalUnit == 'week') { | |
227 | $intervalLength *= 7; | |
228 | $intervalUnit = 'days'; | |
229 | } | |
230 | elseif ($intervalUnit == 'year') { | |
231 | $intervalLength *= 12; | |
232 | $intervalUnit = 'months'; | |
233 | } | |
234 | elseif ($intervalUnit == 'day') { | |
235 | $intervalUnit = 'days'; | |
236 | } | |
237 | elseif ($intervalUnit == 'month') { | |
238 | $intervalUnit = 'months'; | |
239 | } | |
240 | ||
241 | // interval cannot be less than 7 days or more than 1 year | |
242 | if ($intervalUnit == 'days') { | |
243 | if ($intervalLength < 7) { | |
244 | return self::error(9001, 'Payment interval must be at least one week'); | |
245 | } | |
246 | elseif ($intervalLength > 365) { | |
247 | return self::error(9001, 'Payment interval may not be longer than one year'); | |
248 | } | |
249 | } | |
250 | elseif ($intervalUnit == 'months') { | |
251 | if ($intervalLength < 1) { | |
252 | return self::error(9001, 'Payment interval must be at least one week'); | |
253 | } | |
254 | elseif ($intervalLength > 12) { | |
255 | return self::error(9001, 'Payment interval may not be longer than one year'); | |
256 | } | |
257 | } | |
258 | ||
259 | $template->assign('intervalLength', $intervalLength); | |
260 | $template->assign('intervalUnit', $intervalUnit); | |
261 | ||
262 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
263 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
264 | $template->assign('refId', substr($this->_getParam('invoiceID'), 0, 20)); | |
265 | ||
266 | //for recurring, carry first contribution id | |
267 | $template->assign('invoiceNumber', $this->_getParam('contributionID')); | |
268 | $firstPaymentDate = $this->_getParam('receive_date'); | |
269 | if (!empty($firstPaymentDate)) { | |
270 | //allow for post dated payment if set in form | |
271 | $startDate = date_create($firstPaymentDate); | |
272 | } | |
273 | else { | |
274 | $startDate = date_create(); | |
275 | } | |
276 | /* Format start date in Mountain Time to avoid Authorize.net error E00017 | |
277 | * we do this only if the day we are setting our start time to is LESS than the current | |
278 | * day in mountaintime (ie. the server time of the A-net server). A.net won't accept a date | |
279 | * earlier than the current date on it's server so if we are in PST we might need to use mountain | |
280 | * time to bring our date forward. But if we are submitting something future dated we want | |
281 | * the date we entered to be respected | |
282 | */ | |
283 | $minDate = date_create('now', new DateTimeZone(self::TIMEZONE)); | |
9b873358 | 284 | if (strtotime($startDate->format('Y-m-d')) < strtotime($minDate->format('Y-m-d'))) { |
6a488035 TO |
285 | $startDate->setTimezone(new DateTimeZone(self::TIMEZONE)); |
286 | } | |
287 | ||
481a74f4 | 288 | $template->assign('startDate', $startDate->format('Y-m-d')); |
a2dd09cc | 289 | |
6a488035 | 290 | $installments = $this->_getParam('installments'); |
a2dd09cc DL |
291 | |
292 | // for open ended subscription totalOccurrences has to be 9999 | |
293 | $installments = empty($installments) ? 9999 : $installments; | |
294 | $template->assign('totalOccurrences', $installments); | |
6a488035 TO |
295 | |
296 | $template->assign('amount', $this->_getParam('amount')); | |
297 | ||
298 | $template->assign('cardNumber', $this->_getParam('credit_card_number')); | |
299 | $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT); | |
300 | $exp_year = $this->_getParam('year'); | |
301 | $template->assign('expirationDate', $exp_year . '-' . $exp_month); | |
302 | ||
303 | // name rather than description is used in the tpl - see http://www.authorize.net/support/ARB_guide.pdf | |
304 | $template->assign('name', $this->_getParam('description', TRUE)); | |
305 | ||
306 | $template->assign('email', $this->_getParam('email')); | |
307 | $template->assign('contactID', $this->_getParam('contactID')); | |
308 | $template->assign('billingFirstName', $this->_getParam('billing_first_name')); | |
309 | $template->assign('billingLastName', $this->_getParam('billing_last_name')); | |
310 | $template->assign('billingAddress', $this->_getParam('street_address', TRUE)); | |
311 | $template->assign('billingCity', $this->_getParam('city', TRUE)); | |
312 | $template->assign('billingState', $this->_getParam('state_province')); | |
313 | $template->assign('billingZip', $this->_getParam('postal_code', TRUE)); | |
314 | $template->assign('billingCountry', $this->_getParam('country')); | |
315 | ||
316 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
317 | // submit to authorize.net | |
318 | ||
319 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
320 | if (!$submit) { | |
321 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
322 | } | |
323 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
be2fb01f | 324 | curl_setopt($submit, CURLOPT_HTTPHEADER, ["Content-Type: text/xml"]); |
6a488035 TO |
325 | curl_setopt($submit, CURLOPT_HEADER, 1); |
326 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
327 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 328 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
329 | |
330 | $response = curl_exec($submit); | |
331 | ||
332 | if (!$response) { | |
333 | return self::error(curl_errno($submit), curl_error($submit)); | |
334 | } | |
335 | ||
336 | curl_close($submit); | |
337 | $responseFields = $this->_ParseArbReturn($response); | |
338 | ||
339 | if ($responseFields['resultCode'] == 'Error') { | |
340 | return self::error($responseFields['code'], $responseFields['text']); | |
341 | } | |
342 | ||
343 | // update recur processor_id with subscriptionId | |
344 | CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionRecur', $this->_getParam('contributionRecurID'), | |
345 | 'processor_id', $responseFields['subscriptionId'] | |
346 | ); | |
347 | //only impact of assigning this here is is can be used to cancel the subscription in an automated test | |
348 | // if it isn't cancelled a duplicate transaction error occurs | |
a7488080 | 349 | if (!empty($responseFields['subscriptionId'])) { |
6a488035 TO |
350 | $this->_setParam('subscriptionId', $responseFields['subscriptionId']); |
351 | } | |
352 | } | |
353 | ||
6c786a9b EM |
354 | /** |
355 | * @return array | |
356 | */ | |
00be9182 | 357 | public function _getAuthorizeNetFields() { |
518fa0ee SL |
358 | //Total amount is from the form contribution field |
359 | $amount = $this->_getParam('total_amount'); | |
360 | //CRM-9894 would this ever be the case?? | |
361 | if (empty($amount)) { | |
6a488035 TO |
362 | $amount = $this->_getParam('amount'); |
363 | } | |
be2fb01f | 364 | $fields = []; |
6a488035 TO |
365 | $fields['x_login'] = $this->_getParam('apiLogin'); |
366 | $fields['x_tran_key'] = $this->_getParam('paymentKey'); | |
367 | $fields['x_email_customer'] = $this->_getParam('emailCustomer'); | |
368 | $fields['x_first_name'] = $this->_getParam('billing_first_name'); | |
369 | $fields['x_last_name'] = $this->_getParam('billing_last_name'); | |
370 | $fields['x_address'] = $this->_getParam('street_address'); | |
371 | $fields['x_city'] = $this->_getParam('city'); | |
372 | $fields['x_state'] = $this->_getParam('state_province'); | |
373 | $fields['x_zip'] = $this->_getParam('postal_code'); | |
374 | $fields['x_country'] = $this->_getParam('country'); | |
375 | $fields['x_customer_ip'] = $this->_getParam('ip_address'); | |
376 | $fields['x_email'] = $this->_getParam('email'); | |
5bd23b41 | 377 | $fields['x_invoice_num'] = $this->_getParam('invoiceID'); |
353ffa53 | 378 | $fields['x_amount'] = $amount; |
6a488035 TO |
379 | $fields['x_currency_code'] = $this->_getParam('currencyID'); |
380 | $fields['x_description'] = $this->_getParam('description'); | |
381 | $fields['x_cust_id'] = $this->_getParam('contactID'); | |
382 | if ($this->_getParam('paymentType') == 'AIM') { | |
383 | $fields['x_relay_response'] = 'FALSE'; | |
384 | // request response in CSV format | |
385 | $fields['x_delim_data'] = 'TRUE'; | |
386 | $fields['x_delim_char'] = ','; | |
387 | $fields['x_encap_char'] = '"'; | |
388 | // cc info | |
389 | $fields['x_card_num'] = $this->_getParam('credit_card_number'); | |
390 | $fields['x_card_code'] = $this->_getParam('cvv2'); | |
391 | $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT); | |
392 | $exp_year = $this->_getParam('year'); | |
393 | $fields['x_exp_date'] = "$exp_month/$exp_year"; | |
394 | } | |
395 | ||
396 | if ($this->_mode != 'live') { | |
397 | $fields['x_test_request'] = 'TRUE'; | |
398 | } | |
399 | ||
400 | return $fields; | |
401 | } | |
402 | ||
6a488035 TO |
403 | /** |
404 | * Generate HMAC_MD5 | |
405 | * | |
406 | * @param string $key | |
407 | * @param string $data | |
408 | * | |
a6c01b45 CW |
409 | * @return string |
410 | * the HMAC_MD5 encoding string | |
7c550ca0 | 411 | */ |
00be9182 | 412 | public function hmac($key, $data) { |
6a488035 TO |
413 | if (function_exists('mhash')) { |
414 | // Use PHP mhash extension | |
415 | return (bin2hex(mhash(MHASH_MD5, $data, $key))); | |
416 | } | |
417 | else { | |
418 | // RFC 2104 HMAC implementation for php. | |
419 | // Creates an md5 HMAC. | |
420 | // Eliminates the need to install mhash to compute a HMAC | |
421 | // Hacked by Lance Rushing | |
422 | // byte length for md5 | |
423 | $b = 64; | |
424 | if (strlen($key) > $b) { | |
425 | $key = pack("H*", md5($key)); | |
426 | } | |
353ffa53 TO |
427 | $key = str_pad($key, $b, chr(0x00)); |
428 | $ipad = str_pad('', $b, chr(0x36)); | |
429 | $opad = str_pad('', $b, chr(0x5c)); | |
6a488035 TO |
430 | $k_ipad = $key ^ $ipad; |
431 | $k_opad = $key ^ $opad; | |
432 | return md5($k_opad . pack("H*", md5($k_ipad . $data))); | |
433 | } | |
434 | } | |
435 | ||
6a488035 | 436 | /** |
fe482240 | 437 | * Calculate and return the transaction fingerprint. |
6a488035 | 438 | * |
a6c01b45 CW |
439 | * @return string |
440 | * fingerprint | |
7c550ca0 | 441 | */ |
00be9182 | 442 | public function CalculateFP() { |
353ffa53 TO |
443 | $x_tran_key = $this->_getParam('paymentKey'); |
444 | $loginid = $this->_getParam('apiLogin'); | |
445 | $sequence = $this->_getParam('sequence'); | |
446 | $timestamp = $this->_getParam('timestamp'); | |
447 | $amount = $this->_getParam('amount'); | |
448 | $currency = $this->_getParam('currencyID'); | |
6a488035 TO |
449 | $transaction = "$loginid^$sequence^$timestamp^$amount^$currency"; |
450 | return $this->hmac($x_tran_key, $transaction); | |
451 | } | |
452 | ||
453 | /** | |
454 | * Split a CSV file. Requires , as delimiter and " as enclosure. | |
455 | * Based off notes from http://php.net/fgetcsv | |
456 | * | |
6a0b768e TO |
457 | * @param string $data |
458 | * A single CSV line. | |
6a488035 | 459 | * |
a6c01b45 CW |
460 | * @return array |
461 | * CSV fields | |
6a488035 | 462 | */ |
00be9182 | 463 | public function explode_csv($data) { |
6a488035 TO |
464 | $data = trim($data); |
465 | //make it easier to parse fields with quotes in them | |
466 | $data = str_replace('""', "''", $data); | |
be2fb01f | 467 | $fields = []; |
6a488035 TO |
468 | |
469 | while ($data != '') { | |
be2fb01f | 470 | $matches = []; |
6a488035 TO |
471 | if ($data[0] == '"') { |
472 | // handle quoted fields | |
473 | preg_match('/^"(([^"]|\\")*?)",?(.*)$/', $data, $matches); | |
474 | ||
475 | $fields[] = str_replace("''", '"', $matches[1]); | |
476 | $data = $matches[3]; | |
477 | } | |
478 | else { | |
479 | preg_match('/^([^,]*),?(.*)$/', $data, $matches); | |
480 | ||
481 | $fields[] = $matches[1]; | |
482 | $data = $matches[2]; | |
483 | } | |
484 | } | |
485 | return $fields; | |
486 | } | |
487 | ||
488 | /** | |
fe482240 | 489 | * Extract variables from returned XML. |
6a488035 TO |
490 | * |
491 | * Function is from Authorize.Net sample code, and used | |
492 | * to prevent the requirement of XML functions. | |
493 | * | |
6a0b768e TO |
494 | * @param string $content |
495 | * XML reply from Authorize.Net. | |
6a488035 | 496 | * |
a6c01b45 CW |
497 | * @return array |
498 | * refId, resultCode, code, text, subscriptionId | |
6a488035 | 499 | */ |
00be9182 | 500 | public function _parseArbReturn($content) { |
353ffa53 TO |
501 | $refId = $this->_substring_between($content, '<refId>', '</refId>'); |
502 | $resultCode = $this->_substring_between($content, '<resultCode>', '</resultCode>'); | |
503 | $code = $this->_substring_between($content, '<code>', '</code>'); | |
504 | $text = $this->_substring_between($content, '<text>', '</text>'); | |
6a488035 | 505 | $subscriptionId = $this->_substring_between($content, '<subscriptionId>', '</subscriptionId>'); |
be2fb01f | 506 | return [ |
6a488035 TO |
507 | 'refId' => $refId, |
508 | 'resultCode' => $resultCode, | |
509 | 'code' => $code, | |
510 | 'text' => $text, | |
511 | 'subscriptionId' => $subscriptionId, | |
be2fb01f | 512 | ]; |
6a488035 TO |
513 | } |
514 | ||
515 | /** | |
fe482240 | 516 | * Helper function for _parseArbReturn. |
6a488035 TO |
517 | * |
518 | * Function is from Authorize.Net sample code, and used to avoid using | |
519 | * PHP5 XML functions | |
54957108 | 520 | * |
521 | * @param string $haystack | |
522 | * @param string $start | |
523 | * @param string $end | |
524 | * | |
525 | * @return bool|string | |
6a488035 | 526 | */ |
00be9182 | 527 | public function _substring_between(&$haystack, $start, $end) { |
6a488035 TO |
528 | if (strpos($haystack, $start) === FALSE || strpos($haystack, $end) === FALSE) { |
529 | return FALSE; | |
530 | } | |
531 | else { | |
532 | $start_position = strpos($haystack, $start) + strlen($start); | |
533 | $end_position = strpos($haystack, $end); | |
534 | return substr($haystack, $start_position, $end_position - $start_position); | |
535 | } | |
536 | } | |
537 | ||
538 | /** | |
fe482240 | 539 | * Get the value of a field if set. |
6a488035 | 540 | * |
6a0b768e TO |
541 | * @param string $field |
542 | * The field. | |
6a488035 | 543 | * |
2a6da8d7 | 544 | * @param bool $xmlSafe |
72b3a70c CW |
545 | * @return mixed |
546 | * value of the field, or empty string if the field is | |
16b10e64 | 547 | * not set |
6a488035 | 548 | */ |
00be9182 | 549 | public function _getParam($field, $xmlSafe = FALSE) { |
6a488035 | 550 | $value = CRM_Utils_Array::value($field, $this->_params, ''); |
a2dd09cc | 551 | if ($xmlSafe) { |
be2fb01f | 552 | $value = str_replace(['&', '"', "'", '<', '>'], '', $value); |
a2dd09cc | 553 | } |
6a488035 TO |
554 | return $value; |
555 | } | |
556 | ||
6c786a9b EM |
557 | /** |
558 | * @param null $errorCode | |
559 | * @param null $errorMessage | |
560 | * | |
561 | * @return object | |
562 | */ | |
00be9182 | 563 | public function &error($errorCode = NULL, $errorMessage = NULL) { |
6a488035 TO |
564 | $e = CRM_Core_Error::singleton(); |
565 | if ($errorCode) { | |
be2fb01f | 566 | $e->push($errorCode, 0, [], $errorMessage); |
6a488035 TO |
567 | } |
568 | else { | |
be2fb01f | 569 | $e->push(9001, 0, [], 'Unknown System Error.'); |
6a488035 TO |
570 | } |
571 | return $e; | |
572 | } | |
573 | ||
574 | /** | |
575 | * Set a field to the specified value. Value must be a scalar (int, | |
576 | * float, string, or boolean) | |
577 | * | |
578 | * @param string $field | |
579 | * @param mixed $value | |
580 | * | |
a6c01b45 CW |
581 | * @return bool |
582 | * false if value is not a scalar, true if successful | |
6a488035 | 583 | */ |
00be9182 | 584 | public function _setParam($field, $value) { |
6a488035 TO |
585 | if (!is_scalar($value)) { |
586 | return FALSE; | |
587 | } | |
588 | else { | |
589 | $this->_params[$field] = $value; | |
590 | } | |
591 | } | |
592 | ||
593 | /** | |
fe482240 | 594 | * This function checks to see if we have the right config values. |
6a488035 | 595 | * |
a6c01b45 CW |
596 | * @return string |
597 | * the error message if any | |
6a488035 | 598 | */ |
00be9182 | 599 | public function checkConfig() { |
be2fb01f | 600 | $error = []; |
6a488035 TO |
601 | if (empty($this->_paymentProcessor['user_name'])) { |
602 | $error[] = ts('APILogin is not set for this payment processor'); | |
603 | } | |
604 | ||
605 | if (empty($this->_paymentProcessor['password'])) { | |
606 | $error[] = ts('Key is not set for this payment processor'); | |
607 | } | |
608 | ||
609 | if (!empty($error)) { | |
610 | return implode('<p>', $error); | |
611 | } | |
612 | else { | |
613 | return NULL; | |
614 | } | |
615 | } | |
616 | ||
6c786a9b EM |
617 | /** |
618 | * @return string | |
619 | */ | |
00be9182 | 620 | public function accountLoginURL() { |
6a488035 TO |
621 | return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net'; |
622 | } | |
623 | ||
6c786a9b EM |
624 | /** |
625 | * @param string $message | |
626 | * @param array $params | |
627 | * | |
628 | * @return bool|object | |
629 | */ | |
be2fb01f | 630 | public function cancelSubscription(&$message = '', $params = []) { |
6a488035 TO |
631 | $template = CRM_Core_Smarty::singleton(); |
632 | ||
633 | $template->assign('subscriptionType', 'cancel'); | |
634 | ||
635 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
636 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
637 | $template->assign('subscriptionId', CRM_Utils_Array::value('subscriptionId', $params)); | |
638 | ||
639 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
640 | ||
641 | // submit to authorize.net | |
642 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
643 | if (!$submit) { | |
644 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
645 | } | |
646 | ||
647 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
be2fb01f | 648 | curl_setopt($submit, CURLOPT_HTTPHEADER, ["Content-Type: text/xml"]); |
6a488035 TO |
649 | curl_setopt($submit, CURLOPT_HEADER, 1); |
650 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
651 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 652 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
653 | |
654 | $response = curl_exec($submit); | |
655 | ||
656 | if (!$response) { | |
657 | return self::error(curl_errno($submit), curl_error($submit)); | |
658 | } | |
659 | ||
660 | curl_close($submit); | |
661 | ||
662 | $responseFields = $this->_ParseArbReturn($response); | |
663 | $message = "{$responseFields['code']}: {$responseFields['text']}"; | |
664 | ||
665 | if ($responseFields['resultCode'] == 'Error') { | |
666 | return self::error($responseFields['code'], $responseFields['text']); | |
667 | } | |
668 | return TRUE; | |
669 | } | |
670 | ||
6c786a9b EM |
671 | /** |
672 | * @param string $message | |
673 | * @param array $params | |
674 | * | |
675 | * @return bool|object | |
676 | */ | |
be2fb01f | 677 | public function updateSubscriptionBillingInfo(&$message = '', $params = []) { |
6a488035 TO |
678 | $template = CRM_Core_Smarty::singleton(); |
679 | $template->assign('subscriptionType', 'updateBilling'); | |
680 | ||
681 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
682 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
683 | $template->assign('subscriptionId', $params['subscriptionId']); | |
684 | ||
685 | $template->assign('cardNumber', $params['credit_card_number']); | |
686 | $exp_month = str_pad($params['month'], 2, '0', STR_PAD_LEFT); | |
687 | $exp_year = $params['year']; | |
688 | $template->assign('expirationDate', $exp_year . '-' . $exp_month); | |
689 | ||
690 | $template->assign('billingFirstName', $params['first_name']); | |
691 | $template->assign('billingLastName', $params['last_name']); | |
692 | $template->assign('billingAddress', $params['street_address']); | |
693 | $template->assign('billingCity', $params['city']); | |
694 | $template->assign('billingState', $params['state_province']); | |
695 | $template->assign('billingZip', $params['postal_code']); | |
696 | $template->assign('billingCountry', $params['country']); | |
697 | ||
698 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
699 | ||
700 | // submit to authorize.net | |
701 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
702 | if (!$submit) { | |
703 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
704 | } | |
705 | ||
706 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
be2fb01f | 707 | curl_setopt($submit, CURLOPT_HTTPHEADER, ["Content-Type: text/xml"]); |
6a488035 TO |
708 | curl_setopt($submit, CURLOPT_HEADER, 1); |
709 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
710 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 711 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
712 | |
713 | $response = curl_exec($submit); | |
714 | ||
715 | if (!$response) { | |
716 | return self::error(curl_errno($submit), curl_error($submit)); | |
717 | } | |
718 | ||
719 | curl_close($submit); | |
720 | ||
721 | $responseFields = $this->_ParseArbReturn($response); | |
722 | $message = "{$responseFields['code']}: {$responseFields['text']}"; | |
723 | ||
724 | if ($responseFields['resultCode'] == 'Error') { | |
725 | return self::error($responseFields['code'], $responseFields['text']); | |
726 | } | |
727 | return TRUE; | |
728 | } | |
729 | ||
23de1ac0 EM |
730 | /** |
731 | * Process incoming notification. | |
732 | */ | |
518fa0ee | 733 | public static function handlePaymentNotification() { |
23de1ac0 EM |
734 | $ipnClass = new CRM_Core_Payment_AuthorizeNetIPN(array_merge($_GET, $_REQUEST)); |
735 | $ipnClass->main(); | |
736 | } | |
737 | ||
6c786a9b EM |
738 | /** |
739 | * @param string $message | |
740 | * @param array $params | |
741 | * | |
742 | * @return bool|object | |
743 | */ | |
be2fb01f | 744 | public function changeSubscriptionAmount(&$message = '', $params = []) { |
6a488035 TO |
745 | $template = CRM_Core_Smarty::singleton(); |
746 | ||
747 | $template->assign('subscriptionType', 'update'); | |
748 | ||
749 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
750 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
751 | ||
752 | $template->assign('subscriptionId', $params['subscriptionId']); | |
702c1203 JM |
753 | |
754 | // for open ended subscription totalOccurrences has to be 9999 | |
755 | $installments = empty($params['installments']) ? 9999 : $params['installments']; | |
756 | $template->assign('totalOccurrences', $installments); | |
757 | ||
6a488035 TO |
758 | $template->assign('amount', $params['amount']); |
759 | ||
760 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
761 | ||
762 | // submit to authorize.net | |
763 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
764 | if (!$submit) { | |
765 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
766 | } | |
767 | ||
768 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
be2fb01f | 769 | curl_setopt($submit, CURLOPT_HTTPHEADER, ["Content-Type: text/xml"]); |
6a488035 TO |
770 | curl_setopt($submit, CURLOPT_HEADER, 1); |
771 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
772 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 773 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
774 | |
775 | $response = curl_exec($submit); | |
776 | ||
777 | if (!$response) { | |
778 | return self::error(curl_errno($submit), curl_error($submit)); | |
779 | } | |
780 | ||
781 | curl_close($submit); | |
782 | ||
6ea16bbf | 783 | $responseFields = $this->_parseArbReturn($response); |
6a488035 TO |
784 | $message = "{$responseFields['code']}: {$responseFields['text']}"; |
785 | ||
786 | if ($responseFields['resultCode'] == 'Error') { | |
787 | return self::error($responseFields['code'], $responseFields['text']); | |
788 | } | |
789 | return TRUE; | |
790 | } | |
96025800 | 791 | |
6a488035 | 792 | } |