device.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * 设备信息工具
  3. */
  4. import { getStorage, setStorage } from './storage'
  5. const DEVICE_ID_KEY = 'DEVICE_ID'
  6. /**
  7. * 生成设备ID
  8. */
  9. function generateDeviceId(): string {
  10. return `device_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  11. }
  12. /**
  13. * 获取设备ID
  14. */
  15. export function getDeviceId(): string {
  16. let deviceId = getStorage<string>(DEVICE_ID_KEY)
  17. if (!deviceId) {
  18. deviceId = generateDeviceId()
  19. setStorage(DEVICE_ID_KEY, deviceId)
  20. }
  21. return deviceId
  22. }
  23. /**
  24. * 获取平台类型
  25. */
  26. export function getPlatform(): 'android' | 'ios' | 'h5' | 'mp-weixin' | 'mp-alipay' {
  27. // #ifdef APP-PLUS
  28. // @ts-ignore
  29. const platform = plus.os.name.toLowerCase()
  30. return platform === 'ios' ? 'ios' : 'android'
  31. // #endif
  32. // #ifdef H5
  33. return 'h5'
  34. // #endif
  35. // #ifdef MP-WEIXIN
  36. return 'mp-weixin'
  37. // #endif
  38. // #ifdef MP-ALIPAY
  39. return 'mp-alipay'
  40. // #endif
  41. return 'h5'
  42. }
  43. /**
  44. * 获取APP类型
  45. */
  46. export function getAppType(): string {
  47. const platform = getPlatform()
  48. return platform === 'android' || platform === 'ios' ? 'app' : platform
  49. }
  50. /**
  51. * 请求头:X-Platform、X-Version(普通请求统一带上,便于后端与网关识别客户端来源)。
  52. */
  53. export function getMobileClientHeaders(): Record<string, string> {
  54. const platform = getPlatform()
  55. let xPlatform = 'H5'
  56. if (platform === 'mp-weixin' || platform === 'mp-alipay') {
  57. xPlatform = 'MINI'
  58. } else if (platform === 'android' || platform === 'ios') {
  59. xPlatform = 'APP'
  60. }
  61. const { version } = getRuntimeClientVersion()
  62. return {
  63. 'X-Platform': xPlatform,
  64. 'X-Version': version || '1.0.0'
  65. }
  66. }
  67. /**
  68. * 小程序 / App 运行时版本号与整型构建号(非 H5 静态写死;与 manifest 发布配置一致)。
  69. */
  70. export function getRuntimeClientVersion(): { version: string; versionCode: number } {
  71. let version = ''
  72. let versionCode = 0
  73. // #ifdef MP-WEIXIN
  74. try {
  75. const ac = uni.getAccountInfoSync()
  76. const mp = ac?.miniProgram as { version?: string; versionCode?: number | string } | undefined
  77. if (mp?.version) version = String(mp.version).trim()
  78. const raw = mp?.versionCode
  79. if (raw !== undefined && raw !== null && raw !== '') {
  80. const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10)
  81. if (!Number.isNaN(n)) versionCode = n
  82. }
  83. } catch {
  84. /* ignore */
  85. }
  86. // #endif
  87. return { version, versionCode }
  88. }