feat(partner): require WeChat OAuth before store photo upload
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
import { Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
|
||||||
|
import { useEffect } from 'react';
|
||||||
import TabLayout from './layouts/TabLayout';
|
import TabLayout from './layouts/TabLayout';
|
||||||
import LoginPage from './pages/LoginPage';
|
import LoginPage from './pages/LoginPage';
|
||||||
import HomePage from './pages/HomePage';
|
import HomePage from './pages/HomePage';
|
||||||
@@ -12,9 +13,36 @@ import BillsPage from './pages/BillsPage';
|
|||||||
import ReshipPage from './pages/ReshipPage';
|
import ReshipPage from './pages/ReshipPage';
|
||||||
import WeeklyReportPage from './pages/WeeklyReportPage';
|
import WeeklyReportPage from './pages/WeeklyReportPage';
|
||||||
import LeaderboardPage from './pages/LeaderboardPage';
|
import LeaderboardPage from './pages/LeaderboardPage';
|
||||||
|
import { handlePartnerWechatCallback, savePartnerWechatAuth } from './lib/wechat-auth';
|
||||||
|
import { isWechatEnv } from './lib/weixin';
|
||||||
|
|
||||||
|
function WechatOAuthHandler() {
|
||||||
|
const location = useLocation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isWechatEnv() || !location.search.includes('code=')) return;
|
||||||
|
void handlePartnerWechatCallback()
|
||||||
|
.then((result) => {
|
||||||
|
if (!result || !savePartnerWechatAuth(result)) return;
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
params.delete('code');
|
||||||
|
params.delete('state');
|
||||||
|
const qs = params.toString();
|
||||||
|
navigate(`${location.pathname}${qs ? `?${qs}` : ''}`, { replace: true });
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* 页面内组件会提示 */
|
||||||
|
});
|
||||||
|
}, [location.pathname, location.search, navigate]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
|
<WechatOAuthHandler />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<LoginPage />} />
|
<Route path="/login" element={<LoginPage />} />
|
||||||
<Route element={<TabLayout />}>
|
<Route element={<TabLayout />}>
|
||||||
@@ -32,5 +60,6 @@ export default function App() {
|
|||||||
<Route path="/orders/:id" element={<OrderDetailPage />} />
|
<Route path="/orders/:id" element={<OrderDetailPage />} />
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { useEffect, useId, useRef, useState } from 'react';
|
import { useEffect, useId, useRef, useState } from 'react';
|
||||||
import { uploadFileToOss, type OssMediaType } from '../lib/upload';
|
import { uploadFileToOss, type OssMediaType } from '../lib/upload';
|
||||||
|
import {
|
||||||
|
authorizePartnerWechat,
|
||||||
|
fetchPartnerProfile,
|
||||||
|
needsWechatAuth,
|
||||||
|
type PartnerProfile,
|
||||||
|
} from '../lib/wechat-auth';
|
||||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||||
|
|
||||||
type OssUploadFieldProps = {
|
type OssUploadFieldProps = {
|
||||||
@@ -11,6 +17,9 @@ type OssUploadFieldProps = {
|
|||||||
wide?: boolean;
|
wide?: boolean;
|
||||||
compact?: boolean;
|
compact?: boolean;
|
||||||
label?: string;
|
label?: string;
|
||||||
|
/** 父级已确认微信授权时可跳过检查 */
|
||||||
|
wechatReady?: boolean;
|
||||||
|
onWechatReadyChange?: (ready: boolean) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_MAX_MB = 10;
|
const DEFAULT_MAX_MB = 10;
|
||||||
@@ -24,22 +33,39 @@ export default function OssUploadField({
|
|||||||
wide,
|
wide,
|
||||||
compact,
|
compact,
|
||||||
label,
|
label,
|
||||||
|
wechatReady,
|
||||||
|
onWechatReadyChange,
|
||||||
}: OssUploadFieldProps) {
|
}: OssUploadFieldProps) {
|
||||||
const inputId = useId();
|
const inputId = useId();
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [authorizing, setAuthorizing] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
const [profile, setProfile] = useState<PartnerProfile | null>(null);
|
||||||
|
|
||||||
const resolvedAccept =
|
const resolvedAccept =
|
||||||
accept ?? (mediaType === 'VIDEO' ? 'video/*' : mediaType === 'FILE' ? 'image/*,.pdf' : 'image/*');
|
accept ?? (mediaType === 'VIDEO' ? 'video/*' : mediaType === 'FILE' ? 'image/*,.pdf' : 'image/*');
|
||||||
const useWechatPicker = isWechatEnv() && mediaType !== 'VIDEO';
|
const useWechatPicker = isWechatEnv() && mediaType !== 'VIDEO';
|
||||||
|
const needsAuth = useWechatPicker && needsWechatAuth(profile) && wechatReady !== true;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!useWechatPicker) return;
|
if (!useWechatPicker) return;
|
||||||
void weixinSdk.init().catch(() => {
|
void fetchPartnerProfile()
|
||||||
/* 点击上传时会再次初始化并提示 */
|
.then((me) => {
|
||||||
|
setProfile(me);
|
||||||
|
onWechatReadyChange?.(!!me.hasWechat);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* 未登录等场景由上传接口报错 */
|
||||||
});
|
});
|
||||||
}, [useWechatPicker]);
|
}, [useWechatPicker, onWechatReadyChange]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!useWechatPicker || needsAuth) return;
|
||||||
|
void weixinSdk.init().catch(() => {
|
||||||
|
/* 点击上传时会再次初始化 */
|
||||||
|
});
|
||||||
|
}, [useWechatPicker, needsAuth]);
|
||||||
|
|
||||||
async function uploadSelectedFile(file: File) {
|
async function uploadSelectedFile(file: File) {
|
||||||
if (file.size > DEFAULT_MAX_MB * 1024 * 1024) {
|
if (file.size > DEFAULT_MAX_MB * 1024 * 1024) {
|
||||||
@@ -59,9 +85,25 @@ export default function OssUploadField({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pickFile() {
|
async function startWechatAuth() {
|
||||||
if (uploading) return;
|
setAuthorizing(true);
|
||||||
setError('');
|
setError('');
|
||||||
|
try {
|
||||||
|
await authorizePartnerWechat();
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : '微信授权失败');
|
||||||
|
setAuthorizing(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickFile() {
|
||||||
|
if (uploading || authorizing) return;
|
||||||
|
setError('');
|
||||||
|
|
||||||
|
if (useWechatPicker && needsAuth) {
|
||||||
|
setError('请先完成微信授权后再上传照片');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (useWechatPicker) {
|
if (useWechatPicker) {
|
||||||
try {
|
try {
|
||||||
@@ -90,22 +132,37 @@ export default function OssUploadField({
|
|||||||
|
|
||||||
const isImage = mediaType === 'IMAGE' && value;
|
const isImage = mediaType === 'IMAGE' && value;
|
||||||
const isFile = mediaType === 'FILE' && value;
|
const isFile = mediaType === 'FILE' && value;
|
||||||
|
const busy = uploading || authorizing;
|
||||||
|
|
||||||
const triggerProps = {
|
const triggerProps = {
|
||||||
type: 'button' as const,
|
type: 'button' as const,
|
||||||
disabled: uploading,
|
disabled: busy || needsAuth,
|
||||||
onClick: () => void pickFile(),
|
onClick: () => void pickFile(),
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="partner-oss-upload">
|
<div className="partner-oss-upload">
|
||||||
|
{needsAuth && (
|
||||||
|
<div className="partner-wechat-auth-hint" role="status">
|
||||||
|
<p className="body-md">上传照片需先完成微信授权</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="partner-btn-outline"
|
||||||
|
style={{ marginTop: 8, width: '100%' }}
|
||||||
|
disabled={authorizing}
|
||||||
|
onClick={() => void startWechatAuth()}
|
||||||
|
>
|
||||||
|
{authorizing ? '跳转授权中…' : '微信授权'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<input
|
<input
|
||||||
id={inputId}
|
id={inputId}
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
type="file"
|
type="file"
|
||||||
accept={resolvedAccept}
|
accept={resolvedAccept}
|
||||||
className="partner-oss-upload-input"
|
className="partner-oss-upload-input"
|
||||||
disabled={uploading}
|
disabled={busy}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) void uploadSelectedFile(file);
|
if (file) void uploadSelectedFile(file);
|
||||||
@@ -115,7 +172,7 @@ export default function OssUploadField({
|
|||||||
<button {...triggerProps} className={`partner-upload-preview${wide ? ' partner-upload-preview--wide' : ''}`}>
|
<button {...triggerProps} className={`partner-upload-preview${wide ? ' partner-upload-preview--wide' : ''}`}>
|
||||||
<img src={value} alt={label ?? '已上传'} />
|
<img src={value} alt={label ?? '已上传'} />
|
||||||
<span className="partner-upload-preview-mask">
|
<span className="partner-upload-preview-mask">
|
||||||
<span className="material-symbols-outlined">{uploading ? 'hourglass_top' : 'edit'}</span>
|
<span className="material-symbols-outlined">{busy ? 'hourglass_top' : 'edit'}</span>
|
||||||
<span>{uploading ? '上传中…' : '更换'}</span>
|
<span>{uploading ? '上传中…' : '更换'}</span>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
@@ -135,10 +192,10 @@ export default function OssUploadField({
|
|||||||
className={`partner-upload-dashed${wide ? ' partner-upload-dashed--wide' : ''}${compact ? ' partner-upload-dashed--compact' : ''}`}
|
className={`partner-upload-dashed${wide ? ' partner-upload-dashed--wide' : ''}${compact ? ' partner-upload-dashed--compact' : ''}`}
|
||||||
>
|
>
|
||||||
<span className="material-symbols-outlined text-primary" style={{ fontSize: compact ? 28 : 36 }}>
|
<span className="material-symbols-outlined text-primary" style={{ fontSize: compact ? 28 : 36 }}>
|
||||||
{uploading ? 'hourglass_top' : 'add_a_photo'}
|
{busy ? 'hourglass_top' : 'add_a_photo'}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-primary" style={{ fontWeight: 500 }}>
|
<span className="text-primary" style={{ fontWeight: 500 }}>
|
||||||
{uploading ? '上传中…' : (label ?? (useWechatPicker ? '从相册选择' : '点击上传'))}
|
{uploading ? '上传中…' : needsAuth ? '请先微信授权' : (label ?? (useWechatPicker ? '从相册选择' : '点击上传'))}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type { WechatLoginResult } from '@dukang/shared-types';
|
||||||
|
import { isWechatEnv, weixinSdk } from './weixin';
|
||||||
|
import { request, saveAuth } from './api';
|
||||||
|
|
||||||
|
export type PartnerProfile = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
companyName: string;
|
||||||
|
hasWechat?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function fetchPartnerProfile(): Promise<PartnerProfile> {
|
||||||
|
return request<PartnerProfile>('PARTNER_H5', '/partner/me');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 微信内上传照片前需完成公众号授权绑定 */
|
||||||
|
export function needsWechatAuth(profile: PartnerProfile | null): boolean {
|
||||||
|
return isWechatEnv() && !!profile && !profile.hasWechat;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function savePartnerWechatAuth(result: WechatLoginResult): boolean {
|
||||||
|
if (!result.accessToken) return false;
|
||||||
|
saveAuth({ accessToken: result.accessToken });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authorizePartnerWechat(): Promise<WechatLoginResult | void> {
|
||||||
|
if (!isWechatEnv()) {
|
||||||
|
throw new Error('请在微信内打开以完成授权');
|
||||||
|
}
|
||||||
|
return weixinSdk.login();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handlePartnerWechatCallback(): Promise<WechatLoginResult | null> {
|
||||||
|
if (!isWechatEnv()) return null;
|
||||||
|
return weixinSdk.handleOAuthCallback();
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ export const weixinSdk = createWeixinSdk({
|
|||||||
apiBase: '/api/v1',
|
apiBase: '/api/v1',
|
||||||
clientApp: 'PARTNER_H5',
|
clientApp: 'PARTNER_H5',
|
||||||
getAccessToken: () => localStorage.getItem('accessToken'),
|
getAccessToken: () => localStorage.getItem('accessToken'),
|
||||||
|
wechatLoginPath: '/partner/auth/login/wechat',
|
||||||
});
|
});
|
||||||
|
|
||||||
export { isWechatEnv };
|
export { isWechatEnv };
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ import OssUploadField from '../components/OssUploadField';
|
|||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { resolveRegionBinding } from '../lib/china-region';
|
import { resolveRegionBinding } from '../lib/china-region';
|
||||||
import { fetchPartnerCities, type OpenCityOption } from '../lib/upload';
|
import { fetchPartnerCities, type OpenCityOption } from '../lib/upload';
|
||||||
|
import {
|
||||||
|
fetchPartnerProfile,
|
||||||
|
handlePartnerWechatCallback,
|
||||||
|
savePartnerWechatAuth,
|
||||||
|
} from '../lib/wechat-auth';
|
||||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||||
import {
|
import {
|
||||||
clearStoreDraft,
|
clearStoreDraft,
|
||||||
@@ -28,6 +33,7 @@ export default function StoreCreatePage() {
|
|||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [cities, setCities] = useState<OpenCityOption[]>([]);
|
const [cities, setCities] = useState<OpenCityOption[]>([]);
|
||||||
const [citiesError, setCitiesError] = useState('');
|
const [citiesError, setCitiesError] = useState('');
|
||||||
|
const [wechatReady, setWechatReady] = useState(false);
|
||||||
|
|
||||||
const stepFromUrl = Number(params.get('step') || 0);
|
const stepFromUrl = Number(params.get('step') || 0);
|
||||||
const step = stepFromUrl >= 1 && stepFromUrl <= 3 ? stepFromUrl : (saved?.step ?? 1);
|
const step = stepFromUrl >= 1 && stepFromUrl <= 3 ? stepFromUrl : (saved?.step ?? 1);
|
||||||
@@ -44,11 +50,25 @@ export default function StoreCreatePage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (step !== 2 || !isWechatEnv()) return;
|
if (step !== 2 || !isWechatEnv()) return;
|
||||||
|
void fetchPartnerProfile()
|
||||||
|
.then((me) => setWechatReady(!!me.hasWechat))
|
||||||
|
.catch(() => setWechatReady(false));
|
||||||
void weixinSdk.init().catch(() => {
|
void weixinSdk.init().catch(() => {
|
||||||
/* OssUploadField 点击时会再次初始化 */
|
/* OssUploadField 点击时会再次初始化 */
|
||||||
});
|
});
|
||||||
}, [step]);
|
}, [step]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isWechatEnv() || !params.get('code')) return;
|
||||||
|
void handlePartnerWechatCallback()
|
||||||
|
.then((result) => {
|
||||||
|
if (result && savePartnerWechatAuth(result)) {
|
||||||
|
setWechatReady(true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((e) => setError(e instanceof Error ? e.message : '微信授权失败'));
|
||||||
|
}, [params]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void fetchPartnerCities()
|
void fetchPartnerCities()
|
||||||
.then((items) => {
|
.then((items) => {
|
||||||
@@ -259,6 +279,8 @@ export default function StoreCreatePage() {
|
|||||||
bizType="STORE_TITLE"
|
bizType="STORE_TITLE"
|
||||||
mediaType="IMAGE"
|
mediaType="IMAGE"
|
||||||
value={form.coverUrl}
|
value={form.coverUrl}
|
||||||
|
wechatReady={wechatReady}
|
||||||
|
onWechatReadyChange={setWechatReady}
|
||||||
onChange={(coverUrl) => patchForm({ coverUrl })}
|
onChange={(coverUrl) => patchForm({ coverUrl })}
|
||||||
label="点击或拖拽上传"
|
label="点击或拖拽上传"
|
||||||
/>
|
/>
|
||||||
@@ -275,6 +297,8 @@ export default function StoreCreatePage() {
|
|||||||
bizType="STORE_ENV"
|
bizType="STORE_ENV"
|
||||||
mediaType="IMAGE"
|
mediaType="IMAGE"
|
||||||
value={url}
|
value={url}
|
||||||
|
wechatReady={wechatReady}
|
||||||
|
onWechatReadyChange={setWechatReady}
|
||||||
label="添加照片"
|
label="添加照片"
|
||||||
onChange={(nextUrl) => {
|
onChange={(nextUrl) => {
|
||||||
const envPhotoUrls = [...form.envPhotoUrls];
|
const envPhotoUrls = [...form.envPhotoUrls];
|
||||||
@@ -294,6 +318,8 @@ export default function StoreCreatePage() {
|
|||||||
mediaType="FILE"
|
mediaType="FILE"
|
||||||
accept="image/*,.pdf"
|
accept="image/*,.pdf"
|
||||||
value={form.contractUrl}
|
value={form.contractUrl}
|
||||||
|
wechatReady={wechatReady}
|
||||||
|
onWechatReadyChange={setWechatReady}
|
||||||
onChange={(contractUrl) => patchForm({ contractUrl })}
|
onChange={(contractUrl) => patchForm({ contractUrl })}
|
||||||
label="上传合同副本"
|
label="上传合同副本"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -932,6 +932,14 @@ html, body, #root {
|
|||||||
aspect-ratio: 1;
|
aspect-ratio: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.partner-wechat-auth-hint {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgba(166, 29, 36, 0.08);
|
||||||
|
border: 1px solid rgba(166, 29, 36, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
.partner-oss-upload-input {
|
.partner-oss-upload-input {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 1px;
|
width: 1px;
|
||||||
|
|||||||
@@ -71,7 +71,8 @@ export async function loginWithWechatCode(
|
|||||||
platform?: WechatLoginPlatform,
|
platform?: WechatLoginPlatform,
|
||||||
): Promise<WechatLoginResult> {
|
): Promise<WechatLoginResult> {
|
||||||
const resolvedPlatform = platform ?? (getRuntimePlatform() === 'mini' ? 'mini' : 'h5');
|
const resolvedPlatform = platform ?? (getRuntimePlatform() === 'mini' ? 'mini' : 'h5');
|
||||||
return apiRequest<WechatLoginResult>(config, '/auth/login/wechat', {
|
const loginPath = config.wechatLoginPath ?? '/auth/login/wechat';
|
||||||
|
return apiRequest<WechatLoginResult>(config, loginPath, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ code, platform: resolvedPlatform }),
|
body: JSON.stringify({ code, platform: resolvedPlatform }),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ export type WeixinSdkConfig = {
|
|||||||
clientApp: string;
|
clientApp: string;
|
||||||
/** 获取 access token(可选,登录后自动带) */
|
/** 获取 access token(可选,登录后自动带) */
|
||||||
getAccessToken?: () => string | null;
|
getAccessToken?: () => string | null;
|
||||||
|
/** 微信 code 登录接口,默认 /auth/login/wechat */
|
||||||
|
wechatLoginPath?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type WxInvokeResult<T> = {
|
export type WxInvokeResult<T> = {
|
||||||
|
|||||||
@@ -114,7 +114,17 @@ export class PartnerAuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('login/wechat')
|
@Post('login/wechat')
|
||||||
wechatLogin(@Body() dto: LoginWechatDto) {
|
@UseGuards(OptionalJwtAuthGuard)
|
||||||
|
wechatLogin(@Req() req: Request, @Body() dto: LoginWechatDto) {
|
||||||
|
const user = (req as Request & { user?: AuthUser }).user;
|
||||||
|
if (user?.actorType === 'PARTNER') {
|
||||||
|
return this.authService.bindPartnerWechat(
|
||||||
|
user.actorId,
|
||||||
|
dto.code,
|
||||||
|
ClientApp.PARTNER_H5,
|
||||||
|
dto.platform ?? 'h5',
|
||||||
|
);
|
||||||
|
}
|
||||||
return this.authService.loginPartnerWechat(dto.code, ClientApp.PARTNER_H5, dto.platform ?? 'h5');
|
return this.authService.loginPartnerWechat(dto.code, ClientApp.PARTNER_H5, dto.platform ?? 'h5');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -498,6 +498,51 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bindPartnerWechat(
|
||||||
|
partnerAccountId: bigint,
|
||||||
|
code: string,
|
||||||
|
clientApp: ClientApp,
|
||||||
|
platform: 'h5' | 'mini' = 'h5',
|
||||||
|
) {
|
||||||
|
this.assertWechatEnabled();
|
||||||
|
const session =
|
||||||
|
platform === 'mini'
|
||||||
|
? await this.wechatProvider.code2Session(code)
|
||||||
|
: await this.wechatProvider.oauth2AccessToken(code);
|
||||||
|
|
||||||
|
const account = await this.prisma.partnerAccount.findUnique({
|
||||||
|
where: { id: partnerAccountId },
|
||||||
|
include: { partner: true },
|
||||||
|
});
|
||||||
|
if (!account) throw new BadRequestException('合伙人账号不存在');
|
||||||
|
|
||||||
|
const conflict = await this.prisma.partnerAccount.findFirst({
|
||||||
|
where: { wxOpenId: session.openId, id: { not: partnerAccountId } },
|
||||||
|
});
|
||||||
|
if (conflict) {
|
||||||
|
throw new BadRequestException('该微信已绑定其他合伙人账号');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await this.prisma.partnerAccount.update({
|
||||||
|
where: { id: partnerAccountId },
|
||||||
|
data: {
|
||||||
|
wxOpenId: session.openId,
|
||||||
|
wxUnionId: session.unionId ?? account.wxUnionId,
|
||||||
|
lastLoginAt: new Date(),
|
||||||
|
},
|
||||||
|
include: { partner: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.issueToken('PARTNER', updated.id, clientApp, false, undefined, undefined, {
|
||||||
|
id: updated.id.toString(),
|
||||||
|
partnerId: updated.partnerId.toString(),
|
||||||
|
name: updated.name,
|
||||||
|
phone: updated.phone,
|
||||||
|
isPrimary: updated.isPrimary === 1,
|
||||||
|
companyName: updated.partner.companyName,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async loginPartnerWechat(code: string, clientApp: ClientApp, platform: 'h5' | 'mini' = 'h5') {
|
async loginPartnerWechat(code: string, clientApp: ClientApp, platform: 'h5' | 'mini' = 'h5') {
|
||||||
this.assertWechatEnabled();
|
this.assertWechatEnabled();
|
||||||
const session =
|
const session =
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export class PartnerMeController {
|
|||||||
phone: account.phone,
|
phone: account.phone,
|
||||||
isPrimary: account.isPrimary === 1,
|
isPrimary: account.isPrimary === 1,
|
||||||
companyName: account.partner.companyName,
|
companyName: account.partner.companyName,
|
||||||
|
hasWechat: !!account.wxOpenId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user