AccessToken.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 string
  50. */
  51. protected $tokenKey = 'access_token';
  52. /**
  53. * @var string
  54. */
  55. protected $cachePrefix = 'easywechat.kernel.access_token.';
  56. /**
  57. * AccessToken constructor.
  58. *
  59. * @param \EasyWeChat\Kernel\ServiceContainer $app
  60. */
  61. public function __construct(ServiceContainer $app)
  62. {
  63. $this->app = $app;
  64. }
  65. public function getLastToken(): array
  66. {
  67. return $this->token;
  68. }
  69. /**
  70. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  71. * @throws \Psr\SimpleCache\InvalidArgumentException
  72. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  73. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  74. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  75. */
  76. public function getRefreshedToken(): array
  77. {
  78. return $this->getToken(true);
  79. }
  80. /**
  81. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  82. * @throws \Psr\SimpleCache\InvalidArgumentException
  83. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  84. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  85. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  86. */
  87. public function getToken(bool $refresh = false): array
  88. {
  89. $cacheKey = $this->getCacheKey();
  90. $cache = $this->getCache();
  91. if (!$refresh && $cache->has($cacheKey) && $result = $cache->get($cacheKey)) {
  92. return $result;
  93. }
  94. /** @var array $token */
  95. $token = $this->requestToken($this->getCredentials(), true);
  96. $this->setToken($token[$this->tokenKey], $token['expires_in'] ?? 7200);
  97. $this->token = $token;
  98. $this->app->events->dispatch(new Events\AccessTokenRefreshed($this));
  99. return $token;
  100. }
  101. /**
  102. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  103. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  104. * @throws \Psr\SimpleCache\InvalidArgumentException
  105. */
  106. public function setToken(string $token, int $lifetime = 7200): AccessTokenInterface
  107. {
  108. $this->getCache()->set($this->getCacheKey(), [
  109. $this->tokenKey => $token,
  110. 'expires_in' => $lifetime,
  111. ], $lifetime);
  112. if (!$this->getCache()->has($this->getCacheKey())) {
  113. throw new RuntimeException('Failed to cache access token.');
  114. }
  115. return $this;
  116. }
  117. /**
  118. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  119. * @throws \Psr\SimpleCache\InvalidArgumentException
  120. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  121. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  122. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  123. */
  124. public function refresh(): AccessTokenInterface
  125. {
  126. $this->getToken(true);
  127. return $this;
  128. }
  129. /**
  130. * @param bool $toArray
  131. *
  132. * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
  133. *
  134. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  135. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  136. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  137. */
  138. public function requestToken(array $credentials, $toArray = false)
  139. {
  140. $response = $this->sendRequest($credentials);
  141. $result = json_decode($response->getBody()->getContents(), true);
  142. $formatted = $this->castResponseToType($response, $this->app['config']->get('response_type'));
  143. if (empty($result[$this->tokenKey])) {
  144. throw new HttpException('Request access_token fail: '.json_encode($result, JSON_UNESCAPED_UNICODE), $response, $formatted);
  145. }
  146. return $toArray ? $result : $formatted;
  147. }
  148. /**
  149. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  150. * @throws \Psr\SimpleCache\InvalidArgumentException
  151. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  152. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  153. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  154. */
  155. public function applyToRequest(RequestInterface $request, array $requestOptions = []): RequestInterface
  156. {
  157. parse_str($request->getUri()->getQuery(), $query);
  158. $query = http_build_query(array_merge($this->getQuery(), $query));
  159. return $request->withUri($request->getUri()->withQuery($query));
  160. }
  161. /**
  162. * Send http request.
  163. *
  164. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  165. * @throws \GuzzleHttp\Exception\GuzzleException
  166. */
  167. protected function sendRequest(array $credentials): ResponseInterface
  168. {
  169. $options = [
  170. ('GET' === $this->requestMethod) ? 'query' : 'json' => $credentials,
  171. ];
  172. return $this->setHttpClient($this->app['http_client'])->request($this->getEndpoint(), $this->requestMethod, $options);
  173. }
  174. /**
  175. * @return string
  176. */
  177. protected function getCacheKey()
  178. {
  179. return $this->cachePrefix.md5(json_encode($this->getCredentials()));
  180. }
  181. /**
  182. * The request query will be used to add to the request.
  183. *
  184. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  185. * @throws \Psr\SimpleCache\InvalidArgumentException
  186. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  187. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  188. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  189. */
  190. protected function getQuery(): array
  191. {
  192. return [$this->queryName ?? $this->tokenKey => $this->getToken()[$this->tokenKey]];
  193. }
  194. /**
  195. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  196. */
  197. public function getEndpoint(): string
  198. {
  199. if (empty($this->endpointToGetToken)) {
  200. throw new InvalidArgumentException('No endpoint for access token request.');
  201. }
  202. return $this->endpointToGetToken;
  203. }
  204. /**
  205. * @return string
  206. */
  207. public function getTokenKey()
  208. {
  209. return $this->tokenKey;
  210. }
  211. /**
  212. * Credential for get token.
  213. */
  214. abstract protected function getCredentials(): array;
  215. }