网页授权页面,初次授权接入的时候没啥问题,可一旦刷新页面或者返回都会报错!解决办法,使用session保存第一次获取到的用户信息,还有用草料二维码的话,最后一次返回也会出错,但把授权链接放在公众号内部就可以了。
<?php
namespace app\home\controller;
use think\Controller;
//define your token
Class Index extends Base
{
public function index()
{ session_start();//开启session
if($_SESSION['openid']){
return $this->fetch('Lists/lists');
}else{
$code=$_GET["code"];
$userinfo_array=$this->getUserInfo($code);
$_SESSION['openid']=$userinfo_array['openid'];
$_SESSION['headimgurl']=$userinfo_array['headimgurl'];
return $this->fetch('Lists/lists');
}
}
public function getUserInfo($code)
{
$appid="XXXXX";//修改为你自己的
$appseret="XXXXXX";//修改为你自己的
$access_token="";
//根据code获得网页Access Token
$access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appseret&code=$code&grant_type=authorization_code";
$access_token_json=$this->https_request( $access_token_url);
$access_token_array=json_decode($access_token_json,true);//转换为数组,若不写true则会转换为数组对象
$access_token=$access_token_array['access_token'];
$openid=$access_token_array['openid'];
//根据openid和access_token获得用户信息
$userinfo_url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
$userinfo_json=$this->https_request($userinfo_url);
$userinfo_array=json_decode($userinfo_json,true);
return $userinfo_array;
}
}