WechatOauth.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services\easywechat\oauth2\wechat;
  12. use Doctrine\Common\Cache\Cache;
  13. use Doctrine\Common\Cache\FilesystemCache;
  14. use EasyWeChat\Core\AbstractAPI;
  15. use EasyWeChat\Core\AccessToken;
  16. use EasyWeChat\Core\Exceptions\HttpException;
  17. use EasyWeChat\Core\Http;
  18. use EasyWeChat\Support\Collection;
  19. use GuzzleHttp\Psr7\Uri;
  20. use Psr\Http\Message\RequestInterface;
  21. use Symfony\Component\HttpFoundation\Request;
  22. /**
  23. * Class WechatOauth
  24. * @package crmeb\services\easywechat\oauth\wechat
  25. */
  26. class WechatOauth extends AbstractAPI
  27. {
  28. /**
  29. * 通过code获取网页授权access_token
  30. */
  31. const API_OAUTH_ACCESS_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token';
  32. /**
  33. * 检验授权凭证(access_token)是否有效
  34. */
  35. const API_OAUTH_CHECK_TOKEN = 'https://api.weixin.qq.com/sns/auth';
  36. /**
  37. * 刷新access_token
  38. */
  39. const API_OAUTH_REFRESH_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
  40. /**
  41. * 获取用户信息
  42. */
  43. const API_OAUTH_GET_USER_INFO = 'https://api.weixin.qq.com/sns/userinfo';
  44. /**
  45. * App ID.
  46. *
  47. * @var string
  48. */
  49. protected $appId;
  50. /**
  51. * App secret.
  52. *
  53. * @var string
  54. */
  55. protected $secret;
  56. /**
  57. * Cache.
  58. *
  59. * @var Cache
  60. */
  61. protected $cache;
  62. protected $openid;
  63. /**
  64. * @var Request
  65. */
  66. protected $request;
  67. /**
  68. * Query name.
  69. *
  70. * @var string
  71. */
  72. protected $queryName = 'access_token';
  73. /**
  74. * Response Json key name.
  75. *
  76. * @var string
  77. */
  78. protected $tokenJsonKey = 'access_token';
  79. /**
  80. * Response Json key name.
  81. *
  82. * @var string
  83. */
  84. protected $refreshTokenJsonKey = 'refresh_token';
  85. /**
  86. * Cache key prefix.
  87. *
  88. * @var string
  89. */
  90. protected $prefix = 'easywechat.common.oauth.access_token.';
  91. /**
  92. * WechatOauth constructor.
  93. * @param AccessToken $accessToken
  94. * @param $appId
  95. * @param $appSecret
  96. */
  97. public function __construct(AccessToken $accessToken, $appId, $appSecret)
  98. {
  99. parent::__construct($accessToken);
  100. $this->appId = $appId;
  101. $this->secret = $appSecret;
  102. }
  103. /**
  104. * @param Request $request
  105. * @return $this
  106. */
  107. public function setRequest(Request $request)
  108. {
  109. $this->request = $request;
  110. return $this;
  111. }
  112. /**
  113. * 获取code
  114. * @return mixed
  115. */
  116. public function getCode()
  117. {
  118. return $this->request->get('code');
  119. }
  120. /**
  121. * 授权获取token
  122. * @param string $code
  123. * @return false|mixed
  124. * @throws HttpException
  125. */
  126. public function oauth(string $code = '')
  127. {
  128. $params = [
  129. 'appid' => $this->appId,
  130. 'secret' => $this->secret,
  131. 'code' => $code ?: $this->getCode(),
  132. 'grant_type' => 'authorization_code',
  133. ];
  134. $http = new Http();
  135. $token = $http->parseJSON($http->get(self::API_OAUTH_ACCESS_TOKEN, $params));
  136. if (empty($token[$this->tokenJsonKey])) {
  137. throw new HttpException('Request AccessToken fail. response: ' . json_encode($token, JSON_UNESCAPED_UNICODE));
  138. }
  139. $this->setCache($token);
  140. return $token;
  141. }
  142. /**
  143. * 刷新token
  144. * @param string $refresh_token
  145. * @return false|mixed
  146. * @throws HttpException
  147. */
  148. public function refreshToken(string $refresh_token)
  149. {
  150. $params = [
  151. 'appid' => $this->appId,
  152. 'refresh_token' => $refresh_token,
  153. 'grant_type' => 'refresh_token',
  154. ];
  155. $http = new Http();
  156. $token = $http->parseJSON($http->get(self::API_OAUTH_REFRESH_TOKEN, $params));
  157. if (empty($token[$this->tokenJsonKey])) {
  158. throw new HttpException('Request AccessToken fail. response: ' . json_encode($token, JSON_UNESCAPED_UNICODE));
  159. }
  160. $this->setCache($token);
  161. return $token;
  162. }
  163. /**
  164. * 获取用户信息
  165. * @param $openId
  166. * @param string $lang
  167. * @return Collection|null
  168. * @throws HttpException
  169. */
  170. public function getUserInfo($openId, $lang = 'zh_CN')
  171. {
  172. $params = [
  173. 'openid' => $openId,
  174. 'lang' => $lang,
  175. ];
  176. $this->openid = $openId;
  177. return $this->parseJSON('get', [self::API_OAUTH_GET_USER_INFO, $params]);
  178. }
  179. /**
  180. * 获取token
  181. * @param false $forceRefresh
  182. * @return bool|mixed|string
  183. * @throws HttpException
  184. */
  185. public function getToken($forceRefresh = false)
  186. {
  187. $cacheKey = $this->prefix;
  188. $cached = $this->getCache()->fetch($cacheKey . $this->tokenJsonKey . $this->openid);
  189. if ($forceRefresh || !$cached) {
  190. $refreshCached = $this->getCache()->fetch($cacheKey . $this->refreshTokenJsonKey . $this->openid);
  191. if ($refreshCached) {
  192. $token = $this->refreshToken($refreshCached);
  193. return $token[$this->tokenJsonKey];
  194. }
  195. return '';
  196. }
  197. return $cached;
  198. }
  199. /**
  200. * 保存token信息
  201. * @param $token
  202. * @return bool
  203. */
  204. public function setCache($token)
  205. {
  206. $cacheKey = $this->prefix;
  207. // XXX: T_T... 7200 - 1500
  208. $this->getCache()->save($cacheKey . $this->tokenJsonKey . $token['openid'], $token[$this->tokenJsonKey], $token['expires_in'] - 1500);
  209. $this->getCache()->save($cacheKey . $this->refreshTokenJsonKey . $token['openid'], $token[$this->refreshTokenJsonKey], 30 * 24 * 3600);
  210. return true;
  211. }
  212. /**
  213. * Return the cache manager.
  214. *
  215. * @return \Doctrine\Common\Cache\Cache
  216. */
  217. public function getCache()
  218. {
  219. return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
  220. }
  221. /**
  222. * Attache access token to request query.
  223. *
  224. * @return \Closure
  225. */
  226. protected function accessTokenMiddleware()
  227. {
  228. return function (callable $handler) {
  229. return function (RequestInterface $request, array $options) use ($handler) {
  230. $token = $this->getToken();
  231. if (!$token) {
  232. return $handler($request, $options);
  233. }
  234. $request = $request->withUri(Uri::withQueryValue($request->getUri(), $this->queryName, $token));
  235. return $handler($request, $options);
  236. };
  237. };
  238. }
  239. }