Completed
Pull Request — master (#67)
by mingyoung
01:30
created

WeChatProvider::component()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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