H5获取微信openid封装方法
- 目录
- 1、前置配置条件
- 2、封装并新建getOpenid.js文件
- 2.1:处理code方法
- 2.2:第一次获取到openid后,再次进入无需再次获取;
- 2.3:页面调用方法
- 3、往期回顾
- 总结:
目录
接到需求,在H5页面中要调起微信用户的openid,传给接口,于是结合实际项目情况,对获取openid方法封装一套公共方法,便于大家使用,配置相应参数,开箱即用!
1、前置配置条件
1、传送门:网页授权 | 微信开发文档
2、确保公众号已认证
3、确保公众号后台设置安全域名
【公众号设置】=》【功能设置】=》【JS接口安全域名】&【网页授权域名】
4、在满足条件的允许下,进行下一步
2、封装并新建getOpenid.js文件
实现方法:
(开箱即用)
2.1:处理code方法
2.2:第一次获取到openid后,再次进入无需再次获取;
2.3:页面调用方法
2.1:处理code方法
定义方法 getUrlCodeParam 处理code
// 获取code方法 在js中不建议使用route.query.code方式
let getUrlCodeParam = (name) => {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
2.2:第一次获取到openid后,再次进入无需再次获取;
获取openid方法
export let getOpenId = async () => {
return new Promise(async (resolve, reject) => {
console.log("初始化");
let openid = "";
let ua = navigator.userAgent.toLowerCase();
// 判断是否在微信内部调用 :/micromessenger/.test(ua)
if (/micromessenger/.test(ua)) {
// 判断本地是否获取过openid:(localStorage.getItem("wx_Openid_2024"))
if (!localStorage.getItem("wx_Openid_2024")) {
console.log("微信内部环境");
// 这里是通过getUrlCodeParam('code')方法处理ulr中的 code
const code = getUrlCodeParam('code')
// 这里是有code走这里
if (code) {
// 我们这里处理的方法是将code传给接口,接口返回openid
const res = await reqxxxxxxx(code);
openid = res.data ? res.data.openid : "";
// 拿到openid后将openid存到本地
localStorage.setItem("wx_Openid_2024", openid ? openid : "");
} else {
// 如果没用code 我们就走这里
let redirect_url = encodeURIComponent(window.location.href);
// 这里是定义的appid,可以通过配置获取,也可以写死在这里;
let app_id = "xxxxxxxxx";
// 这里是默认方法
let url =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
app_id +
"&redirect_uri=" +
redirect_url +
"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
window.location.href = url;
}
// 这块返回了openid
return resolve(openid ? openid : "");
} else {
// 判断接口有openid就直接获取本地的
openid = localStorage.getItem("wx_Openid_2024");
return resolve(openid ? openid : "");
}
} else {
console.log("不在微信环境内");
return resolve("");
}
});
};
2.3:页面调用方法
页面调用,进入页面时在created()中调用方法
// 引入方法
import {getOpenId} from '@/utils/index'
// 调用
created () {
getOpenId().then(res => {
console.log(res,'openid')
})
}
以上就是本篇文章的所有内容了~~~
3、往期回顾
— 获取源码接着往下看!—
vue3 + TS + vite 搭建中后台管理系统(完整项目)
vue3 + JS + vant 搭建移动端H5项目(完整项目)
手把手教 Vue3.2+Vite+Echarts 5 绘制3D线条效果中国地图
总结:
前端路上 | 所知甚少,唯善学。
各位小伙伴有什么疑问,欢迎留言探讨。
— 关注我:前端路上不迷路 —