AccessToken.php 7.8 KB

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