h5端获取微信登录code置换openid
·
1.登录公众号进行网页授权,将校验文件下载下来之后传递给后端,放到根目录下

2、通过 微信官方链接获取到code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect
3.登录之后,从微信打开上面的链接,登录之后,从浏览器打开,就可以看到下面链接里面的code,这块的currentUrl一定是一个能打开的链接

wechatAuth() {
const appid = 'wx273********702eb';
const userid = uni.getStorageSync('userinfo').user_id;
const currentUrl= "https://aicangu.wangluoyunying.work/h5";
console.log(currentUrl);
const state = 'wechat_auth_login';
const redirectUri = encodeURIComponent(currentUrl);
const wechatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
// 跳转微信授权页面
window.location.href = wechatAuthUrl;
},
4.将code从链接里面截取出来,传递给后端
checkWechatCallback() {
console.log("检查微信回调")
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
console.log("获取到的code:", code)
this.$u.toast(code);
// 如果检测到微信回调的code
if (code) {
this.bindWechatOpenId(code);
}
},
bindWechatOpenId(code) {
const that = this;
const userInfo = uni.getStorageSync('userinfo');
// 确保用户信息存在
if (!userInfo || !userInfo.user_id) {
console.error('用户信息不存在');
return;
}
console.log('即将发送的code:', code);
setTimeout(() => {
this.$u.toast('code2: ' + code);
}, 1000);
return;
// 立即发送请求,不要有延迟
that.$u.post('/api/User/openId', {
code: code,
user_id: userInfo.user_id
}).then(res => {
console.log('绑定结果:', res);
that.$u.toast(res.msg || '微信绑定成功');
}).catch(err => {
console.error('绑定微信失败:', err);
that.$u.toast('绑定请求失败,请重试!');
});
},
5.检测拿到的code有没有失效,使用官方置换openid的链接测试,如下图
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code
secret为微信公众号或服务号的秘钥
code为获取的code
注:若置换成功则说明没有问题,获取的code没有失效

更多推荐


所有评论(0)