-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMinaQrcodeCommand.js
106 lines (93 loc) · 2.75 KB
/
MinaQrcodeCommand.js
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
"use strict";
/**
* @description 小程序码生成服务
*/
const querystring = require("../utils/querystring");
const Command = require("../command");
class MinaQrcodeCommand extends Command {
async exec() {
const opt = this.args.type;
switch (opt) {
case "gen":
return this.genQrcode();
case "appid":
return this.queryAppId();
default:
throw new Error(`${opt} not support`);
}
}
async genQrcode() {
this.logger.info("gen mina qrcode...");
let appId = this.args.appId;
const appPath = this.args.appPath;
if (!appId) {
throw new Error(
"请输入正确的小程序的名称/AppID/账号原始ID,并确保小程序允许被搜索"
);
}
if (!appPath) {
throw new Error("请输入正确的小程序路径");
}
if (!/^wx.{16}$/.test(appId)) {
appId = await this.getAppidByAppName(appId);
}
const userInfo = this.admin.getUser();
const params = {
path: `/wxopen/wxaqrcode?action=getqrcode&f=json&appid=${appId}&path=${encodeURIComponent(
appPath
)}&token=${userInfo.token}&lang=zh_CN`,
token: userInfo.token,
random: String(Math.random())
};
let resp = await this.fetch(
`https://mp.weixin.qq.com/wxamp/cgi/route?${querystring.encode(params)}`
);
let content = await resp.json();
if (!content.base64img) {
throw new Error(`小程序码生成失败`);
}
return content.base64img;
}
async queryAppId() {
this.logger.info("query appid...");
let appName = this.args.appName;
if (!appName) {
throw new Error(
"请输入正确的小程序的名称/AppID/账号原始ID,并确保小程序允许被搜索"
);
}
const appId = await this.getAppidByAppName(appName);
return appId;
}
/**
* 根据名称/AppID/账号原始ID获取 appId
* @param {string} appName 名称/AppID/账号原始ID
*/
async getAppidByAppName(appName) {
this.logger.info("getAppidByAppName...", appName);
const userInfo = this.admin.getUser();
const params = {
path: `/wxopen/wxaqrcode?action=search`,
token: userInfo.token,
random: String(Math.random())
};
let resp = await this.fetch(
`https://mp.weixin.qq.com/wxamp/cgi/route?${querystring.encode(params)}`,
{
body: `appid=${encodeURIComponent(appName)}`,
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded"
}
}
);
let content = await resp.json();
if (!content.appid) {
throw new Error(
`请输入正确的小程序的名称/AppID/账号原始ID,并确保小程序允许被搜索`
);
}
return content.appid;
}
}
module.exports = MinaQrcodeCommand;