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