Facebook   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 54
dl 0
loc 143
rs 10
c 0
b 0
f 0
wmc 16

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getUserInfo() 0 12 4
A accessTokenParams() 0 9 1
A parseToken() 0 7 2
A openid() 0 4 1
A getRedirectUrl() 0 13 2
A userInfo() 0 15 2
A getAvatar() 0 6 2
A call() 0 11 1
A __construct() 0 4 1
1
<?php
2
/**
3
 * fackbook 控制台 https://developers.facebook.com/apps/
4
 * Oauth开发文档:
5
 *      https://developers.facebook.com/docs/facebook-login/
6
 * 1.创建项目->并创建凭证
7
 * 2.补充基本信息
8
 * https://developers.facebook.com/apps/你的appid/settings/basic/#add-platform-button
9
 * 3.获取用户信息user_gender权限
10
 * https://developers.facebook.com/apps/你的appid/app-review/permissions/
11
 * 申请这个权限user_gender
12
 */
13
namespace tinymeng\OAuth2\Gateways;
14
15
use tinymeng\OAuth2\Connector\Gateway;
16
use tinymeng\OAuth2\Exception\OAuthException;
17
use tinymeng\OAuth2\Helper\ConstCode;
18
use tinymeng\OAuth2\Helper\Str;
19
20
/**
21
 * Class Facebook
22
 * @package tinymeng\OAuth2\Gateways
23
 * @Author: TinyMeng <[email protected]>
24
 * @Created: 2020/7/29
25
 */
26
class Facebook extends Gateway
27
{
28
    const API_BASE            = 'https://graph.facebook.com/v3.1/';
29
    protected $AuthorizeURL   = 'https://www.facebook.com/v3.1/dialog/oauth';
30
    protected $AccessTokenURL = 'oauth/access_token';
31
32
    /**
33
     * @param $config
34
     * @throws OAuthException
35
     */
36
    public function __construct($config)
37
    {
38
        parent::__construct($config);
39
        $this->AccessTokenURL = static::API_BASE.$this->AccessTokenURL;
40
    }
41
42
    /**
43
     * 得到跳转地址
44
     */
45
    public function getRedirectUrl()
46
    {
47
        //存储state
48
        $this->saveState();
49
        //登录参数
50
        $params = [
51
            'response_type' => $this->config['response_type'],
52
            'client_id'     => $this->config['app_id'],
53
            'redirect_uri'  => $this->config['callback'],
54
            'scope'         => $this->config['scope'],
55
            'state'         => $this->config['state'] ?: Str::random(),
56
        ];
57
        return $this->AuthorizeURL . '?' . http_build_query($params);
58
    }
59
60
    /**
61
     * 获取当前授权用户的openid标识
62
     */
63
    public function openid()
64
    {
65
        $userInfo = $this->userInfo();
66
        return $userInfo['openid'];
67
    }
68
69
    /**
70
     * 获取格式化后的用户信息
71
     */
72
    public function userInfo()
73
    {
74
        $result = $this->getUserInfo();
75
76
        $userInfo = [
77
            'open_id'  => $result['id'],
78
            'access_token'=> $this->token['access_token'] ?? '',
79
            'union_id'=> $result['id'],
80
            'channel' => ConstCode::TYPE_FACEBOOK,
81
            'nickname'    => $result['name'],
82
            'gender'  => isset($result['gender']) ? $this->getGender($result['gender']) : ConstCode::GENDER,
83
            'avatar'  => $this->getAvatar($result),
84
            'native'   => $result,
85
        ];
86
        return $userInfo;
87
    }
88
89
    /**
90
     * 获取原始接口返回的用户信息
91
     */
92
    public function getUserInfo()
93
    {
94
        if($this->type == 'app'){//App登录
95
            if(!isset($_REQUEST['access_token']) ){
96
                throw new OAuthException("Facebook APP登录 需要传输access_token参数! ");
97
            }
98
            $this->token['access_token'] = $_REQUEST['access_token'];
99
        }else {
100
            $this->getToken();
101
        }
102
        $fields = isset($this->config['fields']) ? $this->config['fields'] : 'id,name,gender,picture.width(400)';
103
        return $this->call('me', ['access_token' => $this->token['access_token'], 'fields' => $fields], 'GET');
104
    }
105
106
    /**
107
     * 发起请求
108
     *
109
     * @param string $api
110
     * @param array $params
111
     * @param string $method
112
     * @return array
113
     */
114
    private function call($api, $params = [], $method = 'GET')
115
    {
116
        $method  = strtoupper($method);
117
        $request = [
118
            'method' => $method,
119
            'uri'    => self::API_BASE . $api,
120
        ];
121
122
        $data = $this->$method($request['uri'], $params);
123
124
        return json_decode($data, true);
125
    }
126
127
    /**
128
     * Description:  重写 获取的AccessToken请求参数
129
     * @author: JiaMeng <[email protected]>
130
     * Updater:
131
     * @return array
132
     */
133
    protected function accessTokenParams()
134
    {
135
        $params = [
136
            'client_id'     => $this->config['app_id'],
137
            'client_secret' => $this->config['app_secret'],
138
            'code'          => $this->getCode(),
139
            'redirect_uri'  => $this->config['callback'],
140
        ];
141
        return $params;
142
    }
143
144
    /**
145
     * 解析access_token方法请求后的返回值
146
     * @param string $token 获取access_token的方法的返回值
147
     */
148
    protected function parseToken($token)
149
    {
150
        $token = json_decode($token, true);
151
        if (isset($token['error'])) {
152
            throw new OAuthException($token['error']['message']);
153
        }
154
        return $token;
155
    }
156
157
    /**
158
     * 获取用户头像
159
     *
160
     * @param array $result
161
     * @return string
162
     */
163
    private function getAvatar($result)
164
    {
165
        if (isset($result['picture']['data']['url'])) {
166
            return $result['picture']['data']['url'];
167
        }
168
        return '';
169
    }
170
}
171