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

Last change on this file since 132 was 127, checked in by scdev, 18 years ago

Updated App.inc.php thru Hierarchy.inc.php

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