device.js 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // 获取设备唯一标识(优先 IMEI,退化到 uuid)
  2. // 仅在 APP-PLUS 生效;其他平台返回 null
  3. export function getDeviceImeiOrUuid() {
  4. return new Promise((resolve) => {
  5. try {
  6. // 规范化设备标识:处理逗号/分隔符/重复等,返回首个有效数字串
  7. function normalizeDeviceCode(raw) {
  8. try {
  9. if (!raw) return null;
  10. const text = String(raw).trim();
  11. // 拆分出所有数字片段(过滤空串)
  12. const parts = text.split(/[^0-9]+/).filter(Boolean);
  13. if (parts.length === 0) return null;
  14. // 去重并按长度排序,优先选择更长的数字串
  15. const uniq = [];
  16. for (const p of parts) {
  17. if (!uniq.includes(p)) uniq.push(p);
  18. }
  19. uniq.sort((a, b) => b.length - a.length);
  20. // 选择第一个长度足够的候选(常见 IMEI 为15位,这里放宽到>=10)
  21. const candidate = uniq.find((v) => v.length >= 10) || uniq[0];
  22. return candidate || null;
  23. } catch (e) {
  24. return raw ? String(raw) : null;
  25. }
  26. }
  27. // H5 平台:从 URL 参数读取 imei(用于调试或外部传入)
  28. // 不再依赖任何 debug 模块或本地开关
  29. // #ifdef H5
  30. try {
  31. if (typeof window !== 'undefined') {
  32. const params = new URLSearchParams(window.location.search || '');
  33. const urlImei = params.get('imei');
  34. if (urlImei) {
  35. const normalized = normalizeDeviceCode(urlImei);
  36. console.log('Device.js H5 从URL获取IMEI:', urlImei, '=>', normalized);
  37. resolve(normalized ? String(normalized) : null);
  38. return;
  39. }
  40. }
  41. } catch (e) {}
  42. // #endif
  43. // #ifdef APP-PLUS
  44. // 优先尝试异步获取 IMEI
  45. if (typeof plus !== 'undefined' && plus.device && typeof plus.device.getInfo === 'function') {
  46. plus.device.getInfo({
  47. success: (info) => {
  48. // info 结构按 5+ 文档约定,可能包含 imei/uuid 等
  49. if (info && info.imei) {
  50. const normalized = normalizeDeviceCode(info.imei);
  51. resolve(normalized ? String(normalized) : null);
  52. return;
  53. }
  54. // 退化到 uuid
  55. if (plus.device && plus.device.uuid) {
  56. resolve(String(plus.device.uuid));
  57. return;
  58. }
  59. resolve(null);
  60. },
  61. fail: () => {
  62. // 失败后退化到同步获取
  63. try {
  64. if (plus.device && plus.device.imei) {
  65. const normalized = normalizeDeviceCode(plus.device.imei);
  66. resolve(normalized ? String(normalized) : null);
  67. return;
  68. }
  69. if (plus.device && plus.device.uuid) {
  70. resolve(String(plus.device.uuid));
  71. return;
  72. }
  73. } catch (e) {}
  74. resolve(null);
  75. }
  76. });
  77. return;
  78. }
  79. // 没有 getInfo,尝试直接读取
  80. if (plus.device && plus.device.imei) {
  81. resolve(String(plus.device.imei));
  82. return;
  83. }
  84. if (plus.device && plus.device.uuid) {
  85. resolve(String(plus.device.uuid));
  86. return;
  87. }
  88. // #endif
  89. } catch (e) {}
  90. console.log('Device.js H5环境返回null (非APP-PLUS且非debug模式)');
  91. resolve(null);
  92. });
  93. }