前台页面代码如下:
public function test(){
$WechatOauth=new WechatOauth();
$WechatOauth->getOpenid();
}
后台代码如下:
public function getOpenid()
{
$openid=Session::get('openid');
if(isset($openid)){
echo "有openid session";
exit();
}
if (!isset($_GET['code'])){
/*
*触发微信返回code码
*/
$baseUrl = $this->get_url();//获取当前链接地址
$url = $this->getOauthRedirect($baseUrl,"STATE","snsapi_userinfo"); // 获取 code地址
Header("Location: $url"); // 跳转到微信授权页面 需要用户确认登录的页面
exit();
} else {
//上面获取到code后这里跳转回来
$code = $_GET['code'];
$data = $this->getOauthAccessToken($code);//获取网页授权access_token和用户openid
$data2 = $this->getOauthUserInfo($data['access_token'],$data['openid']);//获取微信用户信息
Session::set('openid',$data['openid']);
exit();
}
在手机上进行调试,服务器会多出来一个新的空session来,就会出错,如图:
但是在微信开发者工具里面调试的话就正常,如图: