在基于uniapp开发小程序时,如果直接使用pay-button组件会有以下问题:
1、getgoodsinfo事件无法正常触发
2、placeorder事件无法正常触发
3、applyrefund事件无法正常触发
在抖音官方的文档中(下图),虽然有解决的demo,但其是使用原生的小程序代码混入uniapp中,这种方案会对以后的维护人员来带心智负担
在uniapp的3.8.7.20230703版本中(下图),uniapp官方集成pay-button,也便修复了这个问题
但是对于一些老项目来说,更新uniapp的版本是一个风险很大的事情,于是我提供了一下解决思路:
究其原因是getgoodsinfo、placeorder、applyrefund三个事件需要返回promise来传递数据,下图以getgoodsinfo为例
但是在uniapp的源码实现中,针对事件的处理,但其事件名不为input时,会把事件return的数据拦截掉,如下图:
所以我们可以更改uni-mp-toutiao的代码为以下
但是毕竟修改的还是node_modules的东西,不会随git提交,所以可以使用npm的postinstall机制去修改uni-mp-toutiao的源码
1、在package.json的scripts新增postinstall
{
"scripts"{
"postinstall": "node ./scripts/postinstall.js"
}
}
2、在对应的路径下编写postinstall.js
const path = require('path');
const fs = require('fs');
// 修改uniapp源码
const packageRoot = path.resolve('node_modules/@dcloudio/uni-mp-toutiao/dist/index.js');
fs.readFile(packageRoot, 'utf8', (err, data) => {
console.log('处理-------------------开始');
if (err) {
console.log(err);
throw new Error(`修改uniapp源码错误,找不到${packageRoot}`);
}
data = data.replace(`eventType === 'input'`, `['input','getgoodsinfo', 'placeorder', 'applyrefund'].includes(eventType)`);
fs.writeFile(packageRoot, data, 'utf8', err => {
if (err) throw err;
console.log('处理结束');
});
});
以后每次npm install后既是修改后的代码,可以直接在uniapp使用pay-button
当然,在以后更新uniapp版本后,记得兼容postinstall.js的代码,毕竟目标代码的内容可能变化,有替换失败的风险,所以需要做好告警等提示信息