当用户通过微信登录你的网页时,记录用户的openid,对于一个公众号来说,每个用户openid都是唯一的。需要获取公众号的appid与appserect。__CALL_URL__的url地址需要转换一下哦
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == true) {
if(isset($_SESSION["openid"])==false) {
//配置参数的数组
$CONF = array(
'__APPID__' =>'xxxx',
'__SERECT__' =>'yyyy',
'__CALL_URL__' =>'http%3a%2f%2fwww.xxx.com' //当前页地址
);
//没有传递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=1";
//跳转微信获取code值,去登陆
header('Location:' . $getCodeUrl);
exit;
}
$code = trim($_GET['code']);
//使用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);
$_SESSION["openid"]=$html['openid'];
}
}else{
echo "<script>alert('请在微信中打开!')</script>";
echo "<script>location.href='index.php'</script>";
exit();
}
if(trim($_SESSION["openid"])==""){
echo "<script>alert('自动登录失败,请稍候重试!')</script>";
echo "<script>location.href='index.php'</script>";
exit();
}
$tempopenid=$_SESSION["openid"];
参考:https://blog.csdn.net/weixin_36333654/article/details/52882287?locationNum=5&fps=1