一、前端根据appID获取code(code通过链接重定向返回,从重定向链接中去截取)
// 获取微信用户code
getCode() {
let appid = '可申请测试的appID';
let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`;
this.code = this.getUrlCode().code;
//如果没有code 去获取code
if (this.code == null) {
window.location.href = url;
}else{
//获取到code后的逻辑
console.log('code', this.code);
// this.getOpenid(this.code)
}
},
// 截取url中的code
getUrlCode() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") !== -1) {
var str = url.substr(1)
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
}
}
return theRequest;
},
微信公众平台测试帐号申请地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
二、后台根据appID、密钥、code获取openId
请求链接:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
参考文档:微信开放文档 (qq.com)
注意:这里的接口也会返回 access_token 但不是我们需要的 要用下面接口获取通用的
code只能使用一次 每次都会变化 openId针对公众号和用户这两个维度 是唯一的
三、后台根据appID和密钥获取access_token
请求链接:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
参考文档:微信开放文档 (qq.com)
四、后台根据openId和access_token获取用户基本信息
请求链接:https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
参考文档:微信开放文档 (qq.com)
注意:以上流程后面三步在前端也可以走,但是出于安全考虑,微信提议还是放到后端比较好,因为涉及到公众号密钥,暴露在前端不太好。当然,第一步获取code也可以直接在后端进行,只要在微信环境中进入后端接口,后端可以采用同样的方式获取code后并重定向回到前端页面。
参考:
微信h5静默、非静默授权获取用户openId的方法和步骤_飞歌Fly的博客-CSDN博客_微信静默授权
h5微信登录授权获取code(测试账号)_江湖浪子女见愁的博客-CSDN博客_h5微信登录
微信H5页面判断用户是否已关注公众号,以及唤起关注公众号页面 - 简书 (jianshu.com)
五、查询当前用户是否关注公众号
https://api.weixin.qq.com/cgi-bin/user/info?access_token=${ACCESS_TOKEN}&openid=${OPENID}&lang=zh_CN