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