在H5公众号项目中使用的是uniapp进行开发,在开发中需要用到一些微信的支付、扫码等功能,这些都需要进行一个微信授权获取到code,由于uniapp的方法不支持h5直接获取code,所以只能使用微信授权链接进行获取,但是根据需求获取还需要不能显示授权页,所以就使用一个静默授权的操作
项目我们要用到自己appid和当前线上地址的回调页面,根据自己需求进行设置不同的回调页面
1 我们要进行授权页数据的传递
// 微信静默授权
function getWxSq(url) {
const appId = 'xxxxxxx'; //自己项目的appid
const redirectUri = encodeURIComponent(url) //页面回调地址
const scope = 'snsapi_base'; // 不弹出授权页面,直接跳转
const state = 'your_custom_state';
const authUrl =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
window.location.href = authUrl; //这个跳转的链接上面会有code 我们在进行获取code
console.log(authUrl)
}
2 获取授权后地址的code
// 截取url中的code方法获取微信授权code
function 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
}
3 再根据code进行后端通信获取到openid(获取后一定要本地保存起来,避免在有效期内多次进行静默授权)
注意此处我处理了获取openid保存起来后又进行了返回上一级菜单,因为静默授权只是不弹出授权页 但也会进行页面跳转,可以根据自己的业务进行处理需不需要返回上一页
// 获取openid
async function _getOpenid() {
const code = getUrlCode().code
const res = await getUserInfoOpenid({
code: code
})
setOpenid(res.data.openid)
setTimeout(()=>{
uni.navigateBack()
},100)
}
4 根据授权需求封装的逻辑判断,判断当前页是否存在code 存在就进行获取code往下进行,不存在就进行授权获取
// 获取链接授权code,并通过code获取到openid
function getcode(url) {
const code = getUrlCode().code // 截取code
if (!code) {
getWxSq(url)
} else {
_getOpenid()
}
}
下面是全部代码,自己封装的wx.js文件 本地存储的数据自己处理,接口调用自己的
// 微信静默授权
function getWxSq(url) {
const appId = 'xxxxx';
const redirectUri = encodeURIComponent(url) //页面回调地址
const scope = 'snsapi_base'; // 不弹出授权页面,直接跳转,只能获取用户openid
const state = 'your_custom_state';
const authUrl =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
window.location.href = authUrl;
console.log(authUrl)
}
// 截取url中的code方法获取微信授权code
function 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
}
// 获取openid
async function _getOpenid() {
const code = getUrlCode().code
const res = await getUserInfoOpenid({
code: code
})
setOpenid(res.data.openid)
setTimeout(()=>{
uni.navigateBack()
},100)
}
// 获取链接授权code,并通过code获取到openid
function getcode(url) {
const code = getUrlCode().code // 截取code
if (!code) {
getWxSq(url)
} else {
_getOpenid()
}
}
export default {
// 获取微信授权的数据 url 需要回调的项目地址
getWxSqUrlData(url) {
if(!getOpenid()){
getcode(url)
}
}
}
页面使用
// 当时体验商品时可以进行微信支付
this.$wx.getWxSqUrlData(`自己的回调链接,可以根据页面需求进行拼接参数,保证跳转回来的页面路径参数不丢失`)