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

Last change on this file since 1 was 1, checked in by scdev, 19 years ago

Initial import.

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