微信支付 WeixinJSBridge is not defined 报错


  1. 我没有用到微信JS-SDK或者接口都正确返回预支付id都正确, 为什么会报这个错呢?
    答: 微信内置浏览器会有WeixinJSBridge ,但是需要一定的加载时间。
  2. 我使用了微信JS-SDK, 但是为什么会出错呢?
    答: 微信webview注入钩子有时序问题:在WeixinJSBridge 还未注入之前,就已经成功注入其它依赖于WeixinJSBridge 的其它XX模块。在XX模块中调用WeixinJSBridge 就会失败。

如何解决

如果你开发一款移动应用,必不可少要考虑分享到微信的功能;如果你开发网页,那么用户之间的分享更多的也是通过微信。那么这个问题到底有多严重,如何解决也变得至关重要。

  • 如果网页中未使用微信JS-SDK, 用户在微信中打开网站可能会触发这个错误,目前看来只有忽略。因为是微信JS-SDK自身的问题,我们也无法控制。
  • 关于微信支付
• 方法一: 改为监听ready事件之后再进行下一步操作
if (typeof window.WeixinJSBridge == "undefined"){• $(document).on('WeixinJSBridgeReady',function(){ })
• //你的代码

• }
• 方法二: function callpay() {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', GotoWxMpPay, false);
}
else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', GotoWxMpPay);
document.attachEvent('onWeixinJSBridgeReady', GotoWxMpPay);
}
}
else {
GotoWxMpPay();
}
}
callpay();• function GotoWxMpPay() {
var data = {};
data.method = "GetMpPayInfo";


ajaxProcess("?", data, function callSuccess(oRet) {
var result = oRet;
if (result != null) {


jsApiCall(result.appId, result.timeStamp, result.nonceStr, result.package, result.paySign, result.OrderNo);
}
}, function callError(e) {
alert(e);
});
return null;
}


function jsApiCall(appid, timeStamp, nonceStr, packages, paySign, orderNo) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": appid, //公众号名称,由商户传入
"timeStamp": timeStamp, //时间戳,自1970 年以来的秒数
"nonceStr": nonceStr, //随机串
"package": packages,
"signType": "MD5", //微信签名方式:
"paySign": paySign //微信签名,
}, function (res) {
if (res.err_msg === "get_brand_wcpay_request:ok") {
// 此处可以使用此方式判断前端返回,微信团队郑重提示:res.err_msg 将在用户支付成
//功后返回ok,但并不保证它绝对可靠。
document.location.href = 你指定的url;
} else {


alert(res.err_msg);
//alert(JSON.stringify(res));
}
}
);
}
  • 方法三: 直接使用JS-SDK文档中的支付代码,不要使用公众号支付文档里面的代码。参考:​​微信支付​

后记: 关于这个问题的帖子从2014年开始就有了,然而到现在依然存在,可见一直没有修复好!

参考链接

[1]微信支付: ​​https://mp.weixin.qq.com/wiki...​​​ [2] Uncaught ReferenceError: WeixinJSBridge is not defined: ​​http://www.henkuai.com/forum....​​ [3] Uncaught ReferenceError: WeixinJSBridge is not defined问题: ​​http://www.henkuai.com/thread...​​ [4] 微信支付问题:Uncaught ReferenceError: WeixinJSBridge is not defined: ​​http://www.java-bbs.com/threa...​​ [5] 传说中的WeixinJSBridge和微信rest接口: ​​http://bbs.blueidea.com/threa...​​ [6] 监听wxbridge加载后再唤起微信支付: ​​https://github.com/whq731/mob...​​