Completed
Pull Request — master (#33)
by
unknown
02:48 queued 52s
created

CorpWechatProvider::getUserByToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/socialite.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Overtrue\Socialite\Providers;
13
14
use Overtrue\Socialite\AccessToken;
15
use Overtrue\Socialite\AccessTokenInterface;
16
use Overtrue\Socialite\InvalidArgumentException;
17
use Overtrue\Socialite\ProviderInterface;
18
use Overtrue\Socialite\User;
19
20
/**
21
 * Class WeChatProvider.
22
 *
23
 * @link http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html [WeChat - 公众平台OAuth文档]
24
 * @link https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN [网站应用微信登录开发指南]
25
 */
26
class CorpWechatProvider extends AbstractProvider implements ProviderInterface
27
{
28
    /**
29
     * The base url of WeChat API.
30
     *
31
     * @var string
32
     */
33
    protected $userBaseInfoApi = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo';
34
    protected $userInfoApi = 'https://qyapi.weixin.qq.com/cgi-bin/user/get';
35
    protected $accessTokenApi = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken';
36
    protected $oauthApi = 'https://open.weixin.qq.com/connect/oauth2/authorize';
37
38
    /**
39
     * {@inheritdoc}.
40
     */
41
    protected $openId;
42
43
    /**
44
     * {@inheritdoc}.
45
     */
46
    protected $scopes = ['snsapi_base'];
47
48
    /**
49
     * Indicates if the session state should be utilized.
50
     *
51
     * @var bool
52
     */
53
    protected $stateless = true;
54
55
    /**
56
     * {@inheritdoc}.
57
     */
58
    protected function getAuthUrl($state)
59
    {
60
        return $this->buildAuthUrlFromBase($this->oauthApi, $state);
61
    }
62
63
    /**
64
     * {@inheritdoc}.
65
     */
66
    protected function buildAuthUrlFromBase($url, $state)
67
    {
68
        $query = http_build_query($this->getCodeFields($state), '', '&', $this->encodingType);
69
        $url = $url.'?'.$query.'#wechat_redirect';
70
71
        return $url;
72
    }
73
74
    /**
75
     * {@inheritdoc}.
76
     */
77 View Code Duplication
    protected function getCodeFields($state = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
    {
79
        $result = array_merge([
80
            'appid' => $this->clientId,
81
            'redirect_uri' => $this->redirectUrl,
82
            'response_type' => 'code',
83
            'scope' => $this->formatScopes($this->scopes, $this->scopeSeparator),
84
            'state' => $state ?: md5(time()),
85
        ], $this->parameters);
86
87
        return $result;
88
    }
89
90
    /**
91
     * 获取 access token的路径.
92
     */
93
    protected function getTokenUrl()
94
    {
95
        return $this->accessTokenApi;
96
    }
97
98
    /**
99
     * {@inheritdoc}.
100
     */
101
    protected function getUserByToken(AccessTokenInterface $token)
102
    {
103
        if (empty($token['UserId'])) {
104
            throw new InvalidArgumentException('UserId of AccessToken is required.');
105
        }
106
107
        $response = $this->getHttpClient()->get($this->userInfoApi, [
108
            'query' => [
109
                'access_token' => $token->getToken(),
110
                'userid' => $token['UserId'],
111
            ],
112
        ]);
113
114
        return json_decode($response->getBody(), true);
115
    }
116
117
    /**
118
     * {@inheritdoc}.
119
     */
120
    protected function mapUserToObject(array $user)
121
    {
122
        return new User([
123
            'userid' => $this->arrayItem($user, 'userid'),
124
            'name' => $this->arrayItem($user, 'name'),
125
            'avatar' => $this->arrayItem($user, 'avatar'),
126
            'mobile' => $this->arrayItem($user, 'mobile'),
127
            'department' => $this->arrayItem($user, 'department'),
128
            'gender' => $this->arrayItem($user, 'gender'),
129
            'email' => $this->arrayItem($user, 'email'),
130
            'status' => $this->arrayItem($user, 'status'),
131
        ]);
132
    }
133
134
    /**
135
     * 构建access_token 的参数列表, 分为两种情况一种是 获取access token, 另一种是直接获取userid.
136
     */
137
    protected function getTokenFields($code = false)
138
    {
139
        if (!$code) {
140
            return [
141
                'corpid' => $this->clientId,
142
                'corpsecret' => $this->clientSecret,
143
            ];
144
        }
145
146
        return [
147
            'access_token' => $this->config['longlive_access_token'],
148
            'code' => $code,
149
        ];
150
    }
151
152
    /**
153
     * 原始微信oauth 应该是返回 access token + openid
154
     * 企业号因为用的是7200秒的, 所以需要支持从外部去获取access_token 不会冲突  要返回 userid.
155
     */
156
    public function getAccessToken($code)
157
    {
158
        //没有指定则自己获取
159
        if (!$this->config['longlive_access_token']) {
160
            $this->config['longlive_access_token'] = $this->getLongiveAccessToken();
161
        }
162
        $param = $this->getTokenFields($code);
163
        $response = $this->getHttpClient()->get($this->userBaseInfoApi, [
164
            'query' => $param,
165
        ]);
166
        $content = $response->getBody()->getContents();
167
        $content = json_decode($content, true);
168
        $content['access_token'] = $this->config['longlive_access_token'];
169
        $token = $this->parseAccessToken($content);
170
171
        return $token;
172
    }
173
    
174
    // !!应该尽量不要调用, 除非 单独与overture/wechat使用, 否则同时获取accesstoken, 会冲突
175
    public function getLongiveAccessToken($forse_refresh = false)
0 ignored issues
show
Unused Code introduced by
The parameter $forse_refresh is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
176
    {
177
        $getTokenUrl = $this->getTokenUrl();
178
        $response = $this->getHttpClient()->get($getTokenUrl, [
179
            'query' => $this->getTokenFields(),
180
        ]);
181
        $content = $response->getBody()->getContents();
182
        $token = $this->parseAccessToken($content);
183
184
        return $token['access_token'];
185
    }
186
187
    /**
188
     * Remove the fucking callback parentheses.
189
     *
190
     * @param mixed $response
191
     *
192
     * @return string
193
     */
194
    protected function removeCallback($response)
195
    {
196
        if (strpos($response, 'callback') !== false) {
197
            $lpos = strpos($response, '(');
198
            $rpos = strrpos($response, ')');
199
            $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
200
        }
201
202
        return $response;
203
    }
204
}
205