Completed
Push — master ( 28d852...e749ea )
by Carlos
02:58
created

WeChatProvider::withCountryCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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