source: trunk/lib/AuthorizeNet.inc.php

Last change on this file was 502, checked in by anonymous, 9 years ago

Many minor fixes during pulso development

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