Completed
Push — master ( 42b4ce...8ef5d4 )
by Carlos
04:00
created

WeChatProvider::parseAccessToken()   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 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 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
     * {@inheritdoc}.
54
     */
55
    protected function getAuthUrl($state)
56
    {
57
        $path = 'oauth2/authorize';
58
59
        if (in_array('snsapi_login', $this->scopes)) {
60
            $path = 'qrconnect';
61
        }
62
63
        return $this->buildAuthUrlFromBase("https://open.weixin.qq.com/connect/{$path}", $state);
64
    }
65
66
    /**
67
     * {@inheritdoc}.
68
     */
69
    protected function buildAuthUrlFromBase($url, $state)
70
    {
71
        $query = http_build_query($this->getCodeFields($state), '', '&', $this->encodingType);
72
73
        return $url.'?'.$query.'#wechat_redirect';
74
    }
75
76
    /**
77
     * {@inheritdoc}.
78
     */
79
    protected function getCodeFields($state = null)
80
    {
81
        return array_merge([
82
            'appid'         => $this->clientId,
83
            'redirect_uri'  => $this->redirectUrl,
84
            'response_type' => 'code',
85
            'scope'         => $this->formatScopes($this->scopes, $this->scopeSeparator),
86
            'state'         => $state ?: md5(time()),
87
        ], $this->parameters);
88
    }
89
90
    /**
91
     * {@inheritdoc}.
92
     */
93
    protected function getTokenUrl()
94
    {
95
        return $this->baseUrl.'/oauth2/access_token';
96
    }
97
98
    /**
99
     * {@inheritdoc}.
100
     */
101
    protected function getUserByToken(AccessTokenInterface $token)
102
    {
103
        $scopes = explode(',', $token->getAttribute('scope', ''));
104
105
        if (in_array('snsapi_base', $scopes)) {
106
            return $token->toArray();
107
        }
108
109
        if (empty($token['openid'])) {
110
            throw new InvalidArgumentException('openid of AccessToken is required.');
111
        }
112
113
        $response = $this->getHttpClient()->get($this->baseUrl.'/userinfo', [
114
            'query' => [
115
                'access_token' => $token->getToken(),
116
                'openid'       => $token['openid'],
117
                'lang'         => 'zh_CN',
118
            ],
119
        ]);
120
121
        return json_decode($response->getBody(), true);
122
    }
123
124
    /**
125
     * {@inheritdoc}.
126
     */
127
    protected function mapUserToObject(array $user)
128
    {
129
        return new User([
130
            'id'       => $this->arrayItem($user, 'openid'),
131
            'name'     => $this->arrayItem($user, 'nickname'),
132
            'nickname' => $this->arrayItem($user, 'nickname'),
133
            'avatar'   => $this->arrayItem($user, 'headimgurl'),
134
            'email'    => null,
135
        ]);
136
    }
137
138
    /**
139
     * {@inheritdoc}.
140
     */
141
    protected function getTokenFields($code)
142
    {
143
        return [
144
            'appid'      => $this->clientId,
145
            'secret'     => $this->clientSecret,
146
            'code'       => $code,
147
            'grant_type' => 'authorization_code',
148
        ];
149
    }
150
151
    /**
152
     * {@inheritdoc}.
153
     */
154 View Code Duplication
    public function getAccessToken($code)
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...
155
    {
156
        $response = $this->getHttpClient()->get($this->getTokenUrl(), [
157
            'query' => $this->getTokenFields($code),
158
        ]);
159
160
        return $this->parseAccessToken($response->getBody()->getContents());
0 ignored issues
show
Documentation introduced by
$response->getBody()->getContents() is of type string, but the function expects a object<Psr\Http\Message\StreamInterface>|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
161
    }
162
163
    /**
164
     * Remove the fucking callback parentheses.
165
     *
166
     * @param mixed $response
167
     *
168
     * @return string
169
     */
170 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...
171
    {
172
        if (strpos($response, 'callback') !== false) {
173
            $lpos     = strpos($response, '(');
174
            $rpos     = strrpos($response, ')');
175
            $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
176
        }
177
178
        return $response;
179
    }
180
}
181