H5页面获取微信用户openid极简攻略
背景
之前每次写到获取openid 就觉得特别麻烦,网上很多代码段会把一部分功能分开写,确实相对合理,但是对于复制粘贴代码来说依赖越少越方便,所以根据自己的经验做了一个极简的复用代码。
前置条件
1.公众号已认证,否则会出现“Scope 参数错误或没有 Scope 权限”
2.公众号后台设置安全域名
【公众号设置】=》【功能设置】=》【JS接口安全域名】&【网页授权域名】
前端
getUrlParam(name){
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
getOpenId(){
let ua = navigator.userAgent.toLowerCase();
if (/micromessenger/.test(ua)) {
if (!localStorage.getItem('wxOpenid')) {
const code = getUrlParam('code'); // 截取路径中的code,
if (code == null || code === '' || code === false) {
const local = location.href;
let appid = 'xxxxxxx';
window.location.href =
'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
appid +
'&redirect_uri=' +
encodeURIComponent(local) +
'&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
} else {
this.$axios.post('/index/index/getWxOpenid?code=' + code).then(res => {
const openid = res.data.data.openid;
if (openid) {
localStorage.setItem('wxOpenid', openid);
} else {
location.href = '/';
}
});
}
}
}
}
后端
如果只是需要获取到openid,不需要其他信息
public function getOpenid(){
$appid = '<公众号appid>';
$secret = '<公众号secret>';
$code = $_GET["code"];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret. "&code=" . $code . "&grant_type=authorization_code";
$weixin = file_get_contents($url);
$jsondecode = json_decode($weixin);
return result(1, $jsondecode, '成功');
}
如果需要根据openid进一步获取用户信息
public function getUserInfo(){
$appid = '<公众号appid>';
$secret = '<公众号secret>';
$code = $_GET["code"];
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$user_obj = json_decode($res,true);
$_SESSION['user'] = $user_obj;
return json($user_obj);
}

浙公网安备 33010602011771号