Completed
Pull Request — master (#48)
by mingyoung
02:00
created

WeChatProvider::isOpenPlatform()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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
        return $this->baseUrl.'/oauth2/access_token';
128
    }
129
130
    /**
131
     * {@inheritdoc}.
132
     */
133
    protected function getUserByToken(AccessTokenInterface $token)
134
    {
135
        $scopes = explode(',', $token->getAttribute('scope', ''));
136
137
        if (in_array('snsapi_base', $scopes)) {
138
            return $token->toArray();
139
        }
140
141
        if (empty($token['openid'])) {
142
            throw new InvalidArgumentException('openid of AccessToken is required.');
143
        }
144
145
        $language = $this->withCountryCode ? null : (isset($this->parameters['lang']) ? $this->parameters['lang'] : 'zh_CN');
146
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
155
        return json_decode($response->getBody(), true);
156
    }
157
158
    /**
159
     * {@inheritdoc}.
160
     */
161
    protected function mapUserToObject(array $user)
162
    {
163
        return new User([
164
            'id' => $this->arrayItem($user, 'openid'),
165
            'name' => $this->arrayItem($user, 'nickname'),
166
            'nickname' => $this->arrayItem($user, 'nickname'),
167
            'avatar' => $this->arrayItem($user, 'headimgurl'),
168
            'email' => null,
169
        ]);
170
    }
171
172
    /**
173
     * {@inheritdoc}.
174
     */
175
    protected function getTokenFields($code)
176
    {
177
        return [
178
            'appid' => $this->clientId,
179
            'secret' => $this->clientSecret,
180
            'code' => $code,
181
            'grant_type' => 'authorization_code',
182
        ];
183
    }
184
185
    /**
186
     * Remove the fucking callback parentheses.
187
     *
188
     * @param mixed $response
189
     *
190
     * @return string
191
     */
192 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...
193
    {
194
        if (strpos($response, 'callback') !== false) {
195
            $lpos = strpos($response, '(');
196
            $rpos = strrpos($response, ')');
197
            $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
198
        }
199
200
        return $response;
201
    }
202
}
203