hejianhao
2026-08-24 fd68a2574b62674f8a0679446b2eb3eb53969a78
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// 安卓业务插件桥接,保持与设备初始化页相同的插件入口。
let HardwarePlugin = null;
if (typeof uni !== 'undefined' && typeof uni.requireNativePlugin === 'function') {
  HardwarePlugin = uni.requireNativePlugin('business-module');
}
let initPromise = null;
let initResult = null;
 
const getPluginMethod = (methodNames = []) => {
  if (!HardwarePlugin) {
    return null;
  }
 
  return methodNames.find((methodName) => typeof HardwarePlugin[methodName] === 'function') || null;
};
 
export const HardwareAPI = {
  init(options = {}) {
    if (initResult) {
      return Promise.resolve(initResult);
    }
    if (initPromise) {
      return initPromise;
    }
 
    initPromise = new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
      const methodName = getPluginMethod(['init']);
      if (!methodName) {
        initPromise = null;
        reject(new Error('当前插件未提供初始化能力'));
        return;
      }
 
      let isSettled = false;
      let fallbackTimer = null;
      const finishInit = (result) => {
        if (isSettled) {
          return;
        }
        isSettled = true;
        if (fallbackTimer) {
          clearTimeout(fallbackTimer);
        }
        initResult = result;
        resolve(result);
      };
 
      try {
        HardwarePlugin[methodName](options, (result) => {
          if (result) {
            finishInit(result);
          }
        });
        fallbackTimer = setTimeout(() => {
          finishInit({ code: 200, msg: 'init_called_without_callback' });
        }, 300);
      } catch (error) {
        initPromise = null;
        reject(error);
      }
      // #endif
 
      // #ifndef APP-PLUS
      initResult = { code: 200, msg: 'success' };
      resolve(initResult);
      // #endif
    });
 
    return initPromise;
  },
 
  startScan(callback) {
    // #ifdef APP-PLUS
    const methodName = getPluginMethod(['startScan']);
    if (!methodName) {
      throw new Error('当前插件未提供 startScan 能力');
    }
    HardwarePlugin[methodName]({ duration: 2000 }, (result) => callback?.(result));
    return;
    // #endif
    // #ifndef APP-PLUS
    throw new Error('当前平台不支持 startScan');
    // #endif
  },
 
  openWebPay(options = {}) {
    return new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
      const methodName = getPluginMethod(['openWebPay']);
      if (!methodName) {
        reject(new Error('当前插件未提供网页支付能力'));
        return;
      }
      try {
        HardwarePlugin[methodName](options, resolve);
      } catch (error) {
        reject(error);
      }
      // #endif
      // #ifndef APP-PLUS
      reject(new Error('当前平台不支持网页支付'));
      // #endif
    });
  },
};