source: branches/2.0singleton/lib/AuthorizeNet.inc.php @ 250

Last change on this file since 250 was 250, checked in by quinn, 17 years ago

Fixed LOG_ERROR -> LOG_ERR in AuthorizeNet?.inc.php.

File size: 8.3 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 $md5_hash_value = ','; // A custom value for the response delimination character.
45    var $_results = array();
46    var $_params = array();
47    var $_default_params = array(
48        'x_version'         => '3.1',
49        'x_relay_response'  => 'FALSE',
50        'x_delim_data'      => 'TRUE',
51        'x_echo_data'       => 'TRUE',
52        'x_adc_url'         => 'FALSE',
53        'x_type'            => 'AUTH_CAPTURE',
54        'x_method'          => 'CC',
55        'x_login'           => '',
56        'x_tran_key'        => '',
57        'x_delim_char'      => ',',
58        'x_encap_char'      => '',
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        if (!function_exists('curl_init')) {
114            trigger_error('AuthorizeNet error: curl not installed.', E_USER_ERROR);
115        }
116
117        // The authorize.net url to post to.
118        $this->post_url = isset($params['post_url']) ? $params['post_url'] : 'https://secure.authorize.net/gateway/transact.dll';
119
120        // A custom value for the response delimination character.
121        $this->md5_hash_value = isset($params['md5_hash_value']) ? $params['md5_hash_value'] : '';
122
123        // Set default parameters.
124        $this->_params = $this->_default_params;
125    }
126
127    /**
128     * Set (or overwrite existing) parameters by passing an array of new parameters.
129     *
130     * @access public
131     * @param  array    $params     Array of parameters (key => val pairs).
132     */
133    function setParam($params)
134    {
135        $app =& App::getInstance();
136   
137        if (isset($params) && is_array($params)) {
138            // Merge new parameters with old overriding only those passed.
139            $this->_params = array_merge($this->_params, $params);
140        } else {
141            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
142        }
143    }
144
145    /**
146     * Return the value of a parameter, if it exists.
147     *
148     * @access public
149     * @param string $param        Which parameter to return.
150     * @return mixed               Configured parameter value.
151     */
152    function getParam($param)
153    {
154        $app =& App::getInstance();
155   
156        if (isset($this->_params[$param])) {
157            return $this->_params[$param];
158        } else {
159            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
160            return null;
161        }
162    }
163
164
165    /**
166     * Submit parameters to gateway.
167     *
168     * @access public
169     *
170     * @return mixed      False or x_response_code: false = error, 1 = accepted, 2 = declined, 3 = error
171     */
172    function process()
173    {
174        $app =& App::getInstance();
175   
176        if (empty($this->_params['x_login'])) {
177            $this->_results['x_response_reason_text'] = _("Transaction gateway temporarily not available. Please try again later.");
178            $app->logMsg(sprintf('x_login not specified.', null), LOG_ERR, __FILE__, __LINE__);
179            return false;
180        }
181        if (empty($this->_params['x_card_num'])) {
182            $this->_results['x_response_reason_text'] = _("Transaction gateway temporarily not available. Please try again later.");
183            $app->logMsg(sprintf('x_card_num not specified.', null), LOG_ERR, __FILE__, __LINE__);
184            return false;
185        }
186
187        // Generate query string from params.
188        $q = '';
189        $delim = '';
190        foreach ($this->_params as $key=>$val) {
191            $q .= $delim . $key . '=' . urlencode($val);
192            $delim = '&';
193        }
194
195        // Setup curl and execute request.
196        $ch = curl_init();
197        curl_setopt($ch, CURLOPT_URL, $this->post_url);
198        curl_setopt($ch, CURLOPT_HEADER, 0);
199        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
200        curl_setopt($ch, CURLOPT_POST, 1);
201        curl_setopt($ch, CURLOPT_POSTFIELDS, $q);
202        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
203        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
204        $result = curl_exec($ch);
205        curl_close($ch);
206
207        if (!$result) {
208            return false;
209        }
210        return $this->_processResult($result);
211    }
212
213
214    /**
215     * Returns the results array. Returns a specific element if $key is provided.
216     *
217     * @access public
218     *
219     * @return array             Returns the results array.
220     */
221    function getResult($key=null)
222    {
223        if (isset($key)) {
224            return $this->_results[$key];
225        } else {
226            return $this->_results;
227        }
228    }
229
230    /**
231     * Tests a returned md5 hash value with a locally computated one.
232     *
233     * @access public
234     *
235     * @return bool             True if the hash is valid, false otherwise.
236     */
237    function validMD5Hash()
238    {
239        return (
240            strtolower($this->getResult('x_md5_hash')) == strtolower(md5(
241                $this->md5_hash_value .
242                $this->getParam('x_login') .
243                $this->getResult('x_trans_id') .
244                $this->getResult('x_amount')
245            ))
246        );
247    }
248
249    /**
250     * Reset all variables. Call before beginning a new transaction.
251     *
252     * @access public
253     */
254    function reset()
255    {
256        $this->_results = Array();
257        $this->_params = $this->_default_params;
258    }
259
260    /**
261     * Process the result from the curl execution to create an associative array of returned data.
262     *
263     * @access private.
264     *
265     * @param  mixed $result    The result from the curl execution.
266     *
267     * @return integer      Transaction result code.
268     */
269    function _processResult($result)
270    {
271        $this->_results = Array();
272
273        $results = explode($this->getParam('x_delim_char'), $result);
274
275        $num = sizeof($this->_result_fields);
276        for ($i=0, $j=0; $i<$num; $i++) {
277            if (isset($this->_result_fields[$i])) {
278                $this->_results[$this->_result_fields[$i]] = $results[$i];
279            } else {
280                $j++;
281                $this->_results["x_custom_$j"] = $results[$i];
282            }
283        }
284        return $this->_results['x_response_code'];
285    }
286}
287?>
Note: See TracBrowser for help on using the repository browser.