Ian province abbreviation patch - issue 724
[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;
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));
159 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
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);
318 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
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
541 */
00be9182 542 public function _substring_between(&$haystack, $start, $end) {
6a488035
TO
543 if (strpos($haystack, $start) === FALSE || strpos($haystack, $end) === FALSE) {
544 return FALSE;
545 }
546 else {
547 $start_position = strpos($haystack, $start) + strlen($start);
548 $end_position = strpos($haystack, $end);
549 return substr($haystack, $start_position, $end_position - $start_position);
550 }
551 }
552
553 /**
fe482240 554 * Get the value of a field if set.
6a488035 555 *
6a0b768e
TO
556 * @param string $field
557 * The field.
6a488035 558 *
2a6da8d7 559 * @param bool $xmlSafe
72b3a70c
CW
560 * @return mixed
561 * value of the field, or empty string if the field is
16b10e64 562 * not set
6a488035 563 */
00be9182 564 public function _getParam($field, $xmlSafe = FALSE) {
6a488035 565 $value = CRM_Utils_Array::value($field, $this->_params, '');
a2dd09cc 566 if ($xmlSafe) {
481a74f4 567 $value = str_replace(array('&', '"', "'", '<', '>'), '', $value);
a2dd09cc 568 }
6a488035
TO
569 return $value;
570 }
571
6c786a9b
EM
572 /**
573 * @param null $errorCode
574 * @param null $errorMessage
575 *
576 * @return object
577 */
00be9182 578 public function &error($errorCode = NULL, $errorMessage = NULL) {
6a488035
TO
579 $e = CRM_Core_Error::singleton();
580 if ($errorCode) {
2aa397bc 581 $e->push($errorCode, 0, array(), $errorMessage);
6a488035
TO
582 }
583 else {
2aa397bc 584 $e->push(9001, 0, array(), 'Unknown System Error.');
6a488035
TO
585 }
586 return $e;
587 }
588
589 /**
590 * Set a field to the specified value. Value must be a scalar (int,
591 * float, string, or boolean)
592 *
593 * @param string $field
594 * @param mixed $value
595 *
a6c01b45
CW
596 * @return bool
597 * false if value is not a scalar, true if successful
6a488035 598 */
00be9182 599 public function _setParam($field, $value) {
6a488035
TO
600 if (!is_scalar($value)) {
601 return FALSE;
602 }
603 else {
604 $this->_params[$field] = $value;
605 }
606 }
607
608 /**
fe482240 609 * This function checks to see if we have the right config values.
6a488035 610 *
a6c01b45
CW
611 * @return string
612 * the error message if any
6a488035 613 */
00be9182 614 public function checkConfig() {
6a488035
TO
615 $error = array();
616 if (empty($this->_paymentProcessor['user_name'])) {
617 $error[] = ts('APILogin is not set for this payment processor');
618 }
619
620 if (empty($this->_paymentProcessor['password'])) {
621 $error[] = ts('Key is not set for this payment processor');
622 }
623
624 if (!empty($error)) {
625 return implode('<p>', $error);
626 }
627 else {
628 return NULL;
629 }
630 }
631
6c786a9b
EM
632 /**
633 * @return string
634 */
00be9182 635 public function accountLoginURL() {
6a488035
TO
636 return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net';
637 }
638
6c786a9b
EM
639 /**
640 * @param string $message
641 * @param array $params
642 *
643 * @return bool|object
644 */
00be9182 645 public function cancelSubscription(&$message = '', $params = array()) {
6a488035
TO
646 $template = CRM_Core_Smarty::singleton();
647
648 $template->assign('subscriptionType', 'cancel');
649
650 $template->assign('apiLogin', $this->_getParam('apiLogin'));
651 $template->assign('paymentKey', $this->_getParam('paymentKey'));
652 $template->assign('subscriptionId', CRM_Utils_Array::value('subscriptionId', $params));
653
654 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
655
656 // submit to authorize.net
657 $submit = curl_init($this->_paymentProcessor['url_recur']);
658 if (!$submit) {
659 return self::error(9002, 'Could not initiate connection to payment gateway');
660 }
661
662 curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
663 curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
664 curl_setopt($submit, CURLOPT_HEADER, 1);
665 curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
666 curl_setopt($submit, CURLOPT_POST, 1);
667 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
668
669 $response = curl_exec($submit);
670
671 if (!$response) {
672 return self::error(curl_errno($submit), curl_error($submit));
673 }
674
675 curl_close($submit);
676
677 $responseFields = $this->_ParseArbReturn($response);
678 $message = "{$responseFields['code']}: {$responseFields['text']}";
679
680 if ($responseFields['resultCode'] == 'Error') {
681 return self::error($responseFields['code'], $responseFields['text']);
682 }
683 return TRUE;
684 }
685
6c786a9b
EM
686 /**
687 * @param string $message
688 * @param array $params
689 *
690 * @return bool|object
691 */
00be9182 692 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
6a488035
TO
693 $template = CRM_Core_Smarty::singleton();
694 $template->assign('subscriptionType', 'updateBilling');
695
696 $template->assign('apiLogin', $this->_getParam('apiLogin'));
697 $template->assign('paymentKey', $this->_getParam('paymentKey'));
698 $template->assign('subscriptionId', $params['subscriptionId']);
699
700 $template->assign('cardNumber', $params['credit_card_number']);
701 $exp_month = str_pad($params['month'], 2, '0', STR_PAD_LEFT);
702 $exp_year = $params['year'];
703 $template->assign('expirationDate', $exp_year . '-' . $exp_month);
704
705 $template->assign('billingFirstName', $params['first_name']);
706 $template->assign('billingLastName', $params['last_name']);
707 $template->assign('billingAddress', $params['street_address']);
708 $template->assign('billingCity', $params['city']);
709 $template->assign('billingState', $params['state_province']);
710 $template->assign('billingZip', $params['postal_code']);
711 $template->assign('billingCountry', $params['country']);
712
713 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
714
715 // submit to authorize.net
716 $submit = curl_init($this->_paymentProcessor['url_recur']);
717 if (!$submit) {
718 return self::error(9002, 'Could not initiate connection to payment gateway');
719 }
720
721 curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
722 curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
723 curl_setopt($submit, CURLOPT_HEADER, 1);
724 curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
725 curl_setopt($submit, CURLOPT_POST, 1);
726 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
727
728 $response = curl_exec($submit);
729
730 if (!$response) {
731 return self::error(curl_errno($submit), curl_error($submit));
732 }
733
734 curl_close($submit);
735
736 $responseFields = $this->_ParseArbReturn($response);
737 $message = "{$responseFields['code']}: {$responseFields['text']}";
738
739 if ($responseFields['resultCode'] == 'Error') {
740 return self::error($responseFields['code'], $responseFields['text']);
741 }
742 return TRUE;
743 }
744
23de1ac0
EM
745 /**
746 * Process incoming notification.
747 */
748 static public function handlePaymentNotification() {
749 $ipnClass = new CRM_Core_Payment_AuthorizeNetIPN(array_merge($_GET, $_REQUEST));
750 $ipnClass->main();
751 }
752
6c786a9b
EM
753 /**
754 * @param string $message
755 * @param array $params
756 *
757 * @return bool|object
758 */
00be9182 759 public function changeSubscriptionAmount(&$message = '', $params = array()) {
6a488035
TO
760 $template = CRM_Core_Smarty::singleton();
761
762 $template->assign('subscriptionType', 'update');
763
764 $template->assign('apiLogin', $this->_getParam('apiLogin'));
765 $template->assign('paymentKey', $this->_getParam('paymentKey'));
766
767 $template->assign('subscriptionId', $params['subscriptionId']);
702c1203
JM
768
769 // for open ended subscription totalOccurrences has to be 9999
770 $installments = empty($params['installments']) ? 9999 : $params['installments'];
771 $template->assign('totalOccurrences', $installments);
772
6a488035
TO
773 $template->assign('amount', $params['amount']);
774
775 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
776
777 // submit to authorize.net
778 $submit = curl_init($this->_paymentProcessor['url_recur']);
779 if (!$submit) {
780 return self::error(9002, 'Could not initiate connection to payment gateway');
781 }
782
783 curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
784 curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
785 curl_setopt($submit, CURLOPT_HEADER, 1);
786 curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
787 curl_setopt($submit, CURLOPT_POST, 1);
788 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
789
790 $response = curl_exec($submit);
791
792 if (!$response) {
793 return self::error(curl_errno($submit), curl_error($submit));
794 }
795
796 curl_close($submit);
797
798 $responseFields = $this->_ParseArbReturn($response);
799 $message = "{$responseFields['code']}: {$responseFields['text']}";
800
801 if ($responseFields['resultCode'] == 'Error') {
802 return self::error($responseFields['code'], $responseFields['text']);
803 }
804 return TRUE;
805 }
96025800 806
6a488035 807}