需求
多个微信小程序共用同一套代码,通过开发工具上传代码较繁琐,希望通过后台点击上传。
调研
通过查阅资料,发现微信提供了两种方法
- miniprogram-ci 上传代码https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html
接入较简单,功能也单一,只是提供了代码上传、预览等简单功能 - 通过第三方平台(较为复杂,后续更新)
https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Third_party_platform_appid.html
提供大量接口,可提供公众号和小程序创建、开发等服务,接入较复杂
针对需求和实现难度,暂时考虑miniprogram-ci方法
miniprogram-ci接入
前期准备
- 获取appid和对应的小程序代码上传密钥(开发设置-小程序代码上传中获取)
- 由于是本地环境调试,先关闭IP白名单
- 我使用的是uni-app,将build后的微信小程序文件和小程序上传密钥文件放到vue项目中
一次错误的尝试
- 在vue项目中安装
npm install miniprogram-ci --save
- 按照文档中的写了方法,对应appid、projectPath、privateKeyPath等都配置好了
const ci = require('miniprogram-ci')
;(async () => {
const project = new ci.Project({
appid: 'wxsomeappid',
type: 'miniProgram',
projectPath: 'the/project/path',
privateKeyPath: 'the/path/to/privatekey',
ignores: ['node_modules/**/*'],
})
const uploadResult = await ci.upload({
project,
version: '1.1.1',
desc: 'hello',
setting: {
es6: true,
},
onProgressUpdate: console.log,
})
console.log(uploadResult)
})()
-
调用上面的方法,报错fs.statSync is not a function。
查了一波资料,说是需要node环境。翻官网,看到了这个
image.png - 换个方式
将之前的代码放到mini.js中,在vscode终端中,cd进入mini.js所在目录,执行
node mini.js
去小程序平台查看,上传成功。但这种方法明显不符合需求,不能在后台系统点击操作
使用nodesjs服务执行
- 使用koa搭建nodejs项目
- 引入miniprogram-ci
- 小程序和上传密钥资源拷贝到项目中
- 创建mini.js
let uploadMini = function(appid) {
return new Promise(async (resolve, reject) => {
const ci = require('miniprogram-ci')
const path = require('path')
const project = new ci.Project({
appid: appid,
type: 'miniProgram',
projectPath: path.resolve(__dirname, './source/mp-weixin'),
privateKeyPath: path.resolve(__dirname, `./source/private.${appid}.key`),
ignores: ['node_modules/**/*'],
})
ci.upload({
project,
version: '1.1.1',
desc: 'hello',
setting: {
es6: true,
},
onProgressUpdate: console.log,
}).then(res => {
resolve({ code: 0, msg: 'success' })
}).catch(err => {
reject(err)
})
})
}
module.exports = { uploadMini }
- 创建一个接口
const { uploadMini } = require('./mini.js')
router.get('/uploadMini', async ( ctx )=>{
let appid = ctx.query.appid
let response = {}
if (appid) {
let res = await uploadMini(appid).catch(err => {
if (err.code == 20003) {
err.msg = 'appid与上传密钥不匹配'
}
ctx.body = err
})
if (res) {
ctx.body = res
}
} else {
response = {
code: 1,
msg: '发布失败'
}
ctx.body = response
}
})
- Vue项目中调用该接口(传入appid)