Files
dukang/server/dukang-api/src/integrations/map/tencent-lbs.sign.ts
T
2026-08-04 21:38:49 +08:00

40 lines
1.2 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 { createHash } from 'node:crypto';
const LBS_HOST = 'https://apis.map.qq.com';
/**
* 腾讯位置服务 WebServiceAPIGET)签名 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()}`;
}