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

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

Minor improvements to module maker scripts. Minor AuthorizeNet? change.

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