Files
chazhi_h5/src/hooks/useWeiXin.ts
2025-10-05 18:05:58 +08:00

56 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {wxSnsapiBaseLogin} from '@/api/login'
// import {setUserInfo, getUserInfo} from '@/store/user'
/**
* 微信静默授权
*/
const getUrlCode = (): { [key: string]: string | undefined } => {
// 截取url中的code方法
const url = location.search
// this.winUrl = url;
let theRequest: { [key: string]: string | undefined } = {}
if (url.indexOf('?') != -1) {
let str = url.slice(1)
let strs = str.split('&')
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
}
}
return theRequest
}
/**
* 微信静默授权登录
*/
export function snsapiBaseAuthorize() {
let local = window.location.href // 获取页面url
let appid = import.meta.env.VITE_WX_SERVICE_ACCOUNT_APPID // 公众号的APPID
console.log("🚀 ~ snsapiBaseAuthorize ~ appid:", appid)
let code = getUrlCode().code // 截取code
// 获取之前的code
let oldCode = uni.getStorageSync('wechatCode')
if (code == null || code === '' || code == 'undefined' || code == oldCode) {
// 如果没有code就去请求获取code
console.log('当前没有code进入授权页面')
let uri = encodeURIComponent(local)
// 设置旧的code为0避免死循环
uni.setStorageSync('wechatCode',0)
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
} else {
console.log('存在code使用code换取用户信息')
// 保存最新code
uni.setStorageSync('wechatCode',code)
console.log("🚀 ~ snsapiBaseAuthorize ~ code:", code)
// 使用code换取用户信息
wxSnsapiBaseLogin({code}).then(res=>{
console.log("🚀 ~ snsapiBaseAuthorize ~ res:", res)
}).catch(err=>{
// 失败就重新授权
uni.setStorageSync('wechatCode',0)
console.log('请求失败', err)
})
}
}