微信网页授权获取用户基本信息

来源:互联网 发布:java输出double类型 编辑:程序博客网 时间:2024/05/22 06:48


微信网页授权获取用户基本信息

class WeiXin{

    private $appId;
    private $appSecret;
    private $redirect_uri;

    public function __construct($appId, $appSecret, $redirect_uri) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        //全地址url
        $this->redirect_uri = $redirect_uri;
    }
 
    //获取openId
    public function getOpenId(){
        $jsonStr = $this->getInfo();
        $arr = json_decode($jsonStr, true);
        $openid = $arr['openid'];
        return $openid;
    }
    
    //获取用户信息
    public function getUserInfo(){
        $jsonStr = $this->getInfo();
        $arr = json_decode($jsonStr, true);
        $openid = $arr['openid'];
        $access_token = $arr['access_token'];
        $userinfo_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $info = $this->httpGet($userinfo_url);
        return $info;
    }
    
    //通过code换取网页授权access_token,openid等信息
    private function getInfo(){
        if($_GET['state'] == 'STATE'){        
            $openIdUrl = $this->getOpenidUrl();
            $jsonStr = $this->httpGet($openIdUrl);
            return $jsonStr;
        }else{
            $codeUrl = $this->getCodeUrl();
            header($codeUrl);
            exit;
        }
    }
      
    //获取codeUrl
    private function getCodeUrl(){
        //$redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Home/Test/index';
        $codeUrl = 'location:https://open.weixin.qq.com/connect/oauth2/authorize?'.
        'appid='.$this->appId.
        '&redirect_uri='.$this->redirect_uri.
        '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
        return $codeUrl;
    }
    
    //获取openIdUrl
    private function getOpenidUrl(){
        $code = I('code');
        $openidUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?'.
        'appid='.$this->appId.
        '&secret='.$this->appSecret.
        '&code='.$code.
        '&grant_type=authorization_code';
        return $openidUrl;
    }

    private function httpGet($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $temp = curl_exec($ch);
        curl_close($ch);
        return $temp;
    }
}


0 0