AccessToken.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. /**
  3. * This file is part of the apiadmin/tiktok.
  4. */
  5. namespace App\Libs\TikTok\OpenPlatform\Kernel;
  6. use App\Libs\TikTok\Kernel\Contracts\AccessTokenInterface;
  7. use App\Libs\TikTok\Kernel\Exceptions\AccessTokenException;
  8. use App\Libs\TikTok\Kernel\Exceptions\HttpException;
  9. use App\Libs\TikTok\Kernel\Exceptions\InvalidArgumentException;
  10. use App\Libs\TikTok\Kernel\Exceptions\InvalidConfigException;
  11. use App\Libs\TikTok\Kernel\Exceptions\RuntimeException;
  12. use App\Libs\TikTok\Kernel\ServiceContainer;
  13. use App\Libs\TikTok\Kernel\Support\Collection;
  14. use App\Libs\TikTok\Kernel\Traits\HasHttpRequests;
  15. use App\Libs\TikTok\Kernel\Traits\InteractsWithCache;
  16. use GuzzleHttp\Exception\GuzzleException;
  17. use GuzzleHttp\Psr7\Utils;
  18. use Psr\Http\Message\RequestInterface;
  19. use Psr\Http\Message\ResponseInterface;
  20. /**
  21. * Class AccessToken.
  22. *
  23. * @author overtrue <i@overtrue.me>
  24. */
  25. abstract class AccessToken implements AccessTokenInterface {
  26. use HasHttpRequests;
  27. use InteractsWithCache;
  28. /**
  29. * @var ServiceContainer
  30. */
  31. protected $app;
  32. /**
  33. * @var string
  34. */
  35. protected $requestMethod = 'POST';
  36. /**
  37. * @var string
  38. */
  39. protected $endpointToGetToken = 'oauth/client_token/';
  40. /**
  41. * @var string
  42. */
  43. protected $queryName;
  44. /**
  45. * @var array
  46. */
  47. protected $token;
  48. /**
  49. * @var string
  50. */
  51. protected $tokenKey = 'access_token';
  52. /**
  53. * @var string
  54. */
  55. protected $cachePrefix = 'EasyTiktok.open_platform.access_token.';
  56. /**
  57. * AccessToken constructor.
  58. *
  59. * @param ServiceContainer $app
  60. */
  61. public function __construct(ServiceContainer $app) {
  62. $this->app = $app;
  63. }
  64. /**
  65. * @param bool $refresh
  66. *
  67. * @return array
  68. *
  69. * @throws HttpException
  70. * @throws \Psr\SimpleCache\InvalidArgumentException
  71. * @throws InvalidConfigException
  72. * @throws InvalidArgumentException
  73. * @throws RuntimeException
  74. * @throws GuzzleException
  75. */
  76. public function getToken(bool $refresh = false): array {
  77. $cacheKey = $this->getCacheKey();
  78. $cache = $this->getCache();
  79. if (!$refresh && $cache->has($cacheKey) && $result = $cache->get($cacheKey)) {
  80. return $result;
  81. }
  82. /** @var array $token */
  83. $token = $this->requestToken($this->getCredentials(), true);
  84. $this->setToken($token[$this->tokenKey], $token['expires_in'] ?? 7200);
  85. return $token;
  86. }
  87. /**
  88. * @param string $token
  89. * @param int $lifetime
  90. *
  91. * @return AccessTokenInterface
  92. *
  93. * @throws RuntimeException
  94. * @throws \Psr\SimpleCache\InvalidArgumentException|InvalidArgumentException
  95. */
  96. public function setToken(string $token, int $lifetime = 7200): AccessTokenInterface {
  97. $this->getCache()->set($this->getCacheKey(), [
  98. $this->tokenKey => $token,
  99. 'expires_in' => $lifetime
  100. ], $lifetime);
  101. if (!$this->getCache()->has($this->getCacheKey())) {
  102. throw new RuntimeException('Failed to cache access token.');
  103. }
  104. return $this;
  105. }
  106. /**
  107. * @return AccessTokenInterface
  108. *
  109. * @throws HttpException
  110. * @throws \Psr\SimpleCache\InvalidArgumentException
  111. * @throws InvalidConfigException
  112. * @throws InvalidArgumentException
  113. * @throws RuntimeException|GuzzleException
  114. */
  115. public function refresh(): AccessTokenInterface {
  116. $this->getToken(true);
  117. return $this;
  118. }
  119. /**
  120. * @param array $credentials
  121. * @param bool $toArray
  122. *
  123. * @return ResponseInterface|Collection|array|object|string
  124. *
  125. * @throws HttpException
  126. * @throws InvalidConfigException
  127. * @throws InvalidArgumentException|GuzzleException
  128. */
  129. public function requestToken(array $credentials, bool $toArray) {
  130. $response = $this->sendRequest($credentials);
  131. $result = json_decode($response->getBody()->getContents(), true);
  132. $formatted = $this->castResponseToType($response, $this->app['config']->get('response_type'));
  133. if (empty($result['data'][$this->tokenKey])) {
  134. throw new HttpException('Request access_token fail: ' . json_encode($result, JSON_UNESCAPED_UNICODE), $response, $formatted);
  135. }
  136. return $toArray ? $result['data'] : $formatted;
  137. }
  138. /**
  139. * @param RequestInterface $request
  140. * @param array $requestOptions
  141. *
  142. * @return RequestInterface
  143. *
  144. * @throws HttpException
  145. * @throws \Psr\SimpleCache\InvalidArgumentException
  146. * @throws InvalidConfigException
  147. * @throws InvalidArgumentException
  148. * @throws RuntimeException|GuzzleException
  149. */
  150. public function applyToRequest(RequestInterface $request, array $requestOptions = []): RequestInterface {
  151. parse_str($request->getUri()->getQuery(), $query);
  152. $query = http_build_query(array_merge($this->getQuery(), $query));
  153. return $request->withUri($request->getUri()->withQuery($query));
  154. }
  155. /**
  156. * 处理Post添加AccessToken
  157. * @param RequestInterface $request
  158. * @param array $requestOptions
  159. * @return RequestInterface
  160. * @throws GuzzleException
  161. * @throws HttpException
  162. * @throws InvalidArgumentException
  163. * @throws InvalidConfigException
  164. * @throws RuntimeException
  165. * @throws \Psr\SimpleCache\InvalidArgumentException
  166. * @author zhaoxiang <zhaoxiang051405@gmail.com>
  167. */
  168. public function applyToPostRequest(RequestInterface $request, array $requestOptions = []): RequestInterface {
  169. $query = $request->getBody()->getContents();
  170. $request->getBody()->rewind();
  171. $query = \GuzzleHttp\json_decode($query, true);
  172. $query = array_merge($this->getQuery(), $query);
  173. return $request->withBody(Utils::streamFor(json_encode($query)));
  174. }
  175. /**
  176. * 处理Header添加AccessToken
  177. * @param RequestInterface $request
  178. * @return RequestInterface
  179. * @throws GuzzleException
  180. * @throws HttpException
  181. * @throws InvalidArgumentException
  182. * @throws InvalidConfigException
  183. * @throws RuntimeException
  184. * @throws \Psr\SimpleCache\InvalidArgumentException
  185. */
  186. public function applyToHeaderRequest(RequestInterface $request): RequestInterface {
  187. return $request->withAddedHeader('access-token', $this->getToken()[$this->tokenKey]);
  188. }
  189. /**
  190. * Send http request.
  191. *
  192. * @param array $credentials
  193. *
  194. * @return ResponseInterface
  195. *
  196. * @throws InvalidArgumentException
  197. * @throws GuzzleException
  198. */
  199. protected function sendRequest(array $credentials): ResponseInterface {
  200. $options = [
  201. ('GET' === $this->requestMethod) ? 'query' : 'json' => $credentials,
  202. ];
  203. return $this->setHttpClient($this->app['http_client'])->request($this->getEndpoint(), $this->requestMethod, $options);
  204. }
  205. /**
  206. *
  207. * @return string
  208. * @author zhaoxiang <zhaoxiang051405@gmail.com>
  209. */
  210. protected function getCacheKey(): string {
  211. return $this->cachePrefix . md5(json_encode($this->getCredentials()));
  212. }
  213. /**
  214. * The request query will be used to add to the request.
  215. *
  216. * @return array
  217. *
  218. * @throws HttpException
  219. * @throws \Psr\SimpleCache\InvalidArgumentException
  220. * @throws InvalidConfigException
  221. * @throws InvalidArgumentException
  222. * @throws RuntimeException|GuzzleException
  223. */
  224. protected function getQuery(): array {
  225. return [$this->queryName ?? $this->tokenKey => $this->getToken()[$this->tokenKey]];
  226. }
  227. /**
  228. * @return string
  229. *
  230. * @throws InvalidArgumentException
  231. */
  232. public function getEndpoint(): string {
  233. if (empty($this->endpointToGetToken)) {
  234. throw new InvalidArgumentException('No endpoint for access token request.');
  235. }
  236. return $this->endpointToGetToken;
  237. }
  238. /**
  239. * Credential for get token.
  240. *
  241. * @return array
  242. */
  243. abstract protected function getCredentials(): array;
  244. }