php交流

php微信授权登录

2020-07-14  本文已影响0人  百不理

新建文件 userinfo.php

private $appId;
private $appSecret;

    public function __construct(){
       $this->appId = '';  
       $this->appSecret= '';  
    }

//获取code
    public function getCode(){
        //scope=snsapi_base 实例
        $unique_id = $_GET["unique_id"];
        $appid = $this->appId;
        $redirect_uri = urlencode (config('WEB_URL').'/home/userinfo/getUserInfo?unique_id='.$unique_id);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        header("Location:".$url);
    }

//获取用户信息
    public function getUserInfo(){

        $appid = $this->appId;  
        $secret = $this->appSecret;  
        $code = $_GET["code"];
//自己定义需要携带的参数unique_id 
        $unique_id = $_GET["unique_id"];
         
        //第二步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = $this->getJson($oauth2Url);

        $data = [
            'unique_id' => $unique_id,
            'openid' => $oauth2['openid'],
            'unionid' => $oauth2['unionid'],
            'create_time' => date("Y-m-d H:i:s")
        ];
        
        Db::table('tc_share')->insert($data);
        $redirect_url = 'https://a.app.qq.com/o/simple.jsp?pkgname=com.hdn.tici';
        header("Location:".$redirect_url);
        exit;
    }

//请求
    public function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

上一篇 下一篇

猜你喜欢

热点阅读