自学内容网 自学内容网

微信H5网页静默授权并跳转到指定页面

官方文档

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

代码

// 检查是否是微信环境
isWechat() {
const ua = navigator.userAgent.toLowerCase();
return ua.includes('micromessenger') && !ua.includes('wxwork');
},

// 静默登录
async silentLogin() {
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
// 如果 code存在,传递给后端,换取openid

} else {  // 如果没有 code,跳转到授权页面,去授权
// 授权后重定向的回调链接地址,跳转到启动页
const redirectUriWithId = encodeURIComponent(`项目部署后的启动页的url`);
let state = 'stateFlag'; 
const authUrl =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${redirectUriWithId}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
window.location.href = authUrl
}
},
onLoad() {
if (this.isWechat()) {
this.silentLogin(); // 进行静默登录
}
}

启动页,实现跳转到任意页

redirectPage() {
// console.log(132, window.location.href);
// console.log('state ',history.state);
if (window.location.href.includes('stateFlag')) {
var stateVal = window.location.href.replace('stateFlag', 'STATE')
// // 移除浏览器历史记录,避免页面重复刷新时再次获取state参数
history.replaceState(null, '', stateVal);
// console.log(78999, stateVal);

var val = window.location.href.replace('stateFlag', 'STATE')
//要跳转的url
val = window.location.href + 'pages/register/index'

window.location.href = val;
}
}

我的参考:
https://developers.weixin.qq.com/community/develop/article/doc/00026a17870f80480a31c3c9f6b413


原文地址:https://blog.csdn.net/weixin_45775165/article/details/142761251

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!