cashier/api/auth.ts

100 lines
2.3 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 { APP_CONFIG } from '@/config';
import { HttpStatusError, httpRequest, toFormUrlEncoded } from '@/utils/http';
import { get, postForm } from '@/utils/request';
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 BindMobileResponse {
code: number | string;
msg?: string;
data?: {
token?: string;
expires_in?: number;
code?: string;
msg?: string;
mobile?: string;
};
}
/**
* 支付宝手机号绑定。
* encryptedData = my.getPhoneNumber 成功回调里 response.response解密密文
* 需登录态:走 postForm自动带 Authorization: Bearer <token>
*/
export const bindMobile = (encryptedData: string) => {
return postForm<BindMobileResponse>('user/v1/bind.mobile', {
encryptedData,
app_id: APP_CONFIG.APP_ID,
platform: resolveLoginPlatform()
});
};
export interface OpenInfoResult {
code: number | string;
msg?: string;
data?: {
user?: {
user_id?: number | string;
user_name?: string;
avatar?: string;
};
open?: {
user_id?: number | string;
open_id?: number | string;
};
};
}
/** 当前登录用户信息;有 user_id 视为已绑定过手机号/账号资料 */
export const fetchOpenInfo = () => get<OpenInfoResult>('user/v1/open.info');