Files
chazhi_h5/src/hooks/useWeiXin.ts
2025-10-17 15:40:03 +08:00

80 lines
2.7 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 { useUserStore } from '@/store'
import type { IUserInfoVo } from '@/api/types/login'
/**
* 微信静默授权
*/
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 async function snsapiBaseAuthorize() {
// TODO 测试代码
// wxSnsapiBaseLogin({code: '051wM51w3488N53ThD3w3obLDm2wM51r'}).then((res: IUserInfoVo) => {
// console.log("登录成功 ~ snsapiBaseAuthorize ~ res:", res)
// // 映射 IUserLogin 到 IUserInfoVo
// useUserStore().setUserInfo(res)
// }).catch(err => {
// // 失败就重新授权
// uni.setStorageSync('wechatCode', 0)
// console.log('请求失败', err)
// })
// const res = {
// account: "u39317465",
// avatar: "https://cz.stnav.com/uploads/user/avatar/c2b3c5f94e3f20c8a989bd302519b4c7.jpeg",
// channel:2,
// is_new_user: 1,
// id: 4,
// sn:"39317465",
// token: "013f5128f0208f2f9d9285af5070ae7b",
// nickname: '微信用户',
// mobile: '15005837859'
// }
// useUserStore().setUserInfo(res)
// console.log(useUserStore().userInfo)
// return
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
let uri = encodeURIComponent(local)
console.log("🚀 ~ 当前没有code进入授权页面 snsapiBaseAuthorize ~ uri:", uri)
// 设置旧的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_base&state=123#wechat_redirect`
} else {
// 保存最新code
uni.setStorageSync('wechatCode',code)
// 使用code换取用户信息同步写法
try {
const res: IUserInfoVo = await wxSnsapiBaseLogin({code})
console.log("登录成功 ~ snsapiBaseAuthorize ~ res:", res)
useUserStore().setUserInfo(res)
} catch (err) {
uni.setStorageSync('wechatCode', 0)
console.log('请求失败', err)
}
}
}