由于项目测试人员越来越多,经常需要开发提供二维码测试,所以需要一种动态生成小程序预览二维码的工具。
开发前需要一个无人使用的开发者账号,用于生成二维码。(使用测试的微信号就行)
具体流程为
可以直接使用mpvue taro 等框架直接打包的代码,或者小程序原生未打开增强编译的代码。如果有一下ES新特性的代码,需要编译一下才能打包使用。
第一步是打包 这里使用的是开发工具的源码
./pack.js
"use strict"; const a = require("glob"), b = require("fs"), c = require("path"), d = require("crypto"); module.exports = async (e, f, g = {}) => { const h = [ Buffer.alloc(1), Buffer.alloc(4), Buffer.alloc(4), Buffer.alloc(4), Buffer.alloc(1), ]; (h[0][0] = 190), h[1].writeInt32BE(0, 0), (h[4][0] = 237); let i, j, k, l = 0; const m = [], n = []; return new Promise((o, p) => { const q = Object.assign({ nodir: !0 }, g), r = {}; let s = 0; a(`${e}/**`, q, (a, q) => { if (!a) { q.forEach((a) => { const f = b.readFileSync(a), h = c.relative(e, a); if (g.needMd5) { const a = d.createHash("md5"); a.update(f); const b = a.digest("hex"); if (((r[h] = b), g.ignoreFileMd5 && g.ignoreFileMd5[h] === b)) return; } const i = Buffer.from(`/${h.replace(/\\/g, "/")}`); l++, m.push(i), n.push(f), /\.js\.map$/.test(a) || ((s += f.length), (s += i.length), (s += 12)); }); let a = 18 + 12 * l + Buffer.concat(m).length; k = m.map((b, c) => { const d = Buffer.alloc(4); d.writeInt32BE(b.length, 0); const e = Buffer.alloc(4), f = n[c].length, g = a; e.writeInt32BE(g, 0), (a += f); const h = Buffer.alloc(4); return h.writeInt32BE(f, 0), Buffer.concat([d, b, e, h]); }); const p = Buffer.alloc(4); p.writeInt32BE(l, 0), k.unshift(p), (i = Buffer.concat(k)), (j = Buffer.concat(n)), h[2].writeInt32BE(i.length, 0), h[3].writeInt32BE(j.length, 0); const t = Buffer.concat(h), u = Buffer.concat([t, i, j]); (s += 18), o({ destPath: f, data: u, totalSize: s, fileMd5Info: r }); } else p(a); }); }); };
第二步是上传打包数据
const zlib = require("zlib"); const request = require("request"); const readFile = require("./pack"); exports.testsource = (src, config) =>{ return new Promise((resolve, reject) => { const params = [ "_r=" + Math.random(), "newticket=" + config.newticket, "appid=" + config.appid, "path="+config.path, "debug_launch_info=" + encodeURIComponent(config.launchInfo), "platform=0&ext_appid=&os=win&clientversion=1032006090&gzip=1&is_game_engine_app=1&devplugin=0", ]; readFile(src).then(({ data }) => { const url = "https://servicewechat.com/wxa-dev/testsource?" + params.join("&"); request( { url, body: zlib.gzipSync(data), method: "post" }, (error, response, body) => { if (error) { reject(error); return; } if(response.statusCode != 200){ reject({statusCode:response.statusCode}) return; } resolve(JSON.parse(body)); } ); }); }); };
其中src为源代码的根目录的路径。
config为配置项,config.newticket为开发工具的令牌,具体获取和更新查看《微信小程序开发者工具获取和更新newticket》
config.appid:当前小程序的appid
config.path:小程序入口的路径
config.launchInfo:入口数据的配置 是一个json字符串 {"scene":1001,"path":"pages/index/index","query":{}} 分别对应的是场景值 入口路径和参数
最后通过上传,微信服务器会返回一个base64字符串的图片,解析查看即为预览的二维码。
请发表评论