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