@lambo-design-mobile/lambo-js-bridge 1.0.0-beta.4 → 1.0.0-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,314 +1,513 @@
1
1
  /* eslint-disable @typescript-eslint/no-unused-vars */
2
2
  /* eslint-disable no-undef */
3
3
 
4
- import ajax from "@lambo-design-mobile/shared/utils/ajax";
5
- import config from "@lambo-design-mobile/shared/config/config";
6
- import coordtransform from "coordtransform";
4
+ import ajax from '@lambo-design-mobile/shared/utils/ajax';
5
+ import config from '@lambo-design-mobile/shared/config/config';
6
+ // import coordtransform from "coordtransform";
7
+ import {
8
+ getAddress,
9
+ initBdMap,
10
+ getAddressByType,
11
+ getAxisByType,
12
+ } from './BdMapUtils';
7
13
 
8
14
  class WechatAdapter {
9
- constructor(_options) {
10
- this.appId = _options.wechatId; // 保存 appId 以便在 getInitInfo 中使用
11
- // if (!window.wx) {
12
- // const script = document.createElement('script');
13
- // script.src = "//res.wx.qq.com/open/js/jweixin-1.6.0.js";
14
- // document.head.appendChild(script);
15
- // }
16
- function loadScript(src) {
17
- return new Promise((resolve, reject) => {
18
- const script = document.createElement('script');
19
- script.src = src;
20
- script.onload = () => resolve(script);
21
- script.onerror = () => reject(new Error('Failed to load script'));
22
- document.head.appendChild(script);
23
- });
24
- }
25
- loadScript('//res.wx.qq.com/open/js/jweixin-1.6.0.js')
26
- .then(script => {
27
- console.log('Script loaded');
28
- this.init(_options);
29
- })
30
- .catch(err => console.error(err));
15
+ constructor(_options) {
16
+ this.appId = _options.wechatId; // 保存 appId 以便在 getInitInfo 中使用
17
+ // if (!window.wx) {
18
+ // const script = document.createElement('script');
19
+ // script.src = "//res.wx.qq.com/open/js/jweixin-1.6.0.js";
20
+ // document.head.appendChild(script);
21
+ // }
22
+ function loadScript(src) {
23
+ return new Promise((resolve, reject) => {
24
+ const script = document.createElement('script');
25
+ script.src = src;
26
+ script.onload = () => resolve(script);
27
+ script.onerror = () => reject(new Error('Failed to load script'));
28
+ document.head.appendChild(script);
29
+ });
31
30
  }
31
+ loadScript('//res.wx.qq.com/open/js/jweixin-1.6.0.js')
32
+ .then((script) => {
33
+ console.log('Script loaded');
34
+ this.init(_options);
35
+ })
36
+ .catch((err) => console.error(err));
37
+ }
32
38
 
33
- async init(options) {
34
- const currentUrl = encodeURIComponent(window.location.href.split('#')[0]); // 确保URL编码且去除hash部分
35
- ajax.request({
36
- url: `${config.upmsServerContext}/manage/ibpWxMpBaseinfo/gtJsTicket?appId=${options.wechatId}&url=${currentUrl}`,
37
- method: 'get'
38
- }).then((resp) => {
39
- if (resp.data.code === 1) {
40
- const { data } = resp.data;
41
- window.wx.config({
42
- debug: false, // 开启调试模式
43
- appId: data.appId, // 必填,公众号的唯一标识
44
- timestamp: data.timestamp, // 必填,生成签名的时间戳
45
- nonceStr: data.noncestr, // 必填,生成签名的随机串
46
- signature: data.signature, // 必填,签名
47
- jsApiList: ['getLocation', 'scanQRCode', 'chooseImage', 'getLocalImgData', 'openLocation'] // 必填,需要使用的JS接口列表
48
- });
39
+ /**
40
+ * 初始化jssdk
41
+ * 2025-12-4 16:49:11 修改,增加审计日志回调函数auditLog,在不同阶段会调用该回调函数,调用参数如下
42
+ * {
43
+ * seg: 阶段,当前有 beforeConfig、configError、afterConfig、ready
44
+ * title: 对阶段的文字描述
45
+ * }
46
+ * 业务系统有需要对初始化jssdk进行审计的需求,在初始化jssdk的时候,在options中增加auditLog属性,并根据需要记录所需记录日志的阶段或者全部记录
47
+ * @param {*} options
48
+ * @returns
49
+ */
50
+ async init(options) {
51
+ const currentUrl = encodeURIComponent(window.location.href.split('#')[0]); // 确保URL编码且去除hash部分
52
+ if (options.auditLog && options.auditLog instanceof Function) {
53
+ options.auditLog({
54
+ seg: 'beforeConfig',
55
+ title: '开始小程序jssdk认证',
56
+ });
57
+ }
58
+ ajax
59
+ .request({
60
+ url: `${config.upmsServerContext}/manage/ibpWxMpBaseinfo/gtJsTicket?appId=${options.wechatId}&url=${currentUrl}`,
61
+ method: 'get',
62
+ })
63
+ .then((resp) => {
64
+ if (resp.data.code === 1) {
65
+ const { data } = resp.data;
66
+ window.wx.config({
67
+ debug: false, // 开启调试模式
68
+ appId: data.appId, // 必填,公众号的唯一标识
69
+ timestamp: data.timestamp, // 必填,生成签名的时间戳
70
+ nonceStr: data.noncestr, // 必填,生成签名的随机串
71
+ signature: data.signature, // 必填,签名
72
+ jsApiList: [
73
+ 'getLocation',
74
+ 'scanQRCode',
75
+ 'chooseImage',
76
+ 'getLocalImgData',
77
+ 'openLocation',
78
+ ], // 必填,需要使用的JS接口列表
79
+ });
49
80
 
50
- window.wx.error(function (res) {
51
- console.log("error:", res);
52
- console.error(res);
53
- });
81
+ window.wx.error(function (res) {
82
+ console.log('error:', res);
83
+ if (options.auditLog && options.auditLog instanceof Function) {
84
+ options.auditLog({
85
+ seg: 'configError',
86
+ title: '小程序jssdk认证异常wxerror',
87
+ });
88
+ }
89
+ });
54
90
 
55
- wx.ready(function() {
56
- console.log("ready...");
57
- // config信息验证后会执行ready方法
58
- // 可以在这里调用相关接口
59
- });
91
+ wx.ready(function () {
92
+ if (options.auditLog && options.auditLog instanceof Function) {
93
+ options.auditLog({
94
+ seg: 'afterConfig',
95
+ title: '完成小程序jssdk认证',
96
+ });
60
97
  }
61
- }).catch((err) => {
62
- console.error(err);
63
- });
64
- }
98
+ console.log('ready...');
99
+ // config信息验证后会执行ready方法
100
+ // 可以在这里调用相关接口
101
+ });
102
+ } else {
103
+ if (options.auditLog && options.auditLog instanceof Function) {
104
+ options.auditLog({
105
+ seg: 'configError',
106
+ title:
107
+ '小程序jssdk认证异常请求认证参返回结果异常' +
108
+ JSON.stringify(resp),
109
+ });
110
+ }
111
+ }
112
+ })
113
+ .catch((err) => {
114
+ if (options.auditLog && options.auditLog instanceof Function) {
115
+ options.auditLog({
116
+ seg: 'configError',
117
+ title: '小程序jssdk认证异常请求认证参数失败',
118
+ });
119
+ }
120
+ console.error(err);
121
+ });
122
+ }
65
123
 
66
- async getLocation(options) {
67
- return new Promise((resolve, reject) => {
68
- wx.ready(() => {
69
- // 检查 options.type,如果为空或者不含有 'wgs84' 或 'bd09',则设置为 'gcj02'
70
- let locationType = options.type;
71
- if (!options.type || (options.type !== 'wgs84' && options.type !== 'bd09')) {
72
- locationType = 'gcj02';
73
- }
124
+ /**
125
+ * 获取定位
126
+ * 2025-11-28 15:49:23 修改,增加审计日志回调函数auditLog,在不同阶段会调用该回调函数,调用参数如下
127
+ * {
128
+ * seg: 阶段,当前有 beforeCheck、checkError、afterCheck、beforeLocation、successLocation、errorLocation1、errorLocation2
129
+ * title: 对阶段的文字描述
130
+ * }
131
+ * 业务系统有需要对定位进行审计的需求,在调用定位的时候,在options中增加auditLog属性,并根据需要记录所需记录日志的阶段或者全部记录
132
+ * @param {*} options
133
+ * @returns
134
+ */
135
+ async getLocation(options) {
136
+ return new Promise((resolve, reject) => {
137
+ wx.ready(async () => {
138
+ // 解决在 URL 变化时,由于 wx.config 和 wx.ready 的异步特性导致的微信接口调用使用旧配置、签名失效或调用失败的问题
139
+ // 新增重试机制检查接口可用性
140
+ let retryInterval;
141
+ if (options.auditLog && options.auditLog instanceof Function) {
142
+ options.auditLog({
143
+ seg: 'beforeCheck',
144
+ title: '开始检测小程序jssdk授权状态',
145
+ });
146
+ }
147
+ try {
148
+ await new Promise((retryResolve, retryReject) => {
149
+ let retryCount = 0;
150
+ const maxRetries = 30; // 最大重试次数 (30*100ms=3秒超时)
151
+ retryInterval = setInterval(async () => {
152
+ if (retryCount++ >= maxRetries) {
153
+ clearInterval(retryInterval);
154
+ retryReject(new Error('JS-SDK接口初始化超时'));
155
+ return;
156
+ }
74
157
 
75
- const fetchLocation = (type) => {
76
- return new Promise((resolve, reject) => {
77
- wx.getLocation({
78
- ...options,
79
- type: type,
80
- success: location => {
81
- const unifiedLocation = {
82
- latitude: location.latitude || location.lat || null, // 统一纬度属性
83
- longitude: location.longitude || location.lng || null, // 统一经度属性
84
- accuracy: location.accuracy || null // 精确度,如果有的话
85
- };
158
+ // 检查getLocation接口是否可用
159
+ wx.checkJsApi({
160
+ jsApiList: ['getLocation'],
161
+ success: (res) => {
162
+ if (res.checkResult.getLocation === true) {
163
+ clearInterval(retryInterval);
164
+ retryResolve();
165
+ }
166
+ },
167
+ fail: () => {
168
+ /* 失败不计入重试,继续轮询 */
169
+ },
170
+ });
171
+ }, 100); // 每100ms检查一次
172
+ });
173
+ } catch (error) {
174
+ reject(new Error(`接口初始化失败: ${error.message}`));
175
+ if (options.auditLog && options.auditLog instanceof Function) {
176
+ options.auditLog({
177
+ seg: 'checkError',
178
+ title: '检测小程序jssdk授权状态异常并中止定位',
179
+ });
180
+ }
181
+ return;
182
+ }
86
183
 
87
- if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
88
- return reject(new Error('Invalid location data'));
89
- }
90
-
91
- const myGeo = new BMap.Geocoder({extensions_town: false});
92
- // 根据坐标得到地址描述
93
- myGeo.getLocation(new BMap.Point(unifiedLocation.longitude, unifiedLocation.latitude), function(result){
94
- if (result){
95
- unifiedLocation.city = result.addressComponents.city
96
- unifiedLocation.province = result.addressComponents.province
97
- unifiedLocation.address = result.address
98
- }
99
- });
184
+ if (options.auditLog && options.auditLog instanceof Function) {
185
+ options.auditLog({
186
+ seg: 'afterCheck',
187
+ title: '检测小程序jssdk授权状态结束',
188
+ });
189
+ }
100
190
 
101
- resolve(unifiedLocation);
102
- },
103
- fail: err => {
104
- console.error("getLocation failed:", err);
105
- reject(err);
106
- }
107
- });
108
- });
109
- };
191
+ // 检查 options.type,如果为空或者不含有 'wgs84' 或 'bd09',则设置为 'gcj02'
192
+ let locationType = options.type;
193
+ if (
194
+ !options.type ||
195
+ (options.type !== 'wgs84' && options.type !== 'bd09')
196
+ ) {
197
+ locationType = 'gcj02';
198
+ }
110
199
 
111
- if (locationType === 'bd09') {
112
- // 先获取 gcj02 坐标
113
- fetchLocation('gcj02').then(unifiedLocation => {
114
- // 将 gcj02 坐标转换为 bd09
115
- const [bd09Lng, bd09Lat] = coordtransform.gcj02tobd09(unifiedLocation.longitude, unifiedLocation.latitude);
116
- unifiedLocation.longitude = bd09Lng;
117
- unifiedLocation.latitude = bd09Lat;
200
+ const fetchLocation = (type) => {
201
+ return new Promise((resolve, reject) => {
202
+ if (options.auditLog && options.auditLog instanceof Function) {
203
+ options.auditLog({
204
+ seg: 'beforeLocation',
205
+ title: '小程序调用jssdk发起定位',
206
+ });
207
+ }
208
+ wx.getLocation({
209
+ ...options,
210
+ type: type,
211
+ success: (location) => {
212
+ const unifiedLocation = {
213
+ latitude: location.latitude || location.lat || null, // 统一纬度属性
214
+ longitude: location.longitude || location.lng || null, // 统一经度属性
215
+ accuracy: location.accuracy || null, // 精确度,如果有的话
216
+ };
118
217
 
119
- const myGeo = new BMap.Geocoder({extensions_town: false});
120
- // 根据坐标得到地址描述
121
- myGeo.getLocation(new BMap.Point(unifiedLocation.longitude, unifiedLocation.latitude), function(result){
122
- if (result){
123
- unifiedLocation.city = result.addressComponents.city
124
- unifiedLocation.province = result.addressComponents.province
125
- unifiedLocation.address = result.address
126
- }
127
- });
218
+ if (options.auditLog && options.auditLog instanceof Function) {
219
+ options.auditLog({
220
+ seg: 'successLocation',
221
+ title:
222
+ '小程序调用jssdk定位成功' +
223
+ JSON.stringify(unifiedLocation),
224
+ });
225
+ }
128
226
 
129
- resolve(unifiedLocation);
130
- }).catch(err => {
131
- reject(err);
227
+ if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
228
+ if (
229
+ options.auditLog &&
230
+ options.auditLog instanceof Function
231
+ ) {
232
+ options.auditLog({
233
+ seg: 'errorLocation1',
234
+ title: '小程序调用jssdk定位异常,未取到经纬度',
132
235
  });
133
- } else {
134
- fetchLocation(locationType).then(resolve).catch(reject);
236
+ }
237
+ return reject(new Error('Invalid location data'));
135
238
  }
136
- });
137
- });
138
- }
239
+ // options.needAddress 是否需要地址信息
240
+ // if(options.needAddress && !unifiedLocation.address) {
241
+ // // 根据坐标得到地址描述
242
+ // const res = getAddress(unifiedLocation.longitude, unifiedLocation.latitude)
243
+ // unifiedLocation.city = res.addressComponents.city
244
+ // unifiedLocation.province = res.addressComponents.province
245
+ // unifiedLocation.address = res.address
246
+ // }
139
247
 
140
- async openLocation(options) {
141
- return new Promise((resolve, reject) => {
142
- wx.ready(() => {
143
- wx.openLocation({
144
- latitude: options.latitude,
145
- longitude: options.longitude,
146
- name: options.name || '',
147
- address: options.address || '',
148
- scale: options.scale || 1,
149
- infoUrl: options.infoUrl || '',
150
- success: () => {
151
- console.log("openLocation success");
152
- resolve();
153
- },
154
- fail: err => {
155
- console.error("openLocation failed:", err);
156
- reject(err);
157
- }
158
- });
248
+ resolve(unifiedLocation);
249
+ },
250
+ fail: (err) => {
251
+ console.error('getLocation failed:', err);
252
+ if (options.auditLog && options.auditLog instanceof Function) {
253
+ options.auditLog({
254
+ seg: 'errorLocation2',
255
+ title: '小程序调用jssdk定位异常,' + JSON.stringify(err),
256
+ });
257
+ }
258
+ reject(err);
259
+ },
159
260
  });
160
- });
161
- }
261
+ });
262
+ };
162
263
 
163
- async scanCode(options) {
164
- return new Promise((resolve, reject) => {
165
- wx.ready(() => {
166
- wx.scanQRCode({
167
- ...options,
168
- needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果
169
- success: (res) => {
170
- console.log("scanQRCode success:", res);
171
- resolve( res); // 当needResult 为 1 时,扫码返回的结果
172
- },
173
- fail: (err) => {
174
- console.error("scanQRCode failed:", err);
175
- reject(err);
176
- }
177
- });
178
- });
264
+ // 先判断是否需要地理位置 如不需要 直接返回坐标
265
+ if (options.needAddress) {
266
+ fetchLocation(
267
+ 'gcj02'.then((unifiedLocation) => {
268
+ const result = getAddressByType(unifiedLocation, locationType);
269
+ if (!result) {
270
+ return reject(new Error('Invalid location data'));
271
+ }
272
+ resolve(unifiedLocation);
273
+ })
274
+ ).catch((err) => {
275
+ reject(err);
276
+ });
277
+ } else {
278
+ resolve(fetchLocation(locationType));
279
+ }
280
+
281
+ // // 先取gcj02 再根据type转成不同坐标系
282
+ // fetchLocation('gcj02').then(unifiedLocation => {
283
+ // // options.needAddress 是否需要地址信息
284
+ // if(options.needAddress && !unifiedLocation.address) {
285
+ // const result = getAddressByType(unifiedLocation, locationType)
286
+ // if(!result) {
287
+ // return reject(new Error('Invalid location data'));
288
+ // }
289
+ // resolve(unifiedLocation);
290
+ // }
291
+ // else {
292
+ // const result = getAxisByType(unifiedLocation, locationType)
293
+ // if(!result) {
294
+ // return reject(new Error('Invalid location data'));
295
+ // }
296
+ // resolve(unifiedLocation);
297
+ // }
298
+ // }).catch(err => {
299
+ // reject(err);
300
+ // });
301
+
302
+ // if (locationType === 'bd09') {
303
+ // // 先获取 gcj02 坐标
304
+ // fetchLocation('gcj02').then(unifiedLocation => {
305
+ // // 将 gcj02 坐标转换为 bd09
306
+ // const [bd09Lng, bd09Lat] = coordtransform.gcj02tobd09(unifiedLocation.longitude, unifiedLocation.latitude);
307
+ // unifiedLocation.longitude = bd09Lng;
308
+ // unifiedLocation.latitude = bd09Lat;
309
+ // if (!unifiedLocation.latitude || !unifiedLocation.longitude) {
310
+ // return reject(new Error('Invalid location data'));
311
+ // }
312
+ // // options.needAddress 是否需要地址信息
313
+ // if(options.needAddress && !unifiedLocation.address) {
314
+ // // 根据坐标得到地址描述
315
+ // const res = getAddress(unifiedLocation.longitude, unifiedLocation.latitude)
316
+ // unifiedLocation.city = res.addressComponents.city
317
+ // unifiedLocation.province = res.addressComponents.province
318
+ // unifiedLocation.address = res.address
319
+ // }
320
+
321
+ // resolve(unifiedLocation);
322
+ // }).catch(err => {
323
+ // reject(err);
324
+ // });
325
+ // }
326
+ });
327
+ });
328
+ }
329
+
330
+ async openLocation(options) {
331
+ return new Promise((resolve, reject) => {
332
+ wx.ready(() => {
333
+ wx.openLocation({
334
+ latitude: options.latitude,
335
+ longitude: options.longitude,
336
+ name: options.name || '',
337
+ address: options.address || '',
338
+ scale: options.scale || 1,
339
+ infoUrl: options.infoUrl || '',
340
+ success: () => {
341
+ console.log('openLocation success');
342
+ resolve();
343
+ },
344
+ fail: (err) => {
345
+ console.error('openLocation failed:', err);
346
+ reject(err);
347
+ },
179
348
  });
180
- }
349
+ });
350
+ });
351
+ }
181
352
 
182
- async takePhoto(options) {
183
- return new Promise((resolve, reject) => {
184
- wx.ready(() => {
185
- wx.chooseImage({
186
- ...options,
187
- // count: options.count || 1, // 可以根据传入的options设置选择图片的数量
188
- // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
189
- // sourceType: ['camera','album'], // 可以指定来源是相册还是相机,默认二者都有
190
- success: async (res) => {
191
- const localIds = res.localIds; // 返回选定照片的本地ID数组
192
- const results = [];
353
+ async scanCode(options) {
354
+ return new Promise((resolve, reject) => {
355
+ wx.ready(() => {
356
+ wx.scanQRCode({
357
+ ...options,
358
+ needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果
359
+ success: (res) => {
360
+ console.log('scanQRCode success:', res);
361
+ resolve(res); // 当needResult 为 1 时,扫码返回的结果
362
+ },
363
+ fail: (err) => {
364
+ console.error('scanQRCode failed:', err);
365
+ reject(err);
366
+ },
367
+ });
368
+ });
369
+ });
370
+ }
193
371
 
194
- for (const localId of localIds) {
195
- const result = { localId }; // 存储每张照片的处理结果
196
- if (!options.outputType) {
197
- // outputType为空,返回所有结果
198
- await new Promise((resolve, reject) => {
199
- wx.getLocalImgData({
200
- localId,
201
- success: (dataRes) => {
202
- result.imageData = dataRes.localData;
203
- resolve();
204
- },
205
- fail: (err) => {
206
- console.error("getLocalImgData failed:", err);
207
- reject(err);
208
- }
209
- });
210
- });
211
- } else {
212
- if (options.outputType.includes('info')) {
213
- result.imageInfo = localId;
214
- }
215
- if (options.outputType.includes('data')) {
216
- await new Promise((resolve, reject) => {
217
- wx.getLocalImgData({
218
- localId,
219
- success: (dataRes) => {
220
- result.imageData = dataRes.localData;
221
- resolve();
222
- },
223
- fail: (err) => {
224
- console.error("getLocalImgData failed:", err);
225
- reject(err);
226
- }
227
- });
228
- });
229
- }
230
- if (options.outputType.includes('oss')) {
231
- await new Promise((resolve, reject) => {
232
- wx.getLocalImgData({
233
- localId,
234
- success: (dataRes) => {
235
- const file = this.dataURLtoFile(dataRes.localData, 'image.png');
236
- this.uploadToOSS(file, options).then((ossResult) => {
237
- result.imageOss = ossResult;
238
- resolve();
239
- }).catch((err) => {
240
- console.error("uploadToOSS failed:", err);
241
- reject(err);
242
- });
243
- },
244
- fail: (err) => {
245
- console.error("getLocalImgData failed:", err);
246
- reject(err);
247
- }
248
- });
249
- });
250
- }
251
- }
252
- results.push(result); // 将处理结果添加到数组中
253
- }
372
+ async takePhoto(options) {
373
+ return new Promise((resolve, reject) => {
374
+ wx.ready(() => {
375
+ wx.chooseImage({
376
+ ...options,
377
+ // count: options.count || 1, // 可以根据传入的options设置选择图片的数量
378
+ // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
379
+ // sourceType: ['camera','album'], // 可以指定来源是相册还是相机,默认二者都有
380
+ success: async (res) => {
381
+ const localIds = res.localIds; // 返回选定照片的本地ID数组
382
+ const results = [];
254
383
 
255
- resolve(results); // 返回所有照片的处理结果
384
+ for (const localId of localIds) {
385
+ const result = { localId }; // 存储每张照片的处理结果
386
+ if (!options.outputType) {
387
+ // outputType为空,返回所有结果
388
+ await new Promise((resolve, reject) => {
389
+ wx.getLocalImgData({
390
+ localId,
391
+ success: (dataRes) => {
392
+ result.imageData = dataRes.localData;
393
+ resolve();
256
394
  },
257
395
  fail: (err) => {
258
- console.error("chooseImage failed:", err);
259
- reject(err);
260
- }
396
+ console.error('getLocalImgData failed:', err);
397
+ reject(err);
398
+ },
399
+ });
261
400
  });
262
- });
263
- });
264
- }
401
+ } else {
402
+ if (options.outputType.includes('info')) {
403
+ result.imageInfo = localId;
404
+ }
405
+ if (options.outputType.includes('data')) {
406
+ await new Promise((resolve, reject) => {
407
+ wx.getLocalImgData({
408
+ localId,
409
+ success: (dataRes) => {
410
+ result.imageData = dataRes.localData;
411
+ resolve();
412
+ },
413
+ fail: (err) => {
414
+ console.error('getLocalImgData failed:', err);
415
+ reject(err);
416
+ },
417
+ });
418
+ });
419
+ }
420
+ if (options.outputType.includes('oss')) {
421
+ await new Promise((resolve, reject) => {
422
+ wx.getLocalImgData({
423
+ localId,
424
+ success: (dataRes) => {
425
+ const file = this.dataURLtoFile(
426
+ dataRes.localData,
427
+ 'image.png'
428
+ );
429
+ this.uploadToOSS(file, options)
430
+ .then((ossResult) => {
431
+ result.imageOss = ossResult;
432
+ resolve();
433
+ })
434
+ .catch((err) => {
435
+ console.error('uploadToOSS failed:', err);
436
+ reject(err);
437
+ });
438
+ },
439
+ fail: (err) => {
440
+ console.error('getLocalImgData failed:', err);
441
+ reject(err);
442
+ },
443
+ });
444
+ });
445
+ }
446
+ }
447
+ results.push(result); // 将处理结果添加到数组中
448
+ }
265
449
 
450
+ resolve(results); // 返回所有照片的处理结果
451
+ },
452
+ fail: (err) => {
453
+ console.error('chooseImage failed:', err);
454
+ reject(err);
455
+ },
456
+ });
457
+ });
458
+ });
459
+ }
266
460
 
267
- dataURLtoFile(dataurl, filename) {
268
- let arr = dataurl.split(',');
269
- let mime;
270
- if (arr[0].indexOf(':') !== -1) {
271
- mime = arr[0].match(/:(.*?);/)[1];
272
- } else {
273
- mime = 'application/octet-stream'; // 默认MIME类型
274
- }
275
- let bstr = atob(arr[1] || arr[0]);
276
- let n = bstr.length;
277
- let u8arr = new Uint8Array(n);
278
- while (n--) {
279
- u8arr[n] = bstr.charCodeAt(n);
280
- }
281
- return new File([u8arr], filename, {type: mime});
461
+ dataURLtoFile(dataurl, filename) {
462
+ let arr = dataurl.split(',');
463
+ let mime;
464
+ if (arr[0].indexOf(':') !== -1) {
465
+ mime = arr[0].match(/:(.*?);/)[1];
466
+ } else {
467
+ mime = 'application/octet-stream'; // 默认MIME类型
468
+ }
469
+ let bstr = atob(arr[1] || arr[0]);
470
+ let n = bstr.length;
471
+ let u8arr = new Uint8Array(n);
472
+ while (n--) {
473
+ u8arr[n] = bstr.charCodeAt(n);
282
474
  }
475
+ return new File([u8arr], filename, { type: mime });
476
+ }
283
477
 
284
- uploadToOSS(file, options) {
285
- return new Promise((resolve, reject) => {
286
- let formData = new FormData();
287
- formData.append('file', file);
288
- ajax.post(options.ossServerContext + options.ossImgPutUrl, formData, { payload : true }).then(response => {
289
- if (response.data.code === 1) {
290
- const result = response.data.data;
291
- if (result.length > 0) {
292
- resolve(result[0]);
293
- } else {
294
- reject(new Error('No fileId returned'));
295
- }
296
- } else {
297
- reject(new Error('Upload failed'));
298
- }
299
- }).catch(error =>{
300
- reject(error);
301
- });
478
+ uploadToOSS(file, options) {
479
+ return new Promise((resolve, reject) => {
480
+ let formData = new FormData();
481
+ formData.append('file', file);
482
+ ajax
483
+ .post(options.ossServerContext + options.ossImgPutUrl, formData, {
484
+ payload: true,
485
+ })
486
+ .then((response) => {
487
+ if (response.data.code === 1) {
488
+ const result = response.data.data;
489
+ if (result.length > 0) {
490
+ resolve(result[0]);
491
+ } else {
492
+ reject(new Error('No fileId returned'));
493
+ }
494
+ } else {
495
+ reject(new Error('Upload failed'));
496
+ }
497
+ })
498
+ .catch((error) => {
499
+ reject(error);
302
500
  });
303
- }
501
+ });
502
+ }
304
503
 
305
- async getPlatform(options = {}) {
306
- // 获取初始化信息
307
- return {
308
- appId: this.appId,
309
- platform: 'Wechat'
310
- };
311
- }
504
+ async getPlatform(options = {}) {
505
+ // 获取初始化信息
506
+ return {
507
+ appId: this.appId,
508
+ platform: 'Wechat',
509
+ };
510
+ }
312
511
  }
313
512
 
314
513
  export default WechatAdapter;