source: trunk/lib/AuthorizeNet.inc.php @ 327

Last change on this file since 327 was 327, checked in by quinn, 16 years ago

Created v1.0 of Currency class, using xurrency.com.

File size: 8.6 KB
Line 
1<?php
2/**
3 * AuthorizeNet.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * The AuthorizeNet class provides an abstract interface for communicating
7 * with authorize.net's AIM interface. Supports Auth.Net v3.1
8 *
9 * @author  Quinn Comendant <quinn@strangecode.com>
10 * @version 1.0
11 * @date 2004-04-06
12 */
13 
14// Example usage
15// require_once 'codebase/lib/AuthorizeNet.inc.php';
16//
17// $authorizenet = new AuthorizeNet();
18// $authorizenet->setParam(array(
19//     'x_Login' => 'myaccount',
20//     'x_Test_Request' => 'TRUE',
21//     'x_First_Name' => 'John',
22//     'x_Last_Name' => 'Doe',
23//     'x_Amount' => '1.20',
24//     'x_Card_Num' => '4111111111111111',
25//     'x_Card_Code' => '123',
26//     'x_Exp_Date' => '042008',
27//     'x_Invoice_Num' => '100',
28//     'x_Address' => '10 rue Levouvé',
29//     'x_City' => 'SomeCity',
30//     'x_State' => 'CA',
31//     'x_Zip' => '75010',
32// ));
33//
34// $result_code = $authorizenet->process(); // Returns one of: false = error, 1 = accepted, 2 = declined, 3 = error
35// $result_array = $authorizenet->getResults();
36//
37// foreach ($result_array as $key => $value) {
38//     print "$key: $value<br>\n";
39// }
40
41class AuthorizeNet {
42
43    var $post_url = ''; // The URL to post data to.
44    var $_results = array();
45    var $_params = array();
46    var $_default_params = array(
47        'x_version'         => '3.1',
48        'x_relay_response'  => 'FALSE',
49        'x_delim_data'      => 'TRUE',
50        'x_echo_data'       => 'TRUE',
51        'x_adc_url'         => 'FALSE',
52        'x_type'            => 'AUTH_CAPTURE',
53        'x_method'          => 'CC',
54        'x_login'           => '',
55        'x_tran_key'        => '',
56        'x_delim_char'      => ',',
57        'x_encap_char'      => '',
58        'md5_hash_salt'    => '',
59    );
60
61    // Array of response names. Used in the results array.
62    var $_result_fields = Array(
63        'x_response_code',
64        'x_response_subcode',
65        'x_response_reason_code',
66        'x_response_reason_text',
67        'x_auth_code',
68        'x_avs_code',
69        'x_trans_id',
70        'x_invoice_num',
71        'x_description',
72        'x_amount',
73        'x_method',
74        'x_type',
75        'x_cust_id',
76        'x_first_name',
77        'x_last_name',
78        'x_company',
79        'x_address',
80        'x_city',
81        'x_state',
82        'x_zip',
83        'x_country',
84        'x_phone',
85        'x_fax',
86        'x_email',
87        'x_ship_to_first_name',
88        'x_ship_to_last_name',
89        'x_ship_to_company',
90        'x_ship_to_address',
91        'x_ship_to_city',
92        'x_ship_to_state',
93        'x_ship_to_zip',
94        'x_ship_to_country',
95        'x_tax',
96        'x_duty',
97        'x_freight',
98        'x_tax_exempt',
99        'x_po_num',
100        'x_md5_hash',
101        'x_card_code'
102    );
103
104    /**
105     * Constructs a new authentication object.
106     *
107     * @access public
108     *
109     * @param optional array $_params  A hash containing parameters.
110     */
111    function AuthorizeNet($params = array())
112    {
113        $app =& App::getInstance();
114
115        if (!function_exists('curl_init')) {
116            trigger_error('AuthorizeNet error: curl not installed.', E_USER_ERROR);
117        }
118
119        // The authorize.net url to post to.
120        $this->post_url = isset($params['post_url']) ? $params['post_url'] : 'https://secure.authorize.net/gateway/transact.dll';
121
122        // Set default parameters.
123        $this->_params = $this->_default_params;
124        $this->setParam($params);
125       
126        $this->setParam(array('md5_hash_salt' => $app->getParam('signing_key')));
127    }
128
129    /**
130     * Set (or overwrite existing) parameters by passing an array of new parameters.
131     *
132     * @access public
133     * @param  array    $params     Array of parameters (key => val pairs).
134     */
135    function setParam($params)
136    {
137        $app =& App::getInstance();
138   
139        if (isset($params) && is_array($params)) {
140            // Merge new parameters with old overriding only those passed.
141            $this->_params = array_merge($this->_params, $params);
142        } else {
143            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
144        }
145    }
146
147    /**
148     * Return the value of a parameter, if it exists.
149     *
150     * @access public
151     * @param string $param        Which parameter to return.
152     * @return mixed               Configured parameter value.
153     */
154    function getParam($param)
155    {
156        $app =& App::getInstance();
157   
158        if (isset($this->_params[$param])) {
159            return $this->_params[$param];
160        } else {
161            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
162            return null;
163        }
164    }
165
166
167    /**
168     * Submit parameters to gateway.
169     *
170     * @access public
171     *
172     * @return mixed      False or x_response_code: false = error, 1 = accepted, 2 = declined, 3 = error
173     */
174    function process()
175    {
176        $app =& App::getInstance();
177   
178        if (empty($this->_params['x_login'])) {
179            $this->_results['x_response_reason_text'] = _("Transaction gateway temporarily not available. Please try again later.");
180            $app->logMsg(sprintf('x_login not specified.', null), LOG_ERR, __FILE__, __LINE__);
181            return false;
182        }
183        if (empty($this->_params['x_card_num'])) {
184            $this->_results['x_response_reason_text'] = _("Transaction gateway temporarily not available. Please try again later.");
185            $app->logMsg(sprintf('x_card_num not specified.', null), LOG_ERR, __FILE__, __LINE__);
186            return false;
187        }
188
189        // Generate query string from params.
190        $q = '';
191        $delim = '';
192        foreach ($this->_params as $key=>$val) {
193            $q .= $delim . $key . '=' . urlencode($val);
194            $delim = '&';
195        }
196
197        // Setup curl and execute request.
198        $ch = curl_init();
199        curl_setopt($ch, CURLOPT_URL, $this->post_url);
200        curl_setopt($ch, CURLOPT_HEADER, 0);
201        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
202        curl_setopt($ch, CURLOPT_POST, 1);
203        curl_setopt($ch, CURLOPT_POSTFIELDS, $q);
204        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
205        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
206        $result = curl_exec($ch);
207        $error = curl_error($ch);
208        curl_close($ch);
209
210        if (!$result) {
211            if ('' != $error) {
212                $app->logMsg(sprintf('Curl error: %s', $error), LOG_ERR, __FILE__, __LINE__);
213            }
214            return false;
215        }
216        return $this->_processResult($result);
217    }
218
219
220    /**
221     * Returns the results array. Returns a specific element if $key is provided.
222     *
223     * @access public
224     *
225     * @return array             Returns the results array.
226     */
227    function getResult($key=null)
228    {
229        if (isset($key)) {
230            if (isset($this->_results[$key])) {
231                return $this->_results[$key];
232            } else {
233                return null;
234            }
235        } else {
236            return $this->_results;
237        }
238    }
239
240    /**
241     * Tests a returned md5 hash value with a locally computated one.
242     *
243     * @access public
244     *
245     * @return bool             True if the hash is valid, false otherwise.
246     */
247    function validMD5Hash()
248    {
249        return (
250            mb_strtolower($this->getResult('x_md5_hash')) == mb_strtolower(md5(
251                $this->getParam('md5_hash_salt') .
252                $this->getParam('x_login') .
253                $this->getResult('x_trans_id') .
254                $this->getResult('x_amount')
255            ))
256        );
257    }
258
259    /**
260     * Reset all variables. Call before beginning a new transaction.
261     *
262     * @access public
263     */
264    function reset()
265    {
266        $this->_results = Array();
267        $this->_params = $this->_default_params;
268    }
269
270    /**
271     * Process the result from the curl execution to create an associative array of returned data.
272     *
273     * @access private.
274     *
275     * @param  mixed $result    The result from the curl execution.
276     *
277     * @return integer      Transaction result code.
278     */
279    function _processResult($result)
280    {
281        $this->_results = Array();
282
283        $results = explode($this->getParam('x_delim_char'), $result);
284
285        $num = sizeof($this->_result_fields);
286        for ($i=0, $j=0; $i<$num; $i++) {
287            if (isset($this->_result_fields[$i])) {
288                $this->_results[$this->_result_fields[$i]] = $results[$i];
289            } else {
290                $j++;
291                $this->_results["x_custom_$j"] = $results[$i];
292            }
293        }
294        return $this->_results['x_response_code'];
295    }
296}
297?>
Note: See TracBrowser for help on using the repository browser.