公众号H5中使用微信支付报错签名认证失败
环境描述
- 后台使用的是jsAPI支付,使用的是V2
- 前端是将H5跟公众号(服务号)相关联,必须使用服务号,订阅号没有权限
用户授权登录H5
const appId = 'XXXXXX'; // 使用自己公众号appid
const currentUrl = window.location.href;
const redirectUri = encodeURIComponent(currentUrl);
const authUrl =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
window.location.replace(authUrl);// 进行重定向获取code
const code = urlParams.get('code'); // 重定向回来检查URL中的code
const res = await getUserInfo(code) // 调用后端接口获取用户的信息,最重要的是公众号的openid
进行jsAPI授权
/**
* 加载微信JSSDK
*/
loadWxJSSDK() {
let script = document.createElement('script');
script.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
document.body.appendChild(script);
script.onload = () => {
this.initWxConfig();
};
},
/**
* 初始化微信JSSDK配置
*/
async initWxConfig() {
let response = await getWxConfig(appName.baseUrl) // 调用后台接口 传递当前页面路径最好不要带参数
let data = response;
wx.config({
debug: false,
appId: data.appId,
timestamp: data.timestamp,
nonceStr: data.nonceStr,
signature: data.signature,
jsApiList: ['chooseImage', 'previewImage', 'chooseWXPay'], //使用 chooseWXPay
});
wx.ready(() => {
console.log('配置成功');
});
wx.error((err) => {
console.error("微信SDK配置失败:", err);
});
}
支付调用
wx.chooseWXPay({ // prepayInfo是调用后端接口返回的支付参数
appId: prepayInfo.appId, // 公众号appid
timestamp: prepayInfo.timeStamp, // v2后台版本注意timestamp全部为小写
nonceStr: prepayInfo.nonceStr,
package: prepayInfo.package,
signType: prepayInfo.signType,
paySign: prepayInfo.paySign,
success:() => {}
})