-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathTaxJar.php
98 lines (83 loc) · 2.81 KB
/
TaxJar.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
<?php
namespace TaxJar;
class TaxJar
{
const VERSION = '2.0.0';
const DEFAULT_API_URL = 'https://api.taxjar.com';
const SANDBOX_API_URL = 'https://api.sandbox.taxjar.com';
const API_VERSION = 'v2';
protected $client;
protected $config;
public function __construct($key)
{
if ($key) {
$this->config = [
'base_uri' => self::DEFAULT_API_URL . '/' . self::API_VERSION . '/',
'handler' => $this->errorHandler(),
'headers' => [
'Authorization' => 'Bearer ' . $key,
'Content-Type' => 'application/json',
'User-Agent' => $this->getUserAgent()
],
];
$this->client = new \GuzzleHttp\Client($this->config);
} else {
throw new Exception('Please provide an API key.');
}
}
private function errorHandler()
{
$handler = \GuzzleHttp\HandlerStack::create();
$handler->push(\GuzzleHttp\Middleware::mapResponse(function ($response) {
if ($response->getStatusCode() >= 400) {
$data = json_decode($response->getBody());
throw new Exception(
sprintf(
'%s %s – %s',
$response->getStatusCode(),
isset($data->error) ? $data->error : 'something unexpected occurred',
isset($data->detail) ? $data->detail : 'please try again'
),
$response->getStatusCode()
);
}
return $response;
}));
return $handler;
}
private function refreshClient($config)
{
$this->client = new \GuzzleHttp\Client($config);
}
public function setApiConfig($index, $value)
{
if ($index == 'api_url') {
$index = 'base_uri';
$value .= '/' . self::API_VERSION . '/';
}
if ($index == 'headers') {
$value = array_merge($this->config[$index], $value);
}
$this->config[$index] = $value;
$this->refreshClient($this->config);
}
public function getApiConfig($index)
{
if ($index == 'api_url') {
$index = 'base_uri';
}
if ($index) {
return $this->config[$index];
} else {
return $this->config;
}
}
private function getUserAgent()
{
$os = function_exists('php_uname') ? php_uname('a') : '';
$php = 'PHP ' . PHP_VERSION;
$curl = function_exists('curl_version') ? 'cURL ' . curl_version()['version'] : '';
$openSSL = defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : '';
return "TaxJar/PHP ($os; $php; $curl; $openSSL) taxjar-php/" . self::VERSION;
}
}