返回 AiToEarn
wxGzh.service.ts
根目录 / project / aitoearn-electron / server / src / lib / platAuth / wxGzh.service.ts
1 /*
2 * @Author: nevin
3 * @Date: 2024-06-17 16:12:56
4 * @LastEditTime: 2025-04-14 17:10:59
5 * @LastEditors: nevin
6 * @Description: 艺咖三方平台认证服务 PlatAuth platAuth
7 */
8 import { Injectable } from '@nestjs/common';
9 import axios from 'axios';
10 import { ConfigService } from '@nestjs/config';
11 import { BaseUrl } from './comment';
12 import * as crypto from 'crypto';
13
14 @Injectable()
15 export class PlatAuthWxGzhService {
16 appId = '';
17 secret = '';
18 vi = 'yika2025'; // 盐
19 constructor(private readonly configService: ConfigService) {
20 this.appId = this.configService.get('WX_GZH.WX_GZH_ID');
21 this.secret = this.configService.get('WX_GZH.WX_GZH_SECRET');
22 }
23
24 // 生成加密
25 private async generateEncryptionKey(): Promise<string> {
26 // 1.appId+secret进行sha1加密
27 const encryptionKey = crypto
28 .createHash('sha256')
29 .update(this.appId + this.secret)
30 .digest();
31
32 const vi = Buffer.from(this.vi, 'utf8')
33 .toString()
34 .padEnd(16, '0')
35 .slice(0, 16); // 强制16字节
36
37 // 加入当前时间戳,进行AES加密
38 // 3. 时间戳 AES 加密
39 const timestamp = Date.now().toString(); // 显式转为字符串
40 const cipher = crypto.createCipheriv('aes-256-cbc', encryptionKey, vi);
41 let encrypted = cipher.update(timestamp, 'utf8', 'hex');
42 encrypted += cipher.final('hex'); // 合并 update 和 final 的结果
43 return encrypted;
44 }
45
46 /**
47 * 获取微信登录二维码的票据
48 * @returns
49 */
50 async getWxLoginQrcode(): Promise<{
51 key: string;
52 ticket: string;
53 }> {
54 const url = `${BaseUrl}/wxGzh/qrcode/get/${this.appId}`;
55 const result = await axios.get<{
56 code: number;
57 message: string;
58 data: {
59 key: string;
60 ticket: string;
61 };
62 }>(url);
63
64 return result.data.data;
65 }
66
67 /**
68 * 创建公众号菜单
69 */
70 async createWxGzhMenu(body: any): Promise<{
71 errcode: number;
72 errmsg: string;
73 }> {
74 if (typeof body !== 'object' || body === null || Array.isArray(body))
75 return { errcode: 400, errmsg: '菜单必须为非空对象' };
76
77 const sign = await this.generateEncryptionKey();
78 console.log('----- sign: ', sign);
79
80 const url = `${BaseUrl}/wxGzh/menu/create/${this.appId}`;
81 const result = await axios.post<{
82 code: number;
83 message: string;
84 data: {
85 errcode: number;
86 errmsg: string;
87 };
88 }>(url, { data: body, authKey: sign });
89
90 return result.data.data;
91 }
92
93 /**
94 * 获取菜单
95 */
96 async getMenu(): Promise<{
97 errcode: number;
98 errmsg: string;
99 data: any;
100 }> {
101 const url = `${BaseUrl}/wxGzh/menu/get/${this.appId}`;
102 const result = await axios.get<{
103 code: number;
104 message: string;
105 data: any;
106 }>(url);
107
108 return result.data.data;
109 }
110 }
111
111 lines TYPESCRIPT