cashier/api/auth.ts

83 lines
1.9 KiB
TypeScript

import { APP_CONFIG } from '@/config';
import { HttpStatusError, httpRequest, toFormUrlEncoded } from '@/utils/http';
export interface LoginResponse {
code: number | string;
msg?: string;
data?: {
token?: string;
expires_in?: number;
};
}
export type LoginPlatform = 'mp-weixin' | 'mp-alipay';
export const resolveLoginPlatform = (): LoginPlatform => {
// #ifdef MP-ALIPAY
return 'mp-alipay';
// #endif
// #ifdef MP-WEIXIN
return 'mp-weixin';
// #endif
// #ifndef MP-WEIXIN
// #ifndef MP-ALIPAY
return 'mp-weixin';
// #endif
// #endif
};
/** 微信 code / 支付宝 authCode 都走同一登录接口 */
export const loginByCode = async (code: string) => {
const response = await httpRequest<LoginResponse>({
url: `${APP_CONFIG.API_BASE_URL}/user/v3/login.code`,
method: 'POST',
data: toFormUrlEncoded({
code,
app_id: APP_CONFIG.APP_ID,
platform: resolveLoginPlatform()
}),
header: {
'content-type': 'application/x-www-form-urlencoded'
}
});
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new HttpStatusError('登录请求失败', response.statusCode, response.data);
}
return response.data;
};
/** @deprecated 使用 loginByCode */
export const loginByWechatCode = loginByCode;
export interface MobileAuthBindResponse {
code: number | string;
msg?: string;
data?: unknown;
}
/** 小程序授权绑定手机号(微信/支付宝) */
export const mobileAuthBind = async (code: string) => {
const response = await httpRequest<MobileAuthBindResponse>({
url: `${APP_CONFIG.API_BASE_URL}/user/v1/mobile.auth.bind`,
method: 'POST',
data: toFormUrlEncoded({
code,
app_id: APP_CONFIG.APP_ID,
platform: resolveLoginPlatform()
}),
header: {
'content-type': 'application/x-www-form-urlencoded'
}
});
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new HttpStatusError('手机号绑定失败', response.statusCode, response.data);
}
return response.data;
};