FACEBOOK登录

10 篇文章 0 订阅
该博客详细介绍了如何在PHP环境中实现Facebook的OAuth登录认证。通过Kuxin框架的Oauth类和Facebook子类,实现了从授权页面跳转、获取access_token、解析token信息、获取用户信息等一系列步骤,确保用户能够通过Facebook账号安全地登录和注册到网站。代码中包含了关键的API接口地址、参数设置以及错误处理机制。
摘要由CSDN通过智能技术生成

FACEBOOK登录

相关设置:https://developers.facebook.com/apps

在这里插入图片描述

调用方法

    public function third()
    {
        if (empty($type = Input::get('type', [ 'facebook', 'tuite' ]))) {
            return $this->error('参数错误');
        }
        if (!Config::get('oauth.power')) {
            return $this->error('未开启三方登录');
        }
        $config = Config::get("oauth.{$type}");
        if (empty($config['appid']) || empty($config['appsecret'])) {
            return $this->error('三方登录配置错误');
        }
        $callback = Config::get('siteurl') . Url::build('user.auth.third', [ 'type' => $type ]);
      
        if (Input::has('code') && ($code = Input::get('code', 'str', ''))) {
            $oauth = Oauth::getInstance($type);

            $token = $oauth->getAccessToken($code, $callback); 
            
            if (!is_array($token)) return $this->error($token);
            
            $thirdInfo     = $oauth->getInfo();
           
            $openId   = $thirdInfo['id'];
            $nickname = $thirdInfo['name'];
            $avatar   = $thirdInfo['avatar'];
            $email    = $thirdInfo['email'];
             
            $unionLogin = UnionLogin::I()->where([ 'type' => $type, 'openid' => $openId ])->find();
             
            if ($unionLogin && $unionLogin['user_id']) {
                if (!($info = UserModel::I()->getFullInfo($unionLogin['user_id'])) || !$info['status']) {
                    return $this->error('您帐号已经被禁用了');
                }
                UserModel::I()->setLoginStatus($info['id'], $info['name']); 
                $this->redirect(Url::build('user.index.index'));
            } else {
                if ($this->isLogin) {
                    UserModel::I()->oauthBind($this->userInfo['id'], $type, $openId);
                    $this->redirect(Url::build('user.info.index'));
                } else {
                    $username = strtoupper($type) . "_".date ( 's' ).sp_random_string(6); 

                    $res = UserModel::I()->add($username,  $avatar, $email);

                    if (is_numeric($res)) {  
                        UserModel::I()->oauthBind($res, $type, $openId);
                        return $this->message('注册成功', SUCCESS, Url::build('user.info.index')); 
                    } else {
                        return $this->message($res, ERROR, '#back#');
                    }
                }
            }
        } else {
            $this->redirect(Oauth::getInstance($type)->authorize($callback));
        }
    }
 
认证类
<?php

namespace Kuxin\Oauth;

use Kuxin\Config;
use Kuxin\Helper\Http;
use Kuxin\Loader;

abstract class Oauth
{

    /**
     * 申请应用时分配的app_key
     *
     * @var string
     */
    protected $appid = '';

    /**
     * 申请应用时分配的 app_secret
     *
     * @var string
     */
    protected $appsecret = '';

    /**
     * 授权类型 response_type 目前只能为code
     *
     * @var string
     */
    protected $responseType = 'code';

    /**
     * grant_type 目前只能为 authorization_code
     *
     * @var string
     */
    protected $grantType = 'authorization_code';

    /**
     * 获取request_code的额外参数
     *
     * @var array
     */
    protected $authorizeParam = [];
    /**
     * 获取accesstoekn时候的附加参数
     *
     * @var array
     */
    protected $getTokenParam = [];

    /**
     * 获取request_code请求的URL
     *
     * @var string
     */
    protected $getRequestCodeURL = '';

    /**
     * 获取access_token请求的URL
     *
     * @var string
     */
    protected $getAccessTokenURL = '';

    /**
     * API根路径
     *
     * @var string
     */
    protected $apiBase = '';

    /**
     * 授权后获取到的TOKEN信息
     *
     * @var array
     */
    protected $token = null;
    /**
     * 授权后的用户id
     *
     * @var null
     */
    protected $openid = null;
    /**
     * 授权后的用户id
     *
     * @var null
     */
    protected $type = null;

    /**
     * 构造函数
     *
     * @param array $config
     * @param null $token
     */
    public function __construct(array $config, $token = null)
    {
        $this->appid     = $config['appid'];
        $this->appsecret = $config['appsecret'];
        $this->token     = $token;
        $this->type     = '';
        Config::set('user_agent', '');
    }

    /**
     * @param      $type
     * @param null $token
     * @return static
     */
    public static function getInstance($type, $token = null)
    {
        $config    = Config::get("oauth.{$type}");
        
        $classname = '\\Kuxin\\Oauth\\' . $type;
        return Loader::instance($classname, [ $config, $token ]);
    }

    /**
     * 前往认证页
     *
     * @param $url
     * @return string
     */
    public function authorize($url)
    {
        $query = parse_url($url)['query']; 
        $param = [
            "response_type" => $this->responseType, 
            "redirect_uri"  => $url,
            "state"         => time(),
        ];
        $param['client_id'] = $this->appid; 
        $param = array_merge($param, $this->authorizeParam);

        if (strpos($this->getRequestCodeURL, '?') === false) {
            return $this->getRequestCodeURL . '?' . http_build_query($param);
        } else {
            return $this->getRequestCodeURL . '&' . http_build_query($param);
        }
    }

    /**
     * 获取access token
     *
     * @param $code
     * @param $url
     * @return string
     */
    public function getAccessToken($code, $url)
    {
        $param    = [
            "grant_type"    => $this->grantType, 
            "redirect_uri"  => $url,
            "client_secret" => $this->appsecret,
            "code"          => $code,
        ];
        $query = parse_url($url)['query'];
        if ($query == 'type=weixin'){
           $param['appid'] = $this->appid; 
        }else {
           $param['client_id'] = $this->appid; 
        }

        $param    = array_merge($param, $this->getTokenParam);
        $response = Http::post($this->getAccessTokenURL, http_build_query($param));
        return $this->parseToken($response);
    }


    /**
     * @param string $api 接口名
     * @param string $param 参数
     * @param string $method 是否POST
     * @param bool $multi 是否上传文件
     * @return array
     */
    abstract protected function call($api, $param = '', $method = 'GET', $multi = false);

    /**
     * 抽象方法 解析access_token方法请求后的返回值
     *
     * @param 待处理内容
     * @return string
     */
    abstract protected function parseToken($result);

    /**
     * 抽象方法  获取当前授权用户的标识
     *
     * @return mixed
     */
    abstract public function getOpenId();
    /**
     * 抽象方法  获取当前授权用户的标识
     *
     * @return mixed
     */
    abstract public function getUionId();
     

    /**
     * 获取用户信息
     *
     * @return mixed
     */
    abstract public function getInfo();
}

FACEBOOK类
<?php
/**
 * Facebook登录
 * @author kamiya
 * @ctime 2021-07-15
 */
namespace Kuxin\Oauth;

use Kuxin\Helper\Http;
use Kuxin\Helper\Json;

class Facebook extends Oauth{
    /**
     * 获取requestCode的api接口
     * @var string
     */
    protected $getRequestCodeURL = 'https://www.facebook.com/dialog/oauth';
    /**
     * 获取access_token的api接口
     * @var string
     */
    protected $getAccessTokenURL = 'https://graph.facebook.com/oauth/access_token';
    /**
     * 获取request_code的额外参数 URL查询字符串格式
     * @var srting
     */
    protected $Authorize = 'scope=email';
    /**
     * API根路径
     * @var string
     */
    protected $apiBase = 'https://graph.facebook.com/';
    /**
     * 构造函数
     *
     * @param array $config
     * @param null  $token
     */
    public function __construct(array $config, $token = null)
    {
        parent::__construct($config, $token);
        $this->getTokenParam = [
            'appid'  => $this->appid,
            'secret' => $this->appsecret, 
        ];
    } 
     /**
     * 组装接口调用参数 并调用接口
     *
     * @param  string $api    FB API
     * @param  array  $param  调用API的额外参数
     * @param  string $method HTTP请求方法 默认为GET
     * @param  bool   $multi
     * @return string json
     */
    public function call($api, $param = [], $method = 'GET', $multi = false)
    {
        /*  facebook 调用公共参数 */
        $params = [
            'access_token' => $this->token,
        ];
        $params = array_merge($params, $param);
        $data   = Http::get($this->apiBase . $api, $params);
        return Json::decode($data, true);
    }
     
    protected function parseToken($result)
    {
        $data = Json::decode($result, true);
        if (isset($data['access_token'])) {
            $this->token  = $data['access_token']; 
            return [ 
                'token'   => $this->token,
                'expires' => $data['expires_in'],
                'refresh' => $data['refresh_token'],
            ];
        } else
            return "获取 facebook ACCESS_TOKEN 出错:{$result}";
    }
    /**
     * 获取当前授权应用的openid
     * @return string
     */
    public function getOpenId(){
        if(isset($this->openid))
            return $this->openid;
        
        $data = $this->call('me?fields=id');
       
        if(!empty($data['id']))
            return $data['id'];
        else
            return '没有获取到 facebook 用户ID!';
    }
    
     /**
     * 获取uid
     *
     * @return mixed
     * @throws \Exception
     */
    public function getUionId() {
        
       
    }
    
    /**
     * 获取用户信息
     *
     * @return array
     */
    public function getInfo()
    { 
        $data = $this->call('/me?fields=id,name,email');
      
        return [
            'id'     => $data['id'],
            'name'   => $data['name'], 
            'email'  => $data['email'], 
            'avatar' => '', 
        ];
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值