uniapp 微信服务号微信登录
·
前置条件
1.微信服务号
设置与开发 》 账号设置 》功能设置 》(JS接口安全域名、网页授权域名)都配置一下
2.微信开发者平台
找到对应的服务号,配置(API IP白名单) 和 (JS接口安全域名)
vue3
页面显示调登录,它会跳转一个微信页面授权再返回,返回时地址带微信code
let openId = ref('')
const GetUrlParam = (name) =>{
var reg = new RegExp('(^|&)' + name +'=([^&]*)(&|$)') // 构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg)// 匹配目标参数
if(r != null) return unescape(r[2])
return null// 返回参数值
}
const getOpenId = (code) =>{
//调接口获取openId
wxMq_getAccessTokenByCode({code: code}).then((res) => {
openId.value = res.data.openId
}).catch((error) => {
console.log(error)
})
}
const getCode = () =>{
if(openId.value) return
const code = GetUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
const local = window.location.href.slice(0,window.location.href.length - 1)
const gzhAppID = 'wx*******' //服务号appid
if (code == null || code === '') {
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + gzhAppID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
} else {
getOpenId(code) //把code传给后台获取用户信息
}
}
onShow((e)=>{
getCode()
})
更多推荐



所有评论(0)