网站应用开发-微信联合登录

 其他解决方案    |      2020-02-27
<?php
namespace appportcontroller;


use thinkController;
use thinkDb;
use thinkLoader;


class Wxlogin extends Controller
{
    public $appid = 'xxxxxxxxxxxxxxxxxxxxx';//appid
    public $appsecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';//appsecret


    public function _initialize()
    {
        parent::_initialize();
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }


    //构造函数,获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    { //此处需要将access_token 进行数据存储 也可以存储文件随意怎么
    //方便怎么来
        $data = Db::name('token')->where('id',1)->find();
        if (time()-7200 < $data['add_time']) { // 在有效期内
            return $data['access_token'];
        }
        $urla = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
        $outputa = $this->http_request($urla);
        $result = json_decode($outputa, true);
        Db::name('token')->where('id','1')->update([
            'access_token' => $result['access_token'],
            'add_time' => time(),
            'expires_in' => $result['expires_in']
        ]);
        return $result['access_token'];
    }


    //生成扫码登录的URL
    public function qrconnect($redirect_url, $scope, $state = NULL)
    {
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $this->appid . "&redirect_uri=" . urlencode($redirect_url) . "&response_type=code&scope=" . $scope . "&state=" . $state . "#wechat_redirect";
        return $url;
    }


    //生成OAuth2的Access Token
    public function oauth2_access_token($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $res = $this->http_request($url);
        return json_decode($res, true);
    }


    //获取用户基本信息(OAuth2 授权的 Access Token 获取 未关注用户,Access Token为临时获取)
    public function oauth2_get_user_info($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = $this->http_request($url);
        return json_decode($res, true);
    }


    public function http_request($url){
        return file_get_contents($url);
    }


    //微信扫码登录
    public function weChatLogin(){
        if (!isset($_GET["code"])){
            $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            $token = 'zk'.time();
            $jumpurl = $this->qrconnect($redirect_url, "snsapi_login", $token);
            $res = [
                'code' => 1,
                'data' => $jumpurl,
                'msg'=> '获取连接成功!'
            ];
            exit(json_encode($res));
        }else{
            //获取token
            $oauth2_info = $this->oauth2_access_token($_GET["code"]);
            //获取用户信息
            $userinfo = $this->oauth2_get_user_info($oauth2_info['access_token'], $oauth2_info['openid']);
            $openid = $userinfo['openid'];
            $user = Db::name('user')->where('openid',$openid)->find();
            if(!$user){
//存储登陆信息
                $insert['openid'] = $userinfo['openid'];
                $insert['nickname'] = $userinfo['nickname'];
                $insert['sex'] = $userinfo['sex'];
                $insert['city'] = $userinfo['city'];
                $insert['headimgurl'] = $userinfo['headimgurl'];
                $insert['unionid'] = $userinfo['unionid'];
                $insert['token'] = $_GET['state'];
                $insert['addtime'] = time();
                $insert['create_time'] = time();
                $result = Db::name('user')->insert($insert);
            }else{
   //更新token
                $update['token'] = $_GET['state'];
                Db::name('user')->where('openid',$user['openid'])->update($update);
            }
            header('Location:xxxxxxxxxxxxx(登陆成功后跳转地址)');
            exit();//帮助header跳转页面 不然不执行
        }
    }
}