php之微信登陆

微信登陆和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 "";
        }
        
    }


    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值