feat(partner): map pick UX and Tencent LBS SN signature
Hide locate on store forms; restore optimized locpicker overlay. Add TENCENT_LBS_SECRET_KEY and server-side sig for WebServiceAPI. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { ClientRuntimeConfig } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import {
|
||||
placeToPicked,
|
||||
type LbsPlaceItem,
|
||||
buildTencentLocPickerUrl,
|
||||
parseTencentLocPickerMessage,
|
||||
type TencentPickedLocation,
|
||||
} from '../lib/tencentLocPicker';
|
||||
|
||||
@@ -12,117 +13,84 @@ type Props = {
|
||||
onPick: (loc: TencentPickedLocation) => void;
|
||||
latitude?: number | null;
|
||||
longitude?: number | null;
|
||||
/** 保留兼容,iframe 选点不使用 */
|
||||
region?: string | null;
|
||||
};
|
||||
|
||||
let cachedKey: string | null | undefined;
|
||||
|
||||
async function loadTencentLbsKey(): Promise<string> {
|
||||
if (cachedKey) return cachedKey;
|
||||
const cfg = await request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config', {
|
||||
silent: true,
|
||||
});
|
||||
const key = (cfg.tencentLbsKey || '').trim();
|
||||
if (!key) {
|
||||
throw new Error('未配置腾讯位置服务 Key,请联系管理员在系统设置中配置');
|
||||
}
|
||||
cachedKey = key;
|
||||
return key;
|
||||
}
|
||||
|
||||
export default function TencentLocPickerOverlay({
|
||||
open,
|
||||
onClose,
|
||||
onPick,
|
||||
latitude,
|
||||
longitude,
|
||||
region,
|
||||
}: Props) {
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [items, setItems] = useState<LbsPlaceItem[]>([]);
|
||||
const [key, setKey] = useState<string | null>(cachedKey ?? null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [pending, setPending] = useState<TencentPickedLocation | null>(null);
|
||||
const [hint, setHint] = useState('输入地点名称搜索');
|
||||
const seqRef = useRef(0);
|
||||
const [iframeReady, setIframeReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setKeyword('');
|
||||
setItems([]);
|
||||
setPending(null);
|
||||
setHint('输入地点名称搜索');
|
||||
setIframeReady(false);
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
const lat = latitude != null ? Number(latitude) : NaN;
|
||||
const lng = longitude != null ? Number(longitude) : NaN;
|
||||
if (Number.isFinite(lat) && Number.isFinite(lng) && !(lat === 0 && lng === 0)) {
|
||||
void loadNearby(lat, lng);
|
||||
let cancelled = false;
|
||||
if (key) return;
|
||||
setLoading(true);
|
||||
void loadTencentLbsKey()
|
||||
.then((k) => {
|
||||
if (!cancelled) setKey(k);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e instanceof Error ? e.message : '加载地图配置失败');
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, key]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onMessage(event: MessageEvent) {
|
||||
// 仅处理腾讯选点回传,忽略其它来源噪声
|
||||
const picked = parseTencentLocPickerMessage(event.data);
|
||||
if (!picked) return;
|
||||
setPending(picked);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
window.addEventListener('message', onMessage);
|
||||
return () => window.removeEventListener('message', onMessage);
|
||||
}, [open]);
|
||||
|
||||
async function loadNearby(lat: number, lng: number) {
|
||||
const seq = ++seqRef.current;
|
||||
setLoading(true);
|
||||
setHint('正在加载附近地点…');
|
||||
try {
|
||||
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||
'PARTNER_H5',
|
||||
`/common/lbs/nearby?lat=${encodeURIComponent(String(lat))}&lng=${encodeURIComponent(String(lng))}`,
|
||||
{ silent: true },
|
||||
);
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems(res.items ?? []);
|
||||
setHint(res.items?.length ? `附近 ${res.items.length} 个地点` : '附近暂无地点,请搜索');
|
||||
} catch (e) {
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems([]);
|
||||
setHint(e instanceof Error ? e.message : '加载附近地点失败');
|
||||
} finally {
|
||||
if (seq === seqRef.current) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSearch() {
|
||||
const trimmed = keyword.trim();
|
||||
if (!trimmed) {
|
||||
setHint('请输入搜索关键词');
|
||||
return;
|
||||
}
|
||||
const seq = ++seqRef.current;
|
||||
setLoading(true);
|
||||
setHint('搜索中…');
|
||||
try {
|
||||
const params = new URLSearchParams({ keyword: trimmed });
|
||||
if (region?.trim()) params.set('region', region.trim());
|
||||
const lat = latitude != null ? Number(latitude) : NaN;
|
||||
const lng = longitude != null ? Number(longitude) : NaN;
|
||||
if (Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||
params.set('lat', String(lat));
|
||||
params.set('lng', String(lng));
|
||||
}
|
||||
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||
'PARTNER_H5',
|
||||
`/common/lbs/suggest?${params.toString()}`,
|
||||
{ silent: true },
|
||||
);
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems(res.items ?? []);
|
||||
setHint(res.items?.length ? `找到 ${res.items.length} 个结果` : '无匹配结果');
|
||||
} catch (e) {
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems([]);
|
||||
setHint(e instanceof Error ? e.message : '搜索失败');
|
||||
} finally {
|
||||
if (seq === seqRef.current) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function useBrowserLocation() {
|
||||
if (!navigator.geolocation) {
|
||||
setHint('当前浏览器不支持定位');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
const lat = pos.coords.latitude;
|
||||
const lng = pos.coords.longitude;
|
||||
setPending({ latitude: lat, longitude: lng, name: '当前位置' });
|
||||
void loadNearby(lat, lng);
|
||||
},
|
||||
() => {
|
||||
setLoading(false);
|
||||
setHint('定位失败,请检查定位权限');
|
||||
},
|
||||
{ enableHighAccuracy: true, timeout: 12000 },
|
||||
);
|
||||
}
|
||||
const src = useMemo(() => {
|
||||
if (!key) return '';
|
||||
const lat = latitude != null ? Number(latitude) : undefined;
|
||||
const lng = longitude != null ? Number(longitude) : undefined;
|
||||
return buildTencentLocPickerUrl(key, {
|
||||
latitude: lat != null && Number.isFinite(lat) ? lat : undefined,
|
||||
longitude: lng != null && Number.isFinite(lng) ? lng : undefined,
|
||||
});
|
||||
}, [key, latitude, longitude]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
@@ -134,6 +102,7 @@ export default function TencentLocPickerOverlay({
|
||||
|
||||
return (
|
||||
<div
|
||||
className="partner-locpicker-overlay"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
@@ -141,6 +110,12 @@ export default function TencentLocPickerOverlay({
|
||||
background: '#fff',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
// 微信内全屏更稳:避免 100vh 被地址栏裁切
|
||||
height: '100dvh',
|
||||
maxHeight: '-webkit-fill-available',
|
||||
paddingTop: 'env(safe-area-inset-top)',
|
||||
paddingBottom: 'env(safe-area-inset-bottom)',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -148,20 +123,31 @@ export default function TencentLocPickerOverlay({
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
padding: '12px 16px',
|
||||
padding: '10px 12px',
|
||||
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
||||
flexShrink: 0,
|
||||
gap: 8,
|
||||
background: '#fff',
|
||||
}}
|
||||
>
|
||||
<button type="button" className="partner-btn-outline" style={{ padding: '6px 12px' }} onClick={onClose}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '8px 14px', minWidth: 64 }}
|
||||
onClick={onClose}
|
||||
>
|
||||
关闭
|
||||
</button>
|
||||
<span style={{ fontWeight: 600 }}>地图选点</span>
|
||||
<span style={{ fontWeight: 600, fontSize: 16 }}>腾讯地图选点</span>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ padding: '6px 12px', opacity: pending ? 1 : 0.45, width: 'auto' }}
|
||||
style={{
|
||||
padding: '8px 14px',
|
||||
minWidth: 64,
|
||||
opacity: pending ? 1 : 0.45,
|
||||
width: 'auto',
|
||||
}}
|
||||
disabled={!pending}
|
||||
onClick={confirmPick}
|
||||
>
|
||||
@@ -169,95 +155,89 @@ export default function TencentLocPickerOverlay({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(0,0,0,0.04)', flexShrink: 0 }}>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void runSearch();
|
||||
}}
|
||||
placeholder="输入小区 / 写字楼 / 门店名称"
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '10px 12px',
|
||||
border: '1px solid rgba(0,0,0,0.12)',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ width: 'auto', padding: '8px 14px' }}
|
||||
disabled={loading}
|
||||
onClick={() => void runSearch()}
|
||||
>
|
||||
搜索
|
||||
</button>
|
||||
{pending ? (
|
||||
<div
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: '10px 14px',
|
||||
borderBottom: '1px solid rgba(0,0,0,0.04)',
|
||||
flexShrink: 0,
|
||||
background: 'rgba(166, 29, 36, 0.04)',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--color-heritage-red, #a61d24)' }}>
|
||||
已选位置
|
||||
</div>
|
||||
<div className="label-md text-muted" style={{ marginTop: 4, fontSize: 13, lineHeight: 1.4 }}>
|
||||
{pending.name || '地图选点'}
|
||||
{pending.address ? ` · ${pending.address}` : ''}
|
||||
<br />
|
||||
{pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8, alignItems: 'center' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '6px 12px' }}
|
||||
disabled={loading}
|
||||
onClick={useBrowserLocation}
|
||||
>
|
||||
定位当前位置
|
||||
</button>
|
||||
<span className="label-md text-muted">{hint}</span>
|
||||
</div>
|
||||
{pending ? (
|
||||
<p className="label-md text-muted" style={{ margin: '8px 0 0' }}>
|
||||
已选 {pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
|
||||
{pending.name ? ` · ${pending.name}` : ''}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<p
|
||||
className="label-md text-muted"
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: '8px 14px',
|
||||
borderBottom: '1px solid rgba(0,0,0,0.04)',
|
||||
flexShrink: 0,
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
在地图上点选或搜索地点,选中后点右上角「确认」
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
|
||||
{loading && !items.length ? (
|
||||
<div style={{ flex: 1, minHeight: 0, position: 'relative', background: '#f5f5f5' }}>
|
||||
{loading ? (
|
||||
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||
加载中…
|
||||
正在加载腾讯地图…
|
||||
</p>
|
||||
) : items.length ? (
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
|
||||
{items.map((item) => {
|
||||
const active =
|
||||
pending?.latitude === item.latitude && pending?.longitude === item.longitude;
|
||||
return (
|
||||
<li key={`${item.id}-${item.latitude}-${item.longitude}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPending(placeToPicked(item))}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '12px 16px',
|
||||
border: 0,
|
||||
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
||||
background: active ? 'rgba(166, 29, 36, 0.06)' : '#fff',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontWeight: 600, fontSize: 15 }}>{item.title}</div>
|
||||
<div className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||
{item.address}
|
||||
</div>
|
||||
<div className="label-md text-muted" style={{ marginTop: 2, fontSize: 12 }}>
|
||||
{item.latitude.toFixed(6)}, {item.longitude.toFixed(6)}
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||
{hint}
|
||||
</p>
|
||||
)}
|
||||
) : error ? (
|
||||
<div style={{ padding: 24 }}>
|
||||
<p className="label-md" style={{ color: 'var(--color-heritage-red, #a61d24)' }}>
|
||||
{error}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 12 }}>
|
||||
请确认系统设置中已配置腾讯位置服务 Key,并白名单 apis.map.qq.com。
|
||||
</p>
|
||||
</div>
|
||||
) : src ? (
|
||||
<>
|
||||
{!iframeReady ? (
|
||||
<p
|
||||
className="label-md text-muted"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
margin: 0,
|
||||
zIndex: 1,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
地图加载中…
|
||||
</p>
|
||||
) : null}
|
||||
<iframe
|
||||
title="腾讯地图选点"
|
||||
src={src}
|
||||
allow="geolocation *"
|
||||
onLoad={() => setIframeReady(true)}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: 0,
|
||||
display: 'block',
|
||||
background: '#fff',
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -24,3 +24,78 @@ export function placeToPicked(item: LbsPlaceItem): TencentPickedLocation {
|
||||
cityname: item.city || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
type LocPickerMessage = {
|
||||
module?: string;
|
||||
latlng?: { lat?: number; lng?: number };
|
||||
poiaddress?: string;
|
||||
poiname?: string;
|
||||
cityname?: string;
|
||||
};
|
||||
|
||||
const REFERER = 'dukang';
|
||||
|
||||
function coerceMessageData(data: unknown): LocPickerMessage | null {
|
||||
if (data == null) return null;
|
||||
if (typeof data === 'string') {
|
||||
const trimmed = data.trim();
|
||||
if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) return null;
|
||||
try {
|
||||
return JSON.parse(trimmed) as LocPickerMessage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (typeof data === 'object') return data as LocPickerMessage;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 腾讯地图选点组件(iframe) */
|
||||
export function buildTencentLocPickerUrl(
|
||||
key: string,
|
||||
options?: { latitude?: number; longitude?: number },
|
||||
): string {
|
||||
const params = new URLSearchParams({
|
||||
search: '1',
|
||||
type: '1',
|
||||
key,
|
||||
referer: REFERER,
|
||||
policy: '1',
|
||||
total: '20',
|
||||
radius: '2000',
|
||||
mapdraggable: '1',
|
||||
});
|
||||
const lat = options?.latitude;
|
||||
const lng = options?.longitude;
|
||||
if (
|
||||
lat != null &&
|
||||
lng != null &&
|
||||
Number.isFinite(lat) &&
|
||||
Number.isFinite(lng) &&
|
||||
!(lat === 0 && lng === 0)
|
||||
) {
|
||||
params.set('coord', `${lat},${lng}`);
|
||||
params.set('coordtype', '5');
|
||||
}
|
||||
return `https://apis.map.qq.com/tools/locpicker?${params.toString()}`;
|
||||
}
|
||||
|
||||
export function parseTencentLocPickerMessage(data: unknown): TencentPickedLocation | null {
|
||||
const loc = coerceMessageData(data);
|
||||
if (!loc || loc.module !== 'locationPicker') return null;
|
||||
const lat = Number(loc.latlng?.lat);
|
||||
const lng = Number(loc.latlng?.lng);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
||||
|
||||
let name = loc.poiname?.trim() || undefined;
|
||||
const address = loc.poiaddress?.trim() || undefined;
|
||||
if (name === '我的位置' && address) name = address;
|
||||
|
||||
return {
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
address,
|
||||
name,
|
||||
cityname: loc.cityname?.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { resolveRegionBinding } from '../lib/china-region';
|
||||
|
||||
import { checkStorePhoneAvailable } from '../lib/storePhone';
|
||||
|
||||
import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate';
|
||||
import { formatStoreCoords } from '../lib/storeLocate';
|
||||
|
||||
import { fetchPartnerCities, type OpenCityOption } from '../lib/upload';
|
||||
|
||||
@@ -101,8 +101,6 @@ export default function StoreCreatePage() {
|
||||
|
||||
const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]);
|
||||
|
||||
const [locating, setLocating] = useState(false);
|
||||
|
||||
const [mapPickerOpen, setMapPickerOpen] = useState(false);
|
||||
|
||||
const draftSaveDisabledRef = useRef(false);
|
||||
@@ -662,31 +660,6 @@ export default function StoreCreatePage() {
|
||||
<textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} />
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '8px 12px', fontSize: 13 }}
|
||||
disabled={locating}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setLocating(true);
|
||||
try {
|
||||
const pos = await locateStorePosition();
|
||||
patchForm({
|
||||
latitude: String(pos.latitude),
|
||||
longitude: String(pos.longitude),
|
||||
});
|
||||
toastSuccess('已获取当前坐标');
|
||||
} catch (e) {
|
||||
toastError(e instanceof Error ? e.message : '定位失败');
|
||||
} finally {
|
||||
setLocating(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{locating ? '定位中…' : '获取当前位置'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
@@ -698,7 +671,7 @@ export default function StoreCreatePage() {
|
||||
<span className="label-md text-muted">
|
||||
{formatStoreCoords(form.latitude, form.longitude)
|
||||
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
|
||||
: '未定位(可定位或地图选点)'}
|
||||
: '未选点(可地图选点)'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { canManagePartnerStore } from '../lib/partnerAccess';
|
||||
import { normalizeStringArray, patchEnvPhotoAt } from '../lib/storeDraft';
|
||||
import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate';
|
||||
import { formatStoreCoords } from '../lib/storeLocate';
|
||||
import OssUploadField from '../components/OssUploadField';
|
||||
import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay';
|
||||
import {
|
||||
@@ -55,7 +55,6 @@ export default function StoreDetailPage() {
|
||||
const [statusSaving, setStatusSaving] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [mediaSaving, setMediaSaving] = useState(false);
|
||||
const [locating, setLocating] = useState(false);
|
||||
const [mapPickerOpen, setMapPickerOpen] = useState(false);
|
||||
const [actionError, setActionError] = useState('');
|
||||
const [closeConfirmOpen, setCloseConfirmOpen] = useState(false);
|
||||
@@ -346,35 +345,6 @@ export default function StoreDetailPage() {
|
||||
<textarea disabled={readOnly} rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
|
||||
{!readOnly ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '8px 12px', fontSize: 13 }}
|
||||
disabled={locating}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setLocating(true);
|
||||
setActionError('');
|
||||
try {
|
||||
const pos = await locateStorePosition();
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
latitude: String(pos.latitude),
|
||||
longitude: String(pos.longitude),
|
||||
}));
|
||||
toastSuccess('已获取当前坐标');
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '定位失败';
|
||||
setActionError(msg);
|
||||
toastError(msg);
|
||||
} finally {
|
||||
setLocating(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{locating ? '定位中…' : '获取当前位置'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
@@ -386,7 +356,7 @@ export default function StoreDetailPage() {
|
||||
<span className="label-md text-muted">
|
||||
{formatStoreCoords(form.latitude, form.longitude)
|
||||
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
|
||||
: '未定位'}
|
||||
: '未选点(可地图选点)'}
|
||||
</span>
|
||||
</div>
|
||||
) : formatStoreCoords(form.latitude, form.longitude) ? (
|
||||
|
||||
@@ -21,8 +21,13 @@ export interface AppConfig {
|
||||
aliyunSmsProxyOrderTemplateCode: string;
|
||||
aliyunSmsAccessKeyId: string;
|
||||
aliyunSmsAccessKeySecret: string;
|
||||
/** 腾讯位置服务 Key(逆地理编码) */
|
||||
/** 腾讯位置服务 Key(逆地理编码 / 地点搜索) */
|
||||
tencentLbsKey: string;
|
||||
/**
|
||||
* 腾讯位置服务 SecretKey(SK)
|
||||
* 控制台开启 WebServiceAPI 签名校验后生成;仅服务端签名用,勿下发前端
|
||||
*/
|
||||
tencentLbsSecretKey: string;
|
||||
/** C 端 H5 落地页(推广码二维码链接前缀) */
|
||||
userH5Url: string;
|
||||
}
|
||||
@@ -127,6 +132,7 @@ export function loadAppConfig(env?: Record<string, string | undefined>): AppConf
|
||||
aliyunSmsAccessKeyId: e.ALIYUN_SMS_ACCESS_KEY_ID ?? e.OSS_ACCESS_KEY_ID ?? '',
|
||||
aliyunSmsAccessKeySecret: e.ALIYUN_SMS_ACCESS_KEY_SECRET ?? e.OSS_ACCESS_KEY_SECRET ?? '',
|
||||
tencentLbsKey: e.TENCENT_LBS_KEY ?? '',
|
||||
tencentLbsSecretKey: e.TENCENT_LBS_SECRET_KEY ?? '',
|
||||
userH5Url: (e.USER_H5_URL || DEFAULT_USER_H5_URL).replace(/\/$/, ''),
|
||||
};
|
||||
return {
|
||||
|
||||
@@ -60,9 +60,10 @@ WX_PAY_NOTIFY_URL=https://api.dukanghaoke.com/api/v1/callbacks/wechat/pay
|
||||
WECOM_AIBOT_ENABLED=false
|
||||
|
||||
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
||||
# 控制台须开启 WebServiceAPI;服务端调用建议 Key 不设域名白名单,或改用 IP 白名单
|
||||
# (浏览器内嵌官方选点组件已弃用,避免 mapapi.qq.com / formatted_addresses 崩溃)
|
||||
# 控制台须开启 WebServiceAPI;推荐开启「签名校验」并配置下方 SK(服务端自动附 sig)
|
||||
# 未开签名校验时可只填 KEY;SK 勿下发前端
|
||||
TENCENT_LBS_KEY=
|
||||
TENCENT_LBS_SECRET_KEY=
|
||||
|
||||
# 阿里云 OSS(ali-oss@6.x;凭证齐全时直传,缺失则服务端报错)
|
||||
# RAM 用户需具备 PutObject 权限;可在控制台 Bucket 授权策略中为该 RAM UID 授予读写
|
||||
|
||||
@@ -107,7 +107,25 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
||||
{ key: 'OSS_MAX_UPLOAD_BYTES', label: '单文件上限(字节)', group: G.oss, type: 'number', requiresRestart: false },
|
||||
|
||||
{ key: 'USER_H5_URL', label: 'C 端 H5 落地页', group: G.app, type: 'string', requiresRestart: false },
|
||||
{ key: 'TENCENT_LBS_KEY', label: '腾讯位置服务 Key(须开 WebServiceAPI;服务端地点搜索/地理编码)', group: G.app, type: 'password', secret: true, requiresRestart: false },
|
||||
{
|
||||
key: 'TENCENT_LBS_KEY',
|
||||
label: '腾讯位置服务 Key',
|
||||
group: G.app,
|
||||
type: 'password',
|
||||
secret: true,
|
||||
requiresRestart: false,
|
||||
description: '须开启 WebServiceAPI;服务端地理编码/地点搜索与前端选点组件共用',
|
||||
},
|
||||
{
|
||||
key: 'TENCENT_LBS_SECRET_KEY',
|
||||
label: '腾讯位置服务 SecretKey(SK)',
|
||||
group: G.app,
|
||||
type: 'password',
|
||||
secret: true,
|
||||
requiresRestart: false,
|
||||
description:
|
||||
'控制台开启 WebServiceAPI「签名校验」后生成;仅服务端计算 sig,勿泄露。配置后接口请求自动附带签名',
|
||||
},
|
||||
|
||||
{ key: 'DEPLOY_WEBHOOK_URL', label: '发布 Webhook URL', group: G.deploy, type: 'string', requiresRestart: false },
|
||||
{ key: 'DEPLOY_WEBHOOK_SECRET', label: '发布 Webhook Secret', group: G.deploy, type: 'password', secret: true, requiresRestart: false },
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import type { WechatActorRef } from '../wechat/wechat-log.util';
|
||||
import { buildTencentLbsRequestUrl } from './tencent-lbs.sign';
|
||||
|
||||
export type ReverseGeocodeResult = {
|
||||
province: string;
|
||||
@@ -54,11 +55,22 @@ export class TencentLbsProvider {
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/** 每次读取,避免构造时缓存、以及系统设置热更新后仍用旧 Key */
|
||||
/** 每次读取,避免构造时缓存、以及系统设置热更新后仍用旧 Key/SK */
|
||||
private getLbsKey() {
|
||||
return (loadAppConfig().tencentLbsKey || '').trim();
|
||||
}
|
||||
|
||||
private getLbsSecretKey() {
|
||||
return (loadAppConfig().tencentLbsSecretKey || '').trim();
|
||||
}
|
||||
|
||||
private lbsUrl(path: string, params: Record<string, string>) {
|
||||
return buildTencentLbsRequestUrl(path, params, {
|
||||
key: this.getLbsKey(),
|
||||
secretKey: this.getLbsSecretKey(),
|
||||
});
|
||||
}
|
||||
|
||||
isEnabled() {
|
||||
return !!this.getLbsKey();
|
||||
}
|
||||
@@ -91,12 +103,10 @@ export class TencentLbsProvider {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL('https://apis.map.qq.com/ws/geocoder/v1/');
|
||||
url.searchParams.set('address', trimmed);
|
||||
url.searchParams.set('key', this.getLbsKey());
|
||||
const url = this.lbsUrl('/ws/geocoder/v1', { address: trimmed });
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString());
|
||||
const res = await fetch(url);
|
||||
const data = (await res.json()) as {
|
||||
status?: number;
|
||||
message?: string;
|
||||
@@ -169,14 +179,13 @@ export class TencentLbsProvider {
|
||||
return null;
|
||||
}
|
||||
|
||||
const location = `${latitude},${longitude}`;
|
||||
const url = new URL('https://apis.map.qq.com/ws/geocoder/v1/');
|
||||
url.searchParams.set('location', location);
|
||||
url.searchParams.set('key', this.getLbsKey());
|
||||
url.searchParams.set('get_poi', '0');
|
||||
const url = this.lbsUrl('/ws/geocoder/v1', {
|
||||
location: `${latitude},${longitude}`,
|
||||
get_poi: '0',
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString());
|
||||
const res = await fetch(url);
|
||||
const data = (await res.json()) as {
|
||||
status?: number;
|
||||
message?: string;
|
||||
@@ -265,25 +274,25 @@ export class TencentLbsProvider {
|
||||
return { items: [], error: 'TENCENT_LBS_KEY 未配置' };
|
||||
}
|
||||
|
||||
const url = new URL('https://apis.map.qq.com/ws/place/v1/suggestion');
|
||||
url.searchParams.set('keyword', trimmed.slice(0, 64));
|
||||
url.searchParams.set('key', this.getLbsKey());
|
||||
url.searchParams.set('policy', '1');
|
||||
url.searchParams.set('page_index', '1');
|
||||
url.searchParams.set('page_size', '20');
|
||||
const params: Record<string, string> = {
|
||||
keyword: trimmed.slice(0, 64),
|
||||
policy: '1',
|
||||
page_index: '1',
|
||||
page_size: '20',
|
||||
};
|
||||
const region = options?.region?.trim();
|
||||
if (region) url.searchParams.set('region', region);
|
||||
if (region) params.region = region;
|
||||
if (
|
||||
options?.latitude != null &&
|
||||
options?.longitude != null &&
|
||||
Number.isFinite(options.latitude) &&
|
||||
Number.isFinite(options.longitude)
|
||||
) {
|
||||
url.searchParams.set('location', `${options.latitude},${options.longitude}`);
|
||||
params.location = `${options.latitude},${options.longitude}`;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString());
|
||||
const res = await fetch(this.lbsUrl('/ws/place/v1/suggestion', params));
|
||||
const data = (await res.json()) as {
|
||||
status?: number;
|
||||
message?: string;
|
||||
@@ -315,14 +324,14 @@ export class TencentLbsProvider {
|
||||
}
|
||||
|
||||
const radius = Math.min(5000, Math.max(200, Math.round(radiusMeters)));
|
||||
const url = new URL('https://apis.map.qq.com/ws/place/v1/explore');
|
||||
url.searchParams.set('boundary', `nearby(${latitude},${longitude},${radius})`);
|
||||
url.searchParams.set('policy', '1');
|
||||
url.searchParams.set('page_size', '20');
|
||||
url.searchParams.set('key', this.getLbsKey());
|
||||
const url = this.lbsUrl('/ws/place/v1/explore', {
|
||||
boundary: `nearby(${latitude},${longitude},${radius})`,
|
||||
policy: '1',
|
||||
page_size: '20',
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString());
|
||||
const res = await fetch(url);
|
||||
const data = (await res.json()) as {
|
||||
status?: number;
|
||||
message?: string;
|
||||
@@ -352,13 +361,13 @@ export class TencentLbsProvider {
|
||||
return { item: null, error: 'TENCENT_LBS_KEY 未配置' };
|
||||
}
|
||||
|
||||
const url = new URL('https://apis.map.qq.com/ws/geocoder/v1/');
|
||||
url.searchParams.set('location', `${latitude},${longitude}`);
|
||||
url.searchParams.set('key', this.getLbsKey());
|
||||
url.searchParams.set('get_poi', '1');
|
||||
const url = this.lbsUrl('/ws/geocoder/v1', {
|
||||
location: `${latitude},${longitude}`,
|
||||
get_poi: '1',
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString());
|
||||
const res = await fetch(url);
|
||||
const data = (await res.json()) as {
|
||||
status?: number;
|
||||
message?: string;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const LBS_HOST = 'https://apis.map.qq.com';
|
||||
|
||||
/**
|
||||
* 腾讯位置服务 WebServiceAPI(GET)签名 URL。
|
||||
* 控制台开启 SN/签名校验后须附带 sig;SecretKey 仅服务端使用。
|
||||
*
|
||||
* sig = md5(请求路径 + "?" + 按参数名升序的原始 query + SK)
|
||||
* @see https://lbs.qq.com/FAQ/server_faq.html
|
||||
*/
|
||||
export function buildTencentLbsRequestUrl(
|
||||
path: string,
|
||||
params: Record<string, string>,
|
||||
options: { key: string; secretKey?: string },
|
||||
): string {
|
||||
const key = options.key.trim();
|
||||
if (!key) {
|
||||
throw new Error('TENCENT_LBS_KEY 未配置');
|
||||
}
|
||||
|
||||
const pathname = (path.startsWith('/') ? path : `/${path}`).replace(/\/+$/, '') || '/';
|
||||
const all: Record<string, string> = { ...params, key };
|
||||
const sortedKeys = Object.keys(all).sort();
|
||||
const rawQuery = sortedKeys.map((k) => `${k}=${all[k]}`).join('&');
|
||||
|
||||
const search = new URLSearchParams();
|
||||
for (const k of sortedKeys) {
|
||||
search.set(k, all[k]);
|
||||
}
|
||||
|
||||
const sk = options.secretKey?.trim();
|
||||
if (sk) {
|
||||
const sig = createHash('md5').update(`${pathname}?${rawQuery}${sk}`).digest('hex');
|
||||
search.set('sig', sig);
|
||||
}
|
||||
|
||||
return `${LBS_HOST}${pathname}?${search.toString()}`;
|
||||
}
|
||||
Reference in New Issue
Block a user