wx-login/app/src/routes/wx/services.ts
2025-02-28 03:05:52 +08:00

85 lines
2.6 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 { WxTokenResponse, fetchToken, getUserInfo } from '@/modules/wx.ts';
import { useContextKey } from '@kevisual/use-config/context';
import { UserModel } from '@kevisual/code-center-module';
import { Buffer } from 'buffer';
const User = useContextKey<typeof UserModel>('UserModel');
export class WxServices {
token: WxTokenResponse;
// 创建一个webToken用户登录
webToken: string;
isNew: boolean;
// @ts-ignore
user: User;
constructor() {
//
}
async login(code: string) {
const token = await fetchToken(code);
this.token = token;
if (!token.unionid) {
throw new Error('unionid is required');
}
const unionid = token.unionid;
let user = await User.findOne({ where: { username: unionid } });
if (!user) {
user = await User.createUser(unionid, unionid.slice(0, 8));
this.isNew = true;
}
const tokenInfo = await user.createToken(null, 'plugin');
this.webToken = tokenInfo.token;
this.user = user;
return this.webToken;
}
async checkHasUser() {}
async getUserInfo() {
const userInfo = await getUserInfo(this.token.access_token, this.token.openid);
const { nickname, headimgurl } = userInfo;
this.user.nickname = nickname;
try {
const downloadImgUrl = await this.downloadImg(headimgurl);
this.user.avatar = downloadImgUrl;
} catch (error) {
console.error('Error downloading or converting image:', error);
}
await this.user.save();
}
/**
* 转成base64
* @param url
*/
async downloadImg(url: string): Promise<string> {
try {
return await downloadImag(url);
} catch (error) {
console.error('Error downloading or converting image:', error);
throw error;
}
}
}
// https://thirdwx.qlogo.cn/mmopen/vi_32/WvOPpbDwUKEVJvSst8Z91Y68m7CsBeecMqRGlqey5HejByePD89boYGaVCM8vESsYmokk1jABUDsK08IrfI6JEkibZkDIC2zsb96DGBTEF7E/132
export const downloadImag = async (url: string) => {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
const arrayBufferToBase64 = (buffer: ArrayBuffer): string => {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return Buffer.from(binary, 'binary').toString('base64');
};
const buffer = await res.arrayBuffer();
return `data:image/jpeg;base64,${arrayBufferToBase64(buffer)}`;
} catch (error) {
console.error('Error downloading or converting image:', error);
throw error;
}
};