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; | |
26 | const TIMEZONE = 'America/Denver'; | |
6a488035 TO |
27 | |
28 | protected $_mode = NULL; | |
29 | ||
30 | protected $_params = array(); | |
31 | ||
32 | /** | |
33 | * We only need one instance of this object. So we use the singleton | |
34 | * pattern and cache the instance in this variable | |
35 | * | |
36 | * @var object | |
6a488035 TO |
37 | */ |
38 | static private $_singleton = NULL; | |
39 | ||
40 | /** | |
fe482240 | 41 | * Constructor. |
6a488035 | 42 | * |
6a0b768e TO |
43 | * @param string $mode |
44 | * The mode of operation: live or test. | |
6a488035 | 45 | * |
77b97be7 EM |
46 | * @param $paymentProcessor |
47 | * | |
48 | * @return \CRM_Core_Payment_AuthorizeNet | |
6a488035 | 49 | */ |
00be9182 | 50 | public function __construct($mode, &$paymentProcessor) { |
6a488035 TO |
51 | $this->_mode = $mode; |
52 | $this->_paymentProcessor = $paymentProcessor; | |
53 | $this->_processorName = ts('Authorize.net'); | |
54 | ||
6a488035 TO |
55 | $this->_setParam('apiLogin', $paymentProcessor['user_name']); |
56 | $this->_setParam('paymentKey', $paymentProcessor['password']); | |
57 | $this->_setParam('paymentType', 'AIM'); | |
83e84b04 | 58 | $this->_setParam('md5Hash', CRM_Utils_Array::value('signature', $paymentProcessor)); |
6a488035 TO |
59 | |
60 | $this->_setParam('emailCustomer', 'TRUE'); | |
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 | ||
129 | $postFields = array(); | |
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); | |
170 | ||
171 | // check gateway MD5 response | |
172 | if (!$this->checkMD5($response_fields[37], $response_fields[6], $response_fields[9])) { | |
173 | return self::error(9003, 'MD5 Verification failed'); | |
174 | } | |
175 | ||
176 | // check for application errors | |
177 | // TODO: | |
178 | // AVS, CVV2, CAVV, and other verification results | |
179 | if ($response_fields[0] != self::AUTH_APPROVED) { | |
180 | $errormsg = $response_fields[2] . ' ' . $response_fields[3]; | |
181 | return self::error($response_fields[1], $errormsg); | |
182 | } | |
183 | ||
184 | // Success | |
185 | ||
186 | // test mode always returns trxn_id = 0 | |
187 | // also live mode in CiviCRM with test mode set in | |
188 | // Authorize.Net return $response_fields[6] = 0 | |
189 | // hence treat that also as test mode transaction | |
190 | // fix for CRM-2566 | |
191 | if (($this->_mode == 'test') || $response_fields[6] == 0) { | |
353ffa53 TO |
192 | $query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id RLIKE 'test[0-9]+'"; |
193 | $p = array(); | |
194 | $trxn_id = strval(CRM_Core_DAO::singleValueQuery($query, $p)); | |
195 | $trxn_id = str_replace('test', '', $trxn_id); | |
196 | $trxn_id = intval($trxn_id) + 1; | |
6a488035 TO |
197 | $params['trxn_id'] = sprintf('test%08d', $trxn_id); |
198 | } | |
199 | else { | |
200 | $params['trxn_id'] = $response_fields[6]; | |
201 | } | |
202 | $params['gross_amount'] = $response_fields[9]; | |
203 | // TODO: include authorization code? | |
204 | ||
205 | return $params; | |
206 | } | |
207 | ||
208 | /** | |
fe482240 | 209 | * Submit an Automated Recurring Billing subscription. |
6a488035 | 210 | */ |
00be9182 | 211 | public function doRecurPayment() { |
6a488035 TO |
212 | $template = CRM_Core_Smarty::singleton(); |
213 | ||
214 | $intervalLength = $this->_getParam('frequency_interval'); | |
215 | $intervalUnit = $this->_getParam('frequency_unit'); | |
216 | if ($intervalUnit == 'week') { | |
217 | $intervalLength *= 7; | |
218 | $intervalUnit = 'days'; | |
219 | } | |
220 | elseif ($intervalUnit == 'year') { | |
221 | $intervalLength *= 12; | |
222 | $intervalUnit = 'months'; | |
223 | } | |
224 | elseif ($intervalUnit == 'day') { | |
225 | $intervalUnit = 'days'; | |
226 | } | |
227 | elseif ($intervalUnit == 'month') { | |
228 | $intervalUnit = 'months'; | |
229 | } | |
230 | ||
231 | // interval cannot be less than 7 days or more than 1 year | |
232 | if ($intervalUnit == 'days') { | |
233 | if ($intervalLength < 7) { | |
234 | return self::error(9001, 'Payment interval must be at least one week'); | |
235 | } | |
236 | elseif ($intervalLength > 365) { | |
237 | return self::error(9001, 'Payment interval may not be longer than one year'); | |
238 | } | |
239 | } | |
240 | elseif ($intervalUnit == 'months') { | |
241 | if ($intervalLength < 1) { | |
242 | return self::error(9001, 'Payment interval must be at least one week'); | |
243 | } | |
244 | elseif ($intervalLength > 12) { | |
245 | return self::error(9001, 'Payment interval may not be longer than one year'); | |
246 | } | |
247 | } | |
248 | ||
249 | $template->assign('intervalLength', $intervalLength); | |
250 | $template->assign('intervalUnit', $intervalUnit); | |
251 | ||
252 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
253 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
254 | $template->assign('refId', substr($this->_getParam('invoiceID'), 0, 20)); | |
255 | ||
256 | //for recurring, carry first contribution id | |
257 | $template->assign('invoiceNumber', $this->_getParam('contributionID')); | |
258 | $firstPaymentDate = $this->_getParam('receive_date'); | |
259 | if (!empty($firstPaymentDate)) { | |
260 | //allow for post dated payment if set in form | |
261 | $startDate = date_create($firstPaymentDate); | |
262 | } | |
263 | else { | |
264 | $startDate = date_create(); | |
265 | } | |
266 | /* Format start date in Mountain Time to avoid Authorize.net error E00017 | |
267 | * we do this only if the day we are setting our start time to is LESS than the current | |
268 | * day in mountaintime (ie. the server time of the A-net server). A.net won't accept a date | |
269 | * earlier than the current date on it's server so if we are in PST we might need to use mountain | |
270 | * time to bring our date forward. But if we are submitting something future dated we want | |
271 | * the date we entered to be respected | |
272 | */ | |
273 | $minDate = date_create('now', new DateTimeZone(self::TIMEZONE)); | |
9b873358 | 274 | if (strtotime($startDate->format('Y-m-d')) < strtotime($minDate->format('Y-m-d'))) { |
6a488035 TO |
275 | $startDate->setTimezone(new DateTimeZone(self::TIMEZONE)); |
276 | } | |
277 | ||
481a74f4 | 278 | $template->assign('startDate', $startDate->format('Y-m-d')); |
a2dd09cc | 279 | |
6a488035 | 280 | $installments = $this->_getParam('installments'); |
a2dd09cc DL |
281 | |
282 | // for open ended subscription totalOccurrences has to be 9999 | |
283 | $installments = empty($installments) ? 9999 : $installments; | |
284 | $template->assign('totalOccurrences', $installments); | |
6a488035 TO |
285 | |
286 | $template->assign('amount', $this->_getParam('amount')); | |
287 | ||
288 | $template->assign('cardNumber', $this->_getParam('credit_card_number')); | |
289 | $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT); | |
290 | $exp_year = $this->_getParam('year'); | |
291 | $template->assign('expirationDate', $exp_year . '-' . $exp_month); | |
292 | ||
293 | // name rather than description is used in the tpl - see http://www.authorize.net/support/ARB_guide.pdf | |
294 | $template->assign('name', $this->_getParam('description', TRUE)); | |
295 | ||
296 | $template->assign('email', $this->_getParam('email')); | |
297 | $template->assign('contactID', $this->_getParam('contactID')); | |
298 | $template->assign('billingFirstName', $this->_getParam('billing_first_name')); | |
299 | $template->assign('billingLastName', $this->_getParam('billing_last_name')); | |
300 | $template->assign('billingAddress', $this->_getParam('street_address', TRUE)); | |
301 | $template->assign('billingCity', $this->_getParam('city', TRUE)); | |
302 | $template->assign('billingState', $this->_getParam('state_province')); | |
303 | $template->assign('billingZip', $this->_getParam('postal_code', TRUE)); | |
304 | $template->assign('billingCountry', $this->_getParam('country')); | |
305 | ||
306 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
307 | // submit to authorize.net | |
308 | ||
309 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
310 | if (!$submit) { | |
311 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
312 | } | |
313 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
314 | curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); | |
315 | curl_setopt($submit, CURLOPT_HEADER, 1); | |
316 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
317 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 318 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
319 | |
320 | $response = curl_exec($submit); | |
321 | ||
322 | if (!$response) { | |
323 | return self::error(curl_errno($submit), curl_error($submit)); | |
324 | } | |
325 | ||
326 | curl_close($submit); | |
327 | $responseFields = $this->_ParseArbReturn($response); | |
328 | ||
329 | if ($responseFields['resultCode'] == 'Error') { | |
330 | return self::error($responseFields['code'], $responseFields['text']); | |
331 | } | |
332 | ||
333 | // update recur processor_id with subscriptionId | |
334 | CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionRecur', $this->_getParam('contributionRecurID'), | |
335 | 'processor_id', $responseFields['subscriptionId'] | |
336 | ); | |
337 | //only impact of assigning this here is is can be used to cancel the subscription in an automated test | |
338 | // if it isn't cancelled a duplicate transaction error occurs | |
a7488080 | 339 | if (!empty($responseFields['subscriptionId'])) { |
6a488035 TO |
340 | $this->_setParam('subscriptionId', $responseFields['subscriptionId']); |
341 | } | |
342 | } | |
343 | ||
6c786a9b EM |
344 | /** |
345 | * @return array | |
346 | */ | |
00be9182 | 347 | public function _getAuthorizeNetFields() { |
6a488035 | 348 | $amount = $this->_getParam('total_amount');//Total amount is from the form contribution field |
353ffa53 | 349 | if (empty($amount)) {//CRM-9894 would this ever be the case?? |
6a488035 TO |
350 | $amount = $this->_getParam('amount'); |
351 | } | |
352 | $fields = array(); | |
353 | $fields['x_login'] = $this->_getParam('apiLogin'); | |
354 | $fields['x_tran_key'] = $this->_getParam('paymentKey'); | |
355 | $fields['x_email_customer'] = $this->_getParam('emailCustomer'); | |
356 | $fields['x_first_name'] = $this->_getParam('billing_first_name'); | |
357 | $fields['x_last_name'] = $this->_getParam('billing_last_name'); | |
358 | $fields['x_address'] = $this->_getParam('street_address'); | |
359 | $fields['x_city'] = $this->_getParam('city'); | |
360 | $fields['x_state'] = $this->_getParam('state_province'); | |
361 | $fields['x_zip'] = $this->_getParam('postal_code'); | |
362 | $fields['x_country'] = $this->_getParam('country'); | |
363 | $fields['x_customer_ip'] = $this->_getParam('ip_address'); | |
364 | $fields['x_email'] = $this->_getParam('email'); | |
365 | $fields['x_invoice_num'] = substr($this->_getParam('invoiceID'), 0, 20); | |
353ffa53 | 366 | $fields['x_amount'] = $amount; |
6a488035 TO |
367 | $fields['x_currency_code'] = $this->_getParam('currencyID'); |
368 | $fields['x_description'] = $this->_getParam('description'); | |
369 | $fields['x_cust_id'] = $this->_getParam('contactID'); | |
370 | if ($this->_getParam('paymentType') == 'AIM') { | |
371 | $fields['x_relay_response'] = 'FALSE'; | |
372 | // request response in CSV format | |
373 | $fields['x_delim_data'] = 'TRUE'; | |
374 | $fields['x_delim_char'] = ','; | |
375 | $fields['x_encap_char'] = '"'; | |
376 | // cc info | |
377 | $fields['x_card_num'] = $this->_getParam('credit_card_number'); | |
378 | $fields['x_card_code'] = $this->_getParam('cvv2'); | |
379 | $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT); | |
380 | $exp_year = $this->_getParam('year'); | |
381 | $fields['x_exp_date'] = "$exp_month/$exp_year"; | |
382 | } | |
383 | ||
384 | if ($this->_mode != 'live') { | |
385 | $fields['x_test_request'] = 'TRUE'; | |
386 | } | |
387 | ||
388 | return $fields; | |
389 | } | |
390 | ||
6a488035 TO |
391 | /** |
392 | * Generate HMAC_MD5 | |
393 | * | |
394 | * @param string $key | |
395 | * @param string $data | |
396 | * | |
a6c01b45 CW |
397 | * @return string |
398 | * the HMAC_MD5 encoding string | |
7c550ca0 | 399 | */ |
00be9182 | 400 | public function hmac($key, $data) { |
6a488035 TO |
401 | if (function_exists('mhash')) { |
402 | // Use PHP mhash extension | |
403 | return (bin2hex(mhash(MHASH_MD5, $data, $key))); | |
404 | } | |
405 | else { | |
406 | // RFC 2104 HMAC implementation for php. | |
407 | // Creates an md5 HMAC. | |
408 | // Eliminates the need to install mhash to compute a HMAC | |
409 | // Hacked by Lance Rushing | |
410 | // byte length for md5 | |
411 | $b = 64; | |
412 | if (strlen($key) > $b) { | |
413 | $key = pack("H*", md5($key)); | |
414 | } | |
353ffa53 TO |
415 | $key = str_pad($key, $b, chr(0x00)); |
416 | $ipad = str_pad('', $b, chr(0x36)); | |
417 | $opad = str_pad('', $b, chr(0x5c)); | |
6a488035 TO |
418 | $k_ipad = $key ^ $ipad; |
419 | $k_opad = $key ^ $opad; | |
420 | return md5($k_opad . pack("H*", md5($k_ipad . $data))); | |
421 | } | |
422 | } | |
423 | ||
424 | /** | |
425 | * Check the gateway MD5 response to make sure that this is a proper | |
426 | * gateway response | |
427 | * | |
6a0b768e TO |
428 | * @param string $responseMD5 |
429 | * MD5 hash generated by the gateway. | |
430 | * @param string $transaction_id | |
431 | * Transaction id generated by the gateway. | |
432 | * @param string $amount | |
433 | * Purchase amount. | |
6a488035 | 434 | * |
2a6da8d7 EM |
435 | * @param bool $ipn |
436 | * | |
6a488035 TO |
437 | * @return bool |
438 | */ | |
00be9182 | 439 | public function checkMD5($responseMD5, $transaction_id, $amount, $ipn = FALSE) { |
6a488035 TO |
440 | // cannot check if no MD5 hash |
441 | $md5Hash = $this->_getParam('md5Hash'); | |
442 | if (empty($md5Hash)) { | |
443 | return TRUE; | |
444 | } | |
353ffa53 | 445 | $loginid = $this->_getParam('apiLogin'); |
6a488035 | 446 | $hashString = $ipn ? ($md5Hash . $transaction_id . $amount) : ($md5Hash . $loginid . $transaction_id . $amount); |
353ffa53 | 447 | $result = strtoupper(md5($hashString)); |
6a488035 TO |
448 | |
449 | if ($result == $responseMD5) { | |
450 | return TRUE; | |
451 | } | |
452 | else { | |
453 | return FALSE; | |
454 | } | |
455 | } | |
456 | ||
457 | /** | |
fe482240 | 458 | * Calculate and return the transaction fingerprint. |
6a488035 | 459 | * |
a6c01b45 CW |
460 | * @return string |
461 | * fingerprint | |
7c550ca0 | 462 | */ |
00be9182 | 463 | public function CalculateFP() { |
353ffa53 TO |
464 | $x_tran_key = $this->_getParam('paymentKey'); |
465 | $loginid = $this->_getParam('apiLogin'); | |
466 | $sequence = $this->_getParam('sequence'); | |
467 | $timestamp = $this->_getParam('timestamp'); | |
468 | $amount = $this->_getParam('amount'); | |
469 | $currency = $this->_getParam('currencyID'); | |
6a488035 TO |
470 | $transaction = "$loginid^$sequence^$timestamp^$amount^$currency"; |
471 | return $this->hmac($x_tran_key, $transaction); | |
472 | } | |
473 | ||
474 | /** | |
475 | * Split a CSV file. Requires , as delimiter and " as enclosure. | |
476 | * Based off notes from http://php.net/fgetcsv | |
477 | * | |
6a0b768e TO |
478 | * @param string $data |
479 | * A single CSV line. | |
6a488035 | 480 | * |
a6c01b45 CW |
481 | * @return array |
482 | * CSV fields | |
6a488035 | 483 | */ |
00be9182 | 484 | public function explode_csv($data) { |
6a488035 TO |
485 | $data = trim($data); |
486 | //make it easier to parse fields with quotes in them | |
487 | $data = str_replace('""', "''", $data); | |
488 | $fields = array(); | |
489 | ||
490 | while ($data != '') { | |
491 | $matches = array(); | |
492 | if ($data[0] == '"') { | |
493 | // handle quoted fields | |
494 | preg_match('/^"(([^"]|\\")*?)",?(.*)$/', $data, $matches); | |
495 | ||
496 | $fields[] = str_replace("''", '"', $matches[1]); | |
497 | $data = $matches[3]; | |
498 | } | |
499 | else { | |
500 | preg_match('/^([^,]*),?(.*)$/', $data, $matches); | |
501 | ||
502 | $fields[] = $matches[1]; | |
503 | $data = $matches[2]; | |
504 | } | |
505 | } | |
506 | return $fields; | |
507 | } | |
508 | ||
509 | /** | |
fe482240 | 510 | * Extract variables from returned XML. |
6a488035 TO |
511 | * |
512 | * Function is from Authorize.Net sample code, and used | |
513 | * to prevent the requirement of XML functions. | |
514 | * | |
6a0b768e TO |
515 | * @param string $content |
516 | * XML reply from Authorize.Net. | |
6a488035 | 517 | * |
a6c01b45 CW |
518 | * @return array |
519 | * refId, resultCode, code, text, subscriptionId | |
6a488035 | 520 | */ |
00be9182 | 521 | public function _parseArbReturn($content) { |
353ffa53 TO |
522 | $refId = $this->_substring_between($content, '<refId>', '</refId>'); |
523 | $resultCode = $this->_substring_between($content, '<resultCode>', '</resultCode>'); | |
524 | $code = $this->_substring_between($content, '<code>', '</code>'); | |
525 | $text = $this->_substring_between($content, '<text>', '</text>'); | |
6a488035 TO |
526 | $subscriptionId = $this->_substring_between($content, '<subscriptionId>', '</subscriptionId>'); |
527 | return array( | |
528 | 'refId' => $refId, | |
529 | 'resultCode' => $resultCode, | |
530 | 'code' => $code, | |
531 | 'text' => $text, | |
532 | 'subscriptionId' => $subscriptionId, | |
533 | ); | |
534 | } | |
535 | ||
536 | /** | |
fe482240 | 537 | * Helper function for _parseArbReturn. |
6a488035 TO |
538 | * |
539 | * Function is from Authorize.Net sample code, and used to avoid using | |
540 | * PHP5 XML functions | |
54957108 | 541 | * |
542 | * @param string $haystack | |
543 | * @param string $start | |
544 | * @param string $end | |
545 | * | |
546 | * @return bool|string | |
6a488035 | 547 | */ |
00be9182 | 548 | public function _substring_between(&$haystack, $start, $end) { |
6a488035 TO |
549 | if (strpos($haystack, $start) === FALSE || strpos($haystack, $end) === FALSE) { |
550 | return FALSE; | |
551 | } | |
552 | else { | |
553 | $start_position = strpos($haystack, $start) + strlen($start); | |
554 | $end_position = strpos($haystack, $end); | |
555 | return substr($haystack, $start_position, $end_position - $start_position); | |
556 | } | |
557 | } | |
558 | ||
559 | /** | |
fe482240 | 560 | * Get the value of a field if set. |
6a488035 | 561 | * |
6a0b768e TO |
562 | * @param string $field |
563 | * The field. | |
6a488035 | 564 | * |
2a6da8d7 | 565 | * @param bool $xmlSafe |
72b3a70c CW |
566 | * @return mixed |
567 | * value of the field, or empty string if the field is | |
16b10e64 | 568 | * not set |
6a488035 | 569 | */ |
00be9182 | 570 | public function _getParam($field, $xmlSafe = FALSE) { |
6a488035 | 571 | $value = CRM_Utils_Array::value($field, $this->_params, ''); |
a2dd09cc | 572 | if ($xmlSafe) { |
481a74f4 | 573 | $value = str_replace(array('&', '"', "'", '<', '>'), '', $value); |
a2dd09cc | 574 | } |
6a488035 TO |
575 | return $value; |
576 | } | |
577 | ||
6c786a9b EM |
578 | /** |
579 | * @param null $errorCode | |
580 | * @param null $errorMessage | |
581 | * | |
582 | * @return object | |
583 | */ | |
00be9182 | 584 | public function &error($errorCode = NULL, $errorMessage = NULL) { |
6a488035 TO |
585 | $e = CRM_Core_Error::singleton(); |
586 | if ($errorCode) { | |
2aa397bc | 587 | $e->push($errorCode, 0, array(), $errorMessage); |
6a488035 TO |
588 | } |
589 | else { | |
2aa397bc | 590 | $e->push(9001, 0, array(), 'Unknown System Error.'); |
6a488035 TO |
591 | } |
592 | return $e; | |
593 | } | |
594 | ||
595 | /** | |
596 | * Set a field to the specified value. Value must be a scalar (int, | |
597 | * float, string, or boolean) | |
598 | * | |
599 | * @param string $field | |
600 | * @param mixed $value | |
601 | * | |
a6c01b45 CW |
602 | * @return bool |
603 | * false if value is not a scalar, true if successful | |
6a488035 | 604 | */ |
00be9182 | 605 | public function _setParam($field, $value) { |
6a488035 TO |
606 | if (!is_scalar($value)) { |
607 | return FALSE; | |
608 | } | |
609 | else { | |
610 | $this->_params[$field] = $value; | |
611 | } | |
612 | } | |
613 | ||
614 | /** | |
fe482240 | 615 | * This function checks to see if we have the right config values. |
6a488035 | 616 | * |
a6c01b45 CW |
617 | * @return string |
618 | * the error message if any | |
6a488035 | 619 | */ |
00be9182 | 620 | public function checkConfig() { |
6a488035 TO |
621 | $error = array(); |
622 | if (empty($this->_paymentProcessor['user_name'])) { | |
623 | $error[] = ts('APILogin is not set for this payment processor'); | |
624 | } | |
625 | ||
626 | if (empty($this->_paymentProcessor['password'])) { | |
627 | $error[] = ts('Key is not set for this payment processor'); | |
628 | } | |
629 | ||
630 | if (!empty($error)) { | |
631 | return implode('<p>', $error); | |
632 | } | |
633 | else { | |
634 | return NULL; | |
635 | } | |
636 | } | |
637 | ||
6c786a9b EM |
638 | /** |
639 | * @return string | |
640 | */ | |
00be9182 | 641 | public function accountLoginURL() { |
6a488035 TO |
642 | return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net'; |
643 | } | |
644 | ||
6c786a9b EM |
645 | /** |
646 | * @param string $message | |
647 | * @param array $params | |
648 | * | |
649 | * @return bool|object | |
650 | */ | |
00be9182 | 651 | public function cancelSubscription(&$message = '', $params = array()) { |
6a488035 TO |
652 | $template = CRM_Core_Smarty::singleton(); |
653 | ||
654 | $template->assign('subscriptionType', 'cancel'); | |
655 | ||
656 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
657 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
658 | $template->assign('subscriptionId', CRM_Utils_Array::value('subscriptionId', $params)); | |
659 | ||
660 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
661 | ||
662 | // submit to authorize.net | |
663 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
664 | if (!$submit) { | |
665 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
666 | } | |
667 | ||
668 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
669 | curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); | |
670 | curl_setopt($submit, CURLOPT_HEADER, 1); | |
671 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
672 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 673 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
674 | |
675 | $response = curl_exec($submit); | |
676 | ||
677 | if (!$response) { | |
678 | return self::error(curl_errno($submit), curl_error($submit)); | |
679 | } | |
680 | ||
681 | curl_close($submit); | |
682 | ||
683 | $responseFields = $this->_ParseArbReturn($response); | |
684 | $message = "{$responseFields['code']}: {$responseFields['text']}"; | |
685 | ||
686 | if ($responseFields['resultCode'] == 'Error') { | |
687 | return self::error($responseFields['code'], $responseFields['text']); | |
688 | } | |
689 | return TRUE; | |
690 | } | |
691 | ||
6c786a9b EM |
692 | /** |
693 | * @param string $message | |
694 | * @param array $params | |
695 | * | |
696 | * @return bool|object | |
697 | */ | |
00be9182 | 698 | public function updateSubscriptionBillingInfo(&$message = '', $params = array()) { |
6a488035 TO |
699 | $template = CRM_Core_Smarty::singleton(); |
700 | $template->assign('subscriptionType', 'updateBilling'); | |
701 | ||
702 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
703 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
704 | $template->assign('subscriptionId', $params['subscriptionId']); | |
705 | ||
706 | $template->assign('cardNumber', $params['credit_card_number']); | |
707 | $exp_month = str_pad($params['month'], 2, '0', STR_PAD_LEFT); | |
708 | $exp_year = $params['year']; | |
709 | $template->assign('expirationDate', $exp_year . '-' . $exp_month); | |
710 | ||
711 | $template->assign('billingFirstName', $params['first_name']); | |
712 | $template->assign('billingLastName', $params['last_name']); | |
713 | $template->assign('billingAddress', $params['street_address']); | |
714 | $template->assign('billingCity', $params['city']); | |
715 | $template->assign('billingState', $params['state_province']); | |
716 | $template->assign('billingZip', $params['postal_code']); | |
717 | $template->assign('billingCountry', $params['country']); | |
718 | ||
719 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
720 | ||
721 | // submit to authorize.net | |
722 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
723 | if (!$submit) { | |
724 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
725 | } | |
726 | ||
727 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
728 | curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); | |
729 | curl_setopt($submit, CURLOPT_HEADER, 1); | |
730 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
731 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 732 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
733 | |
734 | $response = curl_exec($submit); | |
735 | ||
736 | if (!$response) { | |
737 | return self::error(curl_errno($submit), curl_error($submit)); | |
738 | } | |
739 | ||
740 | curl_close($submit); | |
741 | ||
742 | $responseFields = $this->_ParseArbReturn($response); | |
743 | $message = "{$responseFields['code']}: {$responseFields['text']}"; | |
744 | ||
745 | if ($responseFields['resultCode'] == 'Error') { | |
746 | return self::error($responseFields['code'], $responseFields['text']); | |
747 | } | |
748 | return TRUE; | |
749 | } | |
750 | ||
23de1ac0 EM |
751 | /** |
752 | * Process incoming notification. | |
753 | */ | |
754 | static public function handlePaymentNotification() { | |
755 | $ipnClass = new CRM_Core_Payment_AuthorizeNetIPN(array_merge($_GET, $_REQUEST)); | |
756 | $ipnClass->main(); | |
757 | } | |
758 | ||
6c786a9b EM |
759 | /** |
760 | * @param string $message | |
761 | * @param array $params | |
762 | * | |
763 | * @return bool|object | |
764 | */ | |
00be9182 | 765 | public function changeSubscriptionAmount(&$message = '', $params = array()) { |
6a488035 TO |
766 | $template = CRM_Core_Smarty::singleton(); |
767 | ||
768 | $template->assign('subscriptionType', 'update'); | |
769 | ||
770 | $template->assign('apiLogin', $this->_getParam('apiLogin')); | |
771 | $template->assign('paymentKey', $this->_getParam('paymentKey')); | |
772 | ||
773 | $template->assign('subscriptionId', $params['subscriptionId']); | |
702c1203 JM |
774 | |
775 | // for open ended subscription totalOccurrences has to be 9999 | |
776 | $installments = empty($params['installments']) ? 9999 : $params['installments']; | |
777 | $template->assign('totalOccurrences', $installments); | |
778 | ||
6a488035 TO |
779 | $template->assign('amount', $params['amount']); |
780 | ||
781 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); | |
782 | ||
783 | // submit to authorize.net | |
784 | $submit = curl_init($this->_paymentProcessor['url_recur']); | |
785 | if (!$submit) { | |
786 | return self::error(9002, 'Could not initiate connection to payment gateway'); | |
787 | } | |
788 | ||
789 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); | |
790 | curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); | |
791 | curl_setopt($submit, CURLOPT_HEADER, 1); | |
792 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); | |
793 | curl_setopt($submit, CURLOPT_POST, 1); | |
aaffa79f | 794 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL')); |
6a488035 TO |
795 | |
796 | $response = curl_exec($submit); | |
797 | ||
798 | if (!$response) { | |
799 | return self::error(curl_errno($submit), curl_error($submit)); | |
800 | } | |
801 | ||
802 | curl_close($submit); | |
803 | ||
804 | $responseFields = $this->_ParseArbReturn($response); | |
805 | $message = "{$responseFields['code']}: {$responseFields['text']}"; | |
806 | ||
807 | if ($responseFields['resultCode'] == 'Error') { | |
808 | return self::error($responseFields['code'], $responseFields['text']); | |
809 | } | |
810 | return TRUE; | |
811 | } | |
96025800 | 812 | |
6a488035 | 813 | } |