-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Client.php
301 lines (255 loc) · 9.06 KB
/
Client.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
<?php
/*
* This file is part of tiktok-shop.
*
* (c) Jin <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace EcomPHP\TiktokShop;
use EcomPHP\TiktokShop\Errors\ResponseException;
use EcomPHP\TiktokShop\Resources\AffiliateCreator;
use EcomPHP\TiktokShop\Resources\AffiliatePartner;
use EcomPHP\TiktokShop\Resources\AffiliateSeller;
use EcomPHP\TiktokShop\Resources\CustomerService;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Middleware;
use GuzzleHttp\RequestOptions;
use EcomPHP\TiktokShop\Errors\TiktokShopException;
use EcomPHP\TiktokShop\Resources\Event;
use EcomPHP\TiktokShop\Resources\Finance;
use EcomPHP\TiktokShop\Resources\Fulfillment;
use EcomPHP\TiktokShop\Resources\GlobalProduct;
use EcomPHP\TiktokShop\Resources\Logistic;
use EcomPHP\TiktokShop\Resources\Order;
use EcomPHP\TiktokShop\Resources\Product;
use EcomPHP\TiktokShop\Resources\Promotion;
use EcomPHP\TiktokShop\Resources\ReturnRefund;
use EcomPHP\TiktokShop\Resources\Seller;
use EcomPHP\TiktokShop\Resources\Authorization;
use EcomPHP\TiktokShop\Resources\Supplychain;
use Psr\Http\Message\RequestInterface;
/**
* @property-read Authorization $Authorization
* @property-read Seller $Seller
* @property-read Product $Product
* @property-read Order $Order
* @property-read Fulfillment $Fulfillment
* @property-read Logistic $Logistic
* @property-read Finance $Finance
* @property-read GlobalProduct $GlobalProduct
* @property-read Promotion $Promotion
* @property-read Supplychain $Supplychain
* @property-read Event $Event
* @property-read ReturnRefund $ReturnRefund
* @property-read CustomerService $CustomerService
* @property-read AffiliateSeller $AffiliateSeller
* @property-read AffiliateCreator $AffiliateCreator
* @property-read AffiliatePartner $AffiliatePartner
*/
class Client
{
public CONST DEFAULT_VERSION = '202309';
protected $app_key;
protected $app_secret;
protected $access_token;
/**
* required for calling cross-border shop
*/
protected $shop_cipher;
protected $version;
/**
* custom guzzle client options
*
* @var array
* @see https://docs.guzzlephp.org/en/stable/request-options.html
*/
protected $options;
public const resources = [
Authorization::class,
Seller::class,
Product::class,
Order::class,
Fulfillment::class,
Logistic::class,
Finance::class,
GlobalProduct::class,
Promotion::class,
Supplychain::class,
Event::class,
ReturnRefund::class,
CustomerService::class,
AffiliateSeller::class,
AffiliateCreator::class,
AffiliatePartner::class,
];
public function __construct($app_key, $app_secret, $options = [])
{
$this->app_key = $app_key;
$this->app_secret = $app_secret;
$this->options = $options;
$this->useVersion(static::DEFAULT_VERSION);
}
public function useSandboxMode()
{
trigger_deprecation('ecomphp/tiktokshop-php', '2.0.0', 'useSandboxMode() will be deprecated: Since API version 202309, Tiktokshop API sandbox is no longer worked, please use production environment.');
}
/**
* Change default api version for all resources called from this client
*/
public function useVersion($version)
{
$this->version = $version;
}
public function getAppKey()
{
return $this->app_key;
}
public function getAppSecret()
{
return $this->app_secret;
}
public function setAccessToken($access_token)
{
$this->access_token = $access_token;
}
public function setShopCipher($shop_cipher)
{
$this->shop_cipher = $shop_cipher;
}
public function auth()
{
return new Auth($this);
}
public function webhook()
{
$webhook = new Webhook($this);
$webhook->verify();
$webhook->capture();
return $webhook;
}
/**
* append app_key, timestamp, version, shop_id, access_token, sign to request
*
* @param RequestInterface $request
* @return RequestInterface
*/
protected function modifyRequestBeforeSend(RequestInterface $request)
{
$uri = $request->getUri();
parse_str($uri->getQuery(), $query);
$query['app_key'] = $this->getAppKey();
$query['timestamp'] = time();
if ($this->access_token && !isset($query['x-tts-access-token'])) {
$request = $request->withHeader('x-tts-access-token', $this->access_token);
}
if ($this->shop_cipher && !isset($query['shop_cipher'])) {
$query['shop_cipher'] = $this->shop_cipher;
}
// shop_cipher is not allowed in some api
if (preg_match('/^\/product\/(\d{6})\/(global_products|files\/upload|images\/upload)/', $uri->getPath())
|| preg_match('/^\/(authorization|seller)\/(\d{6})\//', $uri->getPath())) {
unset($query['shop_cipher']);
}
$this->prepareSignature($request, $query);
$uri = $uri->withQuery(http_build_query($query));
// set default content-type to application/json
if (!$request->getHeaderLine('content-type')) {
$request = $request->withHeader('content-type', 'application/json');
}
return $request->withUri($uri);
}
protected function httpClient()
{
$stack = HandlerStack::create();
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $this->modifyRequestBeforeSend($request);
}));
$options = array_merge([
RequestOptions::HTTP_ERRORS => false, // disable throw exception on http 4xx, manual handle it
'handler' => $stack,
'base_uri' => 'https://open-api.tiktokglobalshop.com/',
], $this->options ?? []);
return new GuzzleHttpClient($options);
}
/**
* tiktokshop api signature algorithm
* @see https://partner.tiktokshop.com/doc/page/274638
*
* @param RequestInterface $request
* @param $params
* @return void
*/
protected function prepareSignature($request, &$params)
{
$paramsToBeSigned = $params;
$stringToBeSigned = '';
// 1. Extract all query param EXCEPT ' sign ', ' access_token ', reorder the params based on alphabetical order.
unset($paramsToBeSigned['sign'], $paramsToBeSigned['access_token'], $paramsToBeSigned['x-tts-access-token']);
ksort($paramsToBeSigned);
// 2. Concat all the param in the format of {key}{value}
foreach ($paramsToBeSigned as $k => $v) {
if (!is_array($v)) {
$stringToBeSigned .= "$k$v";
}
}
// 3. Append the request path to the beginning
$stringToBeSigned = $request->getUri()->getPath() . $stringToBeSigned;
// 4. If the request header content_type is not multipart/form-data, append body to the end
if ($request->getMethod() !== 'GET' && strpos($request->getHeaderLine('content-type'), 'multipart/form-data') === false) {
$stringToBeSigned .= (string) $request->getBody();
}
// 5. Wrap string generated in step 3 with app_secret.
$stringToBeSigned = $this->getAppSecret() . $stringToBeSigned . $this->getAppSecret();
// Encode the digest byte stream in hexadecimal and use sha256 to generate sign with salt(secret).
$params['sign'] = hash_hmac('sha256', $stringToBeSigned, $this->getAppSecret());
}
/**
* Magic call resource
*
* @param $resourceName
* @throws TiktokShopException
* @return mixed
*/
public function __get($resourceName)
{
$resourceClassName = __NAMESPACE__."\\Resources\\".$resourceName;
if (!in_array($resourceClassName, self::resources)) {
throw new TiktokShopException("Invalid resource ".$resourceName);
}
//Initiate the resource object
$resource = new $resourceClassName();
if (!$resource instanceof Resource) {
throw new TiktokShopException("Invalid resource class ".$resourceClassName);
}
$resource->useVersion($this->version);
$resource->useHttpClient($this->httpClient());
return $resource;
}
public function call($method, $uri, $params = [])
{
try {
$response = $this->httpClient()->request($method, $uri, $params);
} catch (GuzzleException $e) {
throw new ResponseException($e->getMessage(), $e->getCode(), $e);
}
$json = json_decode((string) $response->getBody(), true);
if ($json === null) {
throw new ResponseException('Unable to parse response string as JSON');
}
return $json;
}
public function get($uri)
{
return $this->call('GET', $uri);
}
public function post($uri, $data)
{
return $this->call('POST', $uri, [
RequestOptions::JSON => $data,
]);
}
}