79 lines
2.3 KiB
TypeScript
79 lines
2.3 KiB
TypeScript
const UUID_STORAGE_KEY = 'app_uuid';
|
||
|
||
/**
|
||
* 生成一个随机十六进制字符
|
||
*/
|
||
function randomHexChar(): string {
|
||
return Math.floor(Math.random() * 16).toString(16);
|
||
}
|
||
|
||
/**
|
||
* 生成符合 UUID v4 标准的 UUID
|
||
* UUID v4 格式:xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
|
||
* 其中:
|
||
* - x 是任意十六进制数字
|
||
* - 第 13 个字符必须是 '4'(表示版本 4)
|
||
* - 第 17 个字符必须是 8, 9, a, 或 b 中的一个(表示变体)
|
||
*
|
||
* @returns 符合 UUID v4 标准的字符串
|
||
*/
|
||
export function generateUUID(): string {
|
||
// UUID v4 格式:xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
|
||
// 生成随机十六进制数字
|
||
const chars: string[] = [];
|
||
|
||
// 生成 32 个十六进制字符
|
||
for (let i = 0; i < 32; i++) {
|
||
if (i === 12) {
|
||
// 第 13 个字符必须是 '4'(版本号)
|
||
chars[i] = '4';
|
||
} else if (i === 16) {
|
||
// 第 17 个字符必须是 8, 9, a, 或 b 中的一个(变体)
|
||
const variant = ['8', '9', 'a', 'b'][Math.floor(Math.random() * 4)];
|
||
chars[i] = variant;
|
||
} else {
|
||
chars[i] = randomHexChar();
|
||
}
|
||
}
|
||
|
||
// 按照 UUID 格式组合:xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
|
||
return [
|
||
chars.slice(0, 8).join(''),
|
||
chars.slice(8, 12).join(''),
|
||
chars.slice(12, 16).join(''),
|
||
chars.slice(16, 20).join(''),
|
||
chars.slice(20, 32).join(''),
|
||
].join('-');
|
||
}
|
||
|
||
export function setAppUUID(uuid: string): void {
|
||
wx.setStorageSync(UUID_STORAGE_KEY, uuid);
|
||
}
|
||
|
||
/**
|
||
* 获取应用的 UUID
|
||
* 优先从 globalData 获取,如果没有则从 localStorage 获取
|
||
*/
|
||
export function getAppUUID(): string {
|
||
try {
|
||
// 尝试从 globalData 获取
|
||
const app = getApp<IAppOption>();
|
||
if (app && app.globalData && app.globalData.uuid) {
|
||
return app.globalData.uuid;
|
||
}
|
||
|
||
// 如果 globalData 中没有,从 localStorage 获取
|
||
const uuid = wx.getStorageSync(UUID_STORAGE_KEY);
|
||
if (uuid) {
|
||
return uuid;
|
||
}
|
||
|
||
// 如果都没有,返回空字符串(这种情况不应该发生,因为 app.ts 会在启动时生成)
|
||
console.warn('UUID 未找到,请确保应用已正确启动');
|
||
return '';
|
||
} catch (error) {
|
||
console.error('获取 UUID 失败:', error);
|
||
return '';
|
||
}
|
||
}
|