微信公众号静默授权,转发页面并附带code
public function demo () {
// 授权地址
$url = "";
// 判断浏览器信息
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == true) {
//配置参数的数组
$CONF = array(
'__APPID__' =>'公众号的appid',
'__SERECT__' => '公众号的serect',
'__CALL_URL__' =>$url //当前页地址
);
//没有传递code的情况下,先登录一下
if(!isset($_GET['code']) || empty($_GET['code'])){
$getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize".
"?appid=" . $CONF['__APPID__'].
"&redirect_uri=" . $CONF['__CALL_URL__'].
"&response_type=code".
"&scope=snsapi_base". #!!!scope设置为snsapi_base !!!
"&state=123";
//跳转微信获取code值,去登陆
header('Location:' . $getCodeUrl);
exit;
}else{
$code = trim($_GET['code']);
$url = $url.$code;
return redirect($url);
}
}else{
echo "请在微信客户端打开链接";
exit();
}
}
通过code解析openid
$code = $postData['code'];
//配置参数的数组
$CONF = array(
'__APPID__' =>'',
'__SERECT__' => ''
);
//使用code,拼凑链接获取用户openid
$str = "https://api.weixin.qq.com/sns/oauth2/access_token".
"?appid={$CONF['__APPID__']}".
"&secret={$CONF['__SERECT__']}".
"&code={$code}".
"&grant_type=authorization_code";
//拿到openid
$html = json_decode(file_get_contents($str),1);
$openid = $html['openid'];
判断code是否过期
# 如果有键errcode
if(array_key_exists('errcode', $html) == true){
if($html['errcode'] == 40163){
$arr = [
'code'=>40163,
'msg'=>'code失效'
];
return json($arr);
}
}