封版手机一键登录

This commit is contained in:
2025-07-31 09:56:35 +08:00
parent 024e04041c
commit 57cd79ea38
2 changed files with 257 additions and 0 deletions

94
src/utils/wxLogin.ts Normal file
View File

@@ -0,0 +1,94 @@
import { wxPhoneLogin } from '@/api/passport/login';
import Taro from '@tarojs/taro';
/**
* 微信登录工具类
* 提供便捷的微信登录方法
*/
export class WxLoginUtil {
/**
* 处理微信授权手机号登录
* @param detail 微信授权返回的详细信息
* @param options 登录选项
*/
static async handleGetPhoneNumber(
detail: any,
options?: {
onSuccess?: (user: any) => void;
onError?: (error: string) => void;
showToast?: boolean;
navigateBack?: boolean;
tenantId?: number;
}
) {
const { code, encryptedData, iv } = detail;
if (!code) {
const errorMsg = '用户取消授权';
if (options?.onError) {
options.onError(errorMsg);
}
if (options?.showToast !== false) {
Taro.showToast({
title: errorMsg,
icon: 'none'
});
}
return Promise.reject(new Error(errorMsg));
}
try {
return await wxPhoneLogin(
{ code, encryptedData, iv },
options
);
} catch (error: any) {
console.error('微信登录失败:', error);
throw error;
}
}
/**
* 简化版登录方法 - 只需要传入detail使用默认配置
* @param detail 微信授权返回的详细信息
*/
static async quickLogin(detail: any) {
return this.handleGetPhoneNumber(detail, {
showToast: true,
navigateBack: true
});
}
/**
* 自定义成功回调的登录方法
* @param detail 微信授权返回的详细信息
* @param onSuccess 成功回调
*/
static async loginWithCallback(
detail: any,
onSuccess: (user: any) => void
) {
return this.handleGetPhoneNumber(detail, {
onSuccess,
showToast: true,
navigateBack: false
});
}
}
/**
* 创建微信登录处理函数的工厂方法
* @param options 登录选项
* @returns 返回一个可以直接用于 onGetPhoneNumber 的处理函数
*/
export function createWxLoginHandler(options?: {
onSuccess?: (user: any) => void;
onError?: (error: string) => void;
showToast?: boolean;
navigateBack?: boolean;
tenantId?: number;
}) {
return ({ detail }: { detail: any }) => {
return WxLoginUtil.handleGetPhoneNumber(detail, options);
};
}