40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
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()}`;
|
||
}
|