WeChatProvider.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /*
  3. * This file is part of the overtrue/socialite.
  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 Overtrue\Socialite\Providers;
  11. use Overtrue\Socialite\AccessToken;
  12. use Overtrue\Socialite\AccessTokenInterface;
  13. use Overtrue\Socialite\InvalidArgumentException;
  14. use Overtrue\Socialite\ProviderInterface;
  15. use Overtrue\Socialite\User;
  16. use Overtrue\Socialite\WeChatComponentInterface;
  17. /**
  18. * Class WeChatProvider.
  19. *
  20. * @see http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html [WeChat - 公众平台OAuth文档]
  21. * @see https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN [网站应用微信登录开发指南]
  22. */
  23. class WeChatProvider extends AbstractProvider implements ProviderInterface
  24. {
  25. /**
  26. * The base url of WeChat API.
  27. *
  28. * @var string
  29. */
  30. protected $baseUrl = 'https://api.weixin.qq.com/sns';
  31. /**
  32. * {@inheritdoc}.
  33. */
  34. protected $openId;
  35. /**
  36. * {@inheritdoc}.
  37. */
  38. protected $scopes = ['snsapi_login'];
  39. /**
  40. * Indicates if the session state should be utilized.
  41. *
  42. * @var bool
  43. */
  44. protected $stateless = true;
  45. /**
  46. * Return country code instead of country name.
  47. *
  48. * @var bool
  49. */
  50. protected $withCountryCode = false;
  51. /**
  52. * @var WeChatComponentInterface
  53. */
  54. protected $component;
  55. /**
  56. * Return country code instead of country name.
  57. *
  58. * @return $this
  59. */
  60. public function withCountryCode()
  61. {
  62. $this->withCountryCode = true;
  63. return $this;
  64. }
  65. /**
  66. * WeChat OpenPlatform 3rd component.
  67. *
  68. * @param WeChatComponentInterface $component
  69. *
  70. * @return $this
  71. */
  72. public function component(WeChatComponentInterface $component)
  73. {
  74. $this->scopes = ['snsapi_base'];
  75. $this->component = $component;
  76. return $this;
  77. }
  78. /**
  79. * {@inheritdoc}.
  80. */
  81. public function getAccessToken($code)
  82. {
  83. $response = $this->getHttpClient()->get($this->getTokenUrl(), [
  84. 'headers' => ['Accept' => 'application/json'],
  85. 'query' => $this->getTokenFields($code),
  86. ]);
  87. return $this->parseAccessToken($response->getBody());
  88. }
  89. /**
  90. * {@inheritdoc}.
  91. */
  92. protected function getAuthUrl($state)
  93. {
  94. $path = 'oauth2/authorize';
  95. if (in_array('snsapi_login', $this->scopes)) {
  96. $path = 'qrconnect';
  97. }
  98. return $this->buildAuthUrlFromBase("https://open.weixin.qq.com/connect/{$path}", $state);
  99. }
  100. /**
  101. * {@inheritdoc}.
  102. */
  103. protected function buildAuthUrlFromBase($url, $state)
  104. {
  105. $query = http_build_query($this->getCodeFields($state), '', '&', $this->encodingType);
  106. return $url.'?'.$query.'#wechat_redirect';
  107. }
  108. /**
  109. * {@inheritdoc}.
  110. */
  111. protected function getCodeFields($state = null)
  112. {
  113. if ($this->component) {
  114. $this->with(['component_appid' => $this->component->getAppId()]);
  115. }
  116. return array_merge([
  117. 'appid' => $this->clientId,
  118. 'redirect_uri' => $this->redirectUrl,
  119. 'response_type' => 'code',
  120. 'scope' => $this->formatScopes($this->scopes, $this->scopeSeparator),
  121. 'state' => $state ?: md5(time()),
  122. ], $this->parameters);
  123. }
  124. /**
  125. * {@inheritdoc}.
  126. */
  127. protected function getTokenUrl()
  128. {
  129. if ($this->component) {
  130. return $this->baseUrl.'/oauth2/component/access_token';
  131. }
  132. return $this->baseUrl.'/oauth2/access_token';
  133. }
  134. /**
  135. * {@inheritdoc}.
  136. */
  137. protected function getUserByToken(AccessTokenInterface $token)
  138. {
  139. $scopes = explode(',', $token->getAttribute('scope', ''));
  140. if (in_array('snsapi_base', $scopes)) {
  141. return $token->toArray();
  142. }
  143. if (empty($token['openid'])) {
  144. throw new InvalidArgumentException('openid of AccessToken is required.');
  145. }
  146. $language = $this->withCountryCode ? null : (isset($this->parameters['lang']) ? $this->parameters['lang'] : 'zh_CN');
  147. $response = $this->getHttpClient()->get($this->baseUrl.'/userinfo', [
  148. 'query' => array_filter([
  149. 'access_token' => $token->getToken(),
  150. 'openid' => $token['openid'],
  151. 'lang' => $language,
  152. ]),
  153. ]);
  154. return json_decode($response->getBody(), true);
  155. }
  156. /**
  157. * {@inheritdoc}.
  158. */
  159. protected function mapUserToObject(array $user)
  160. {
  161. return new User([
  162. 'id' => $this->arrayItem($user, 'openid'),
  163. 'name' => $this->arrayItem($user, 'nickname'),
  164. 'nickname' => $this->arrayItem($user, 'nickname'),
  165. 'avatar' => $this->arrayItem($user, 'headimgurl'),
  166. 'email' => null,
  167. ]);
  168. }
  169. /**
  170. * {@inheritdoc}.
  171. */
  172. protected function getTokenFields($code)
  173. {
  174. return array_filter([
  175. 'appid' => $this->clientId,
  176. 'secret' => $this->clientSecret,
  177. 'component_appid' => $this->component ? $this->component->getAppId() : null,
  178. 'component_access_token' => $this->component ? $this->component->getToken() : null,
  179. 'code' => $code,
  180. 'grant_type' => 'authorization_code',
  181. ]);
  182. }
  183. /**
  184. * Remove the fucking callback parentheses.
  185. *
  186. * @param mixed $response
  187. *
  188. * @return string
  189. */
  190. protected function removeCallback($response)
  191. {
  192. if (strpos($response, 'callback') !== false) {
  193. $lpos = strpos($response, '(');
  194. $rpos = strrpos($response, ')');
  195. $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
  196. }
  197. return $response;
  198. }
  199. }