php之微信登陆

来源:互联网 发布:田村正和 知乎 编辑:程序博客网 时间:2024/04/29 16:21

微信登陆和qq登陆一样,只是微信登陆少一个不走,access_token和openid是同时获取的。

class weixinClass{
    protected $appid = "";
    protected $callback = "";
    protected $appkey =  "";
    public function __construct()
    {
        require(dirname(__FILE__) . '/oauth.config.php');
        $this->appid    = $wx['appid'];
        $this->callback = urlencode($wx['callback']);
        $this->appkey   =  $wx['appkey'];
       
    }
    public function wx_login(){
        $response_type = "code";
        $scope = "snsapi_login";
         //-------生成唯一随机串防CSRF攻击
        $_SESSION['state'] = md5(uniqid(rand(), TRUE));




        $login_url =  "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->appid.
                      "&redirect_uri=".$this->callback.
                      "&response_type=".$response_type.
                      "&scope=".$scope.
                      "&state=".$_SESSION['state']."#wechat_redirect";
        header("Location:$login_url");
    }


    public function wx_callback(){
        //--------验证state防止CSRF攻击
        
        if($_REQUEST['state'] == $_SESSION['state']){
           $grant_type = "authorization_code";
           $code = $_REQUEST['code'];




            $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid.
                         "&secret=".$this->appkey.
                         "&code=".$code.
                         "&grant_type=".$grant_type;


            $response = file_get_contents($token_url);


            $params = json_decode($response, true);
            if (isset($params->error))
            {
                echo "<h3>error:</h3>" . $msg->error;
                echo "<h3>msg  :</h3>" . $msg->error_description;
                exit;
            }
            return $params;
        }
        else
        {
             return "";
        }
    }


   
    function get_user_info($access_token, $openid)
    {
       
        if(!empty($access_token) && !empty($openid))
        {
            $user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token.
                        "&openid=".$openid;
            
            $response = file_get_contents($user_url);
            $params = json_decode($response, true);
            if (isset($params->error))
            {
                echo "<h3>error:</h3>" . $msg->error;
                echo "<h3>msg  :</h3>" . $msg->error_description;
                exit;
            }
            return $params;
        }else
        {
            return "";
        }
        
    }


    
}

0 0
原创粉丝点击