H5页面获取微信用户openid极简攻略
作者:互联网
背景
之前每次写到获取openid 就觉得特别麻烦,网上很多代码段会把一部分功能分开写,确实相对合理,但是对于复制粘贴代码来说依赖越少越方便,所以根据自己的经验做了一个极简的复用代码
前置条件
1.公众号已认证,否则会出现“Scope 参数错误或没有 Scope 权限”
2.公众号后台设置安全域名
【公众号设置】=》【功能设置】=》【JS接口安全域名
】&【网页授权域名】
代码
前端
getOpenId(){
const code = getUrlParam('code') // 截取路径中的code,
if (code == null || code === '' || code === false) {
const local = window.location.href
let appid='<公众号appid>'
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 {
let that=this;
axios.post('/index/active/getUserInfo?code='+code).then((r)=>{
console.log(r.data)
})
}
}
后端
此处以php 为例
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);
}
标签:openid,ch,setopt,极简,微信,token,code,curl,CURLOPT 来源: https://blog.csdn.net/latinhui/article/details/123089845