wangrong
2026-07-25 a97d3b4a19c0fc7586bd02f5b51f609904d5cf15
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
import { Provide, Inject } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import axios from 'axios';
import { BaseSysParamService } from '../../base/service/sys/param';
 
@Provide()
export class Ys7Service extends BaseService {
    @Inject()
    baseSysParamService: BaseSysParamService;
 
    /**
     * 获取萤石云 AccessToken
     * 内部自动读系统参数,不走缓存建议上层包一层 Redis
     */
    async getAccessToken(): Promise<{
        accessToken: string;
        expireTime: number;
    }> {
        // 从 Cool-Admin 系统参数表读取
        const appKey = await this.baseSysParamService.dataByKey('ys7.appKey');
        const appSecret = await this.baseSysParamService.dataByKey('ys7.appSecret');
 
        if (!appKey || !appSecret) {
            throw new Error('萤石云 appKey/appSecret 未配置,请在系统参数中维护 ys7.appKey / ys7.appSecret');
        }
 
        try {
            const res = await axios.post(
                'https://open.ys7.com/api/lapp/token/get',
                new URLSearchParams({
                    appKey,
                    appSecret,
                }),
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    timeout: 8000,
                }
            );
 
            const { code, msg, data } = res.data;
 
            if (String(code) !== '200') {
                throw new Error(`萤石云获取 Token 失败:${msg}(code: ${code})`);
            }
 
            return {
                accessToken: data.accessToken,
                expireTime: data.expireTime,
            };
        } catch (err) {
            throw err;
        }
    }
}