开发起来是一步一个坎啊 文档不清晰甚至有问题,哈哈哈
npm install weixin-js-sdk
import wx from "weixin-js-sdk"; //微信sdk依赖 记得下包 否则wx.config not a function
mounted(){
this.loadWeChatScript().then(() => {
this.getwxconfig();
}).catch(err => {
console.error('微信 JSSDK 脚本加载失败', err);
});
}
methods:{
loadWeChatScript() {
return new Promise((resolve, reject) => {
if (typeof wx !== 'undefined') {
resolve();
return;
}
const script = document.createElement('script');
script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
script.onload = () => {
if (typeof wx !== 'undefined') {
resolve();
} else {
reject(new Error('微信 JSSDK 未正确加载'));
}
};
script.onerror = () => {
reject(new Error('微信 JSSDK 脚本加载错误'));
};
document.head.appendChild(script);
});
},
//发起ajax请求向后端发起请求
getwxconfig() {
const params = {
url: window.location.href.split('#')[0]
}
// 注意 微信文档说的是 需要转码,但是转码会出问题的 导致校验签名不正确
//我是用的是 分享好友,朋友圈. 需要将本页面的url给后端 后端拿这个去算,才能正确,
//不然会失败,建议先使用签名校验工具校验
console.log(params, '这就是我找遍天下角落找到的 params!');
this.$api.wxconfig(params).then(res => {
const data = res.data
this.configs = data.message
this.initWeChatJSSDK();
})
},
}
以下为wx.config 核心代码
methods:{
initWeChatJSSDK() {
const that = this
wx.config({
debug: false, // 开启调试模式
appId: that.configs.appId,
timestamp: that.configs.timestamp,
nonceStr: that.configs.nonceStr,
signature: that.configs.signature,
jsApiList: [
'updateTimelineShareData', 'updateAppMessageShareData', 'chooseWXPay',
]
});
wx.ready(() => {
const parent_id = uni.getStorageSync('userinfo').openid;
console.log(parent_id, ';parent_id');
const c_id = uni.getStorageSync('c_id');
console.log(window.location, ';000');
console.log(that.idinfo, ';that.idinfo');
const link =
`${window.location.origin}${window.location.pathname}${window.location.hash.split('?')[0]}?parent_id=${parent_id}&c_id=${c_id}`;
console.log(link, 'link');
// 自定义分享到朋友圈内容
wx.updateTimelineShareData({
title: that.idinfo.title,
link,
imgUrl: that.idinfo.picurl,
success: function() {
// alert('分享成功');
}
});
// 自定义分享给朋友内容
wx.updateAppMessageShareData({
title: that.idinfo.title,
link,
imgUrl: that.idinfo.picurl,
success: function() {
// alert('分享成功');
}
});
});
wx.error(function(res) {
alert('微信配置错误:', res.errMsg);
console.error('微信配置错误:', res);
});
},
}
坑还是很多的 比如不合法的config 基本就是签名算的不对,需要好好排查
以下为支付
goyupay() {
const params = {
c_id: uni.getStorageSync('c_id'),
openid: uni.getStorageSync('userinfo').openid,
parent_id: uni.getStorageSync('parent_id')
}
this.$api.goyupayapi(params).then(res => {
const data = JSON.parse(res.data.data)
console.log(data, '返回data');
wx.chooseWXPay({
timestamp: data.timeStamp,
nonceStr: data.nonceStr,
package: data.package,
signType: data.signType,
paySign: data.paySign,
success: function(res) {
console.log('支付成功', res)
// 支付成功后的逻辑
},
fail: function(err) {
console.log('支付失败', err)
// 支付失败后的逻辑
}
});
})
},
需要注意,如果是单纯链接进入h5的分享 只有丑陋的链接,是没有标题以及图片等的,最好是从公众号进入 这样分享出来的 是OK的 ,调试时debug开开 然后alert数据排查 .sbtx