1+ <?php
2+ /**
3+ * @link http://www.tintsoft.com/
4+ * @copyright Copyright (c) 2012 TintSoft Technology Co. Ltd.
5+ * @license http://www.tintsoft.com/license/
6+ */
7+
8+ namespace xutl \wechat \oauth ;
9+
10+ use Yii ;
11+ use yii \authclient \OAuth2 ;
12+ use yii \web \HttpException ;
13+
14+ /**
15+ * 微信小程序定制
16+ * @package xutl\wechat\oauth
17+ */
18+ class MiniOAuth extends OAuth2
19+ {
20+ /**
21+ * @inheritdoc
22+ */
23+ public $ tokenUrl = 'https://api.weixin.qq.com/sns/jscode2session ' ;
24+
25+ /**
26+ * @var bool 是否使用openid
27+ */
28+ public $ useOpenId = true ;
29+
30+ /**
31+ * 获取Token
32+ * @param string $authCode
33+ * @param array $params
34+ * @return \yii\authclient\OAuthToken
35+ * @throws \yii\authclient\InvalidResponseException
36+ */
37+ public function fetchAccessToken ($ authCode , array $ params = [])
38+ {
39+ $ defaultParams = [
40+ 'appid ' => $ this ->clientId ,
41+ 'secret ' => $ this ->clientSecret ,
42+ 'js_code ' => $ authCode ,
43+ 'grant_type ' => 'authorization_code '
44+ ];
45+
46+ $ request = $ this ->createRequest ()
47+ ->setMethod ('GET ' )
48+ ->setUrl ($ this ->tokenUrl )
49+ ->setData (array_merge ($ defaultParams , $ params ));
50+
51+ $ response = $ this ->sendRequest ($ request );
52+
53+ $ token = $ this ->createToken (['params ' => $ response ]);
54+ $ this ->setAccessToken ($ token );
55+
56+ return $ token ;
57+ }
58+
59+ /**
60+ * Creates token from its configuration.
61+ * @param array $tokenConfig token configuration.
62+ * @return \yii\authclient\OAuthToken token instance.
63+ */
64+ protected function createToken (array $ tokenConfig = [])
65+ {
66+ $ tokenConfig ['tokenParamKey ' ] = 'session_key ' ;
67+
68+ return parent ::createToken ($ tokenConfig );
69+ }
70+
71+ /**
72+ * @inheritdoc
73+ */
74+ protected function defaultNormalizeUserAttributeMap ()
75+ {
76+ return [
77+ 'id ' => $ this ->useOpenId ? 'openid ' : 'unionid ' ,
78+ ];
79+ }
80+
81+ /**
82+ * @inheritdoc
83+ */
84+ protected function initUserAttributes ()
85+ {
86+ return [];
87+ }
88+ }
0 commit comments