AccessToken.php 7.9 KB

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