微信SDK接通

This commit is contained in:
2026-07-01 19:56:44 +08:00
parent a1cbfc7241
commit aea1513836
38 changed files with 1610 additions and 92 deletions
+12 -49
View File
@@ -1,3 +1,6 @@
import { getWechatLocation } from '@dukang/weixin-sdk';
import { weixinSdk } from './weixin';
export type ClientGpsLocation = {
province?: string;
city?: string;
@@ -7,55 +10,15 @@ export type ClientGpsLocation = {
address?: string;
};
type WxLocationResult = {
latitude: number;
longitude: number;
};
declare global {
interface Window {
wx?: {
getLocation?: (options: {
type?: string;
success?: (res: WxLocationResult) => void;
fail?: () => void;
}) => void;
};
}
}
/** 尝试获取客户端 GPS(微信优先,其次 H5 Geolocation),失败返回 null 不阻塞下单 */
export async function tryGetClientGpsLocation(): Promise<ClientGpsLocation | null> {
if (typeof window !== 'undefined' && window.wx?.getLocation) {
const wxResult = await new Promise<WxLocationResult | null>((resolve) => {
window.wx!.getLocation!({
type: 'gcj02',
success: (res) => resolve(res),
fail: () => resolve(null),
});
});
if (wxResult) {
return {
latitude: wxResult.latitude,
longitude: wxResult.longitude,
};
}
}
if (typeof navigator === 'undefined' || !navigator.geolocation) {
return null;
}
return new Promise((resolve) => {
navigator.geolocation.getCurrentPosition(
(pos) => {
resolve({
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
});
},
() => resolve(null),
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 60_000 },
);
});
const loc = await weixinSdk.getLocation();
if (!loc) return null;
return {
latitude: loc.latitude,
longitude: loc.longitude,
};
}
/** @deprecated 使用 tryGetClientGpsLocation */
export { getWechatLocation };