forked from VinceG/USPS-php-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUSPSBase.php
365 lines (343 loc) · 8.84 KB
/
USPSBase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
/**
* Load required classes
*/
require_once('XMLParser.php');
/**
* USPS Base class
* used to perform the actual api calls
* @since 1.0
* @author Vincent Gabriel
*/
class USPSBase {
const LIVE_API_URL = 'http://production.shippingapis.com/ShippingAPI.dll';
const TEST_API_URL = 'http://production.shippingapis.com/ShippingAPITest.dll';
/**
* @var string - the usps username provided by the usps website
*/
protected $username = '';
/**
* the error code if one exists
* @var integer
*/
protected $errorCode = 0;
/**
* the error message if one exists
* @var string
*/
protected $errorMessage = '';
/**
* the response message
* @var string
*/
protected $response = '';
/**
* the headers returned from the call made
* @var array
*/
protected $headers = '';
/**
* The response represented as an array
* @var array
*/
protected $arrayResponse = array();
/**
* All the post fields we will add to the call
* @var array
*/
protected $postFields = array();
/**
* The api type we are about to call
* @var string
*/
protected $apiVersion = '';
/**
* @var boolean - set whether we are in a test mode or not
*/
public static $testMode = false;
/**
* @var array - different kind of supported api calls by this wrapper
*/
protected $apiCodes = array(
'RateV2' => 'RateV2Request',
'RateV4' => 'RateV4Request',
'IntlRateV2' => 'IntlRateV2Request',
'Verify' => 'AddressValidateRequest',
'ZipCodeLookup' => 'ZipCodeLookupRequest',
'CityStateLookup' => 'CityStateLookupRequest',
'TrackV2' => 'TrackFieldRequest',
'FirstClassMail' => 'FirstClassMailRequest',
'SDCGetLocations' => 'SDCGetLocationsRequest',
'ExpressMailLabel' => 'ExpressMailLabelRequest',
'PriorityMail' => 'PriorityMailRequest',
'OpenDistributePriorityV2' => 'OpenDistributePriorityV2.0Request',
'OpenDistributePriorityV2Certify' => 'OpenDistributePriorityV2.0CertifyRequest',
'ExpressMailIntl' => 'ExpressMailIntlRequest',
'PriorityMailIntl' => 'PriorityMailIntlRequest',
'FirstClassMailIntl' => 'FirstClassMailIntlRequest',
);
/**
* Default options for curl.
*/
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_PORT => 443,
CURLOPT_USERAGENT => 'usps-php',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
);
/**
* Constructor
* @param string $username - the usps api username
*/
public function __construct($username='') {
$this->username = $username;
}
/**
* set the usps api username we are going to user
* @param string $username - the usps api username
*/
public function setUsername($username) {
$this->username = $username;
}
/**
* Return the post data fields as an array
* @return array
*/
public function getPostData() {
$fields = array('API' => $this->apiVersion, 'XML' => $this->getXMLString());
return $fields;
}
/**
* Set the api version we are going to use
* @param string $version the new api version
* @return void
*/
public function setApiVersion($version) {
$this->apiVersion = $version;
}
/**
* Set whether we are in a test mode or not
* @param boolean $value
* @return void
*/
public function setTestMode($value) {
self::$testMode = (bool) $value;
}
/**
* Response api name
* @return string
*/
public function getResponseApiName() {
return str_replace('Request', 'Response', $this->apiCodes[$this->apiVersion]);
}
/**
* Makes an HTTP request. This method can be overriden by subclasses if
* developers want to do fancier things or use something other than curl to
* make the request.
*
* @param CurlHandler optional initialized curl handle
* @return String the response text
*/
protected function doRequest($ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
$opts[CURLOPT_POSTFIELDS] = http_build_query($this->getPostData(), null, '&');
$opts[CURLOPT_URL] = $this->getEndpoint();
// Replace 443 with 80 if it's not secured
if(strpos($opts[CURLOPT_URL], 'https://')===false) {
$opts[CURLOPT_PORT] = 80;
}
// set options
curl_setopt_array($ch, $opts);
// execute
$this->setResponse( curl_exec($ch) );
$this->setHeaders( curl_getinfo($ch) );
// fetch errors
$this->setErrorCode( curl_errno($ch) );
$this->setErrorMessage( curl_error($ch) );
// Convert response to array
$this->convertResponseToArray();
// If it failed then set error code and message
if($this->isError()) {
$arrayResponse = $this->getArrayResponse();
// Find the error number
$errorInfo = $this->getValueByKey($arrayResponse, 'Error');
if($errorInfo) {
$this->setErrorCode( $errorInfo['Number'] );
$this->setErrorMessage( $errorInfo['Description'] );
}
}
// close
curl_close($ch);
return $this->getResponse();
}
public function getEndpoint() {
return self::$testMode ? self::TEST_API_URL : self::LIVE_API_URL;
}
/**
* Return the xml string built that we are about to send over to the api
* @return string
*/
protected function getXMLString() {
// Add in the defaults
$postFields = array(
'@attributes' => array('USERID' => $this->username),
);
// Add in the sub class data
$postFields = array_merge($postFields, $this->getPostFields());
$xml = XMLParser::createXML($this->apiCodes[$this->apiVersion], $postFields);
return $xml->saveXML();
}
/**
* Did we encounter an error?
* @return boolean
*/
public function isError() {
$headers = $this->getHeaders();
$response = $this->getArrayResponse();
// First make sure we got a valid response
if($headers['http_code'] != 200) {
return true;
}
// Make sure the response does not have error in it
if(isset($response['Error'])) {
return true;
}
// Check to see if we have the Error word in the response
if(strpos($this->getResponse(), '<Error>') !== false) {
return true;
}
// No error
return false;
}
/**
* Was the last call successful
* @return boolean
*/
public function isSuccess() {
return !$this->isError() ? true : false;
}
/**
* Return the response represented as string
* @return array
*/
public function convertResponseToArray() {
if($this->getResponse()) {
$this->setArrayResponse(XML2Array::createArray($this->getResponse()));
}
return $this->getArrayResponse();
}
/**
* Set the array response value
* @param array $value
* @return void
*/
public function setArrayResponse($value) {
$this->arrayResponse = $value;
}
/**
* Return the array representation of the last response
* @return array
*/
public function getArrayResponse() {
return $this->arrayResponse;
}
/**
* Set the response
*
* @param mixed the response returned from the call
* @return facebookLib object
*/
public function setResponse( $response='' ) {
$this->response = $response;
return $this;
}
/**
* Get the response data
*
* @return mixed the response data
*/
public function getResponse() {
return $this->response;
}
/**
* Set the headers
*
* @param array the headers array
* @return facebookLib object
*/
public function setHeaders( $headers='' ) {
$this->headers = $headers;
return $this;
}
/**
* Get the headers
*
* @return array the headers returned from the call
*/
public function getHeaders() {
return $this->headers;
}
/**
* Set the error code number
*
* @param integer the error code number
* @return facebookLib object
*/
public function setErrorCode($code=0) {
$this->errorCode = $code;
return $this;
}
/**
* Get the error code number
*
* @return integer error code number
*/
public function getErrorCode() {
return $this->errorCode;
}
/**
* Set the error message
*
* @param string the error message
* @return facebookLib object
*/
public function setErrorMessage($message='') {
$this->errorMessage = $message;
return $this;
}
/**
* Get the error code message
*
* @return string error code message
*/
public function getErrorMessage() {
return $this->errorMessage;
}
/**
* Find a key inside a multi dim. array
* @param array $array
* @param string $key
* @return mixed
*/
protected function getValueByKey($array,$key) {
foreach($array as $k=>$each) {
if($k==$key) {
return $each;
}
if(is_array($each)) {
if($return = $this->getValueByKey($each,$key)) {
return $return;
}
}
}
// Nothing matched
return null;
}
}