AccessToken.php 8.2 KB

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