官方文檔:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6,即可看到h5調起支付需要的參數。
獲取后台調用微信生成的支付簽名,
$scope.onBridgeReady = function () { $http.post("/wechat/createSign", $scope.payOrder).then(function (data) { var order = data.data.data; WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId": order.appid, //公眾號名稱,由商戶傳入 "timeStamp": order.timeStamp, //時間戳,自1970年以來的秒數 "nonceStr": order.nonce_str, //隨機串 "package": "prepay_id=" + order.prepay_id, "signType": "MD5", //微信簽名方式 "paySign": order.sign //微信簽名 }, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { //alert("微信支付成功!"); $http.post("/wechat/toPaySuccessUrl").then(function (data) { window.location.href = data.data.data + "?orderNo=" + order.out_trade_no; }) // window.location.href = "http://qiansheng.imwork.net/paydone.html?orderNo=" + order.out_trade_no; } else if (res.err_msg == "get_brand_wcpay_request:cancel") { //alert("用戶取消支付!"); } else { alert("支付失敗!"); } }); }) }
簽名算法:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
參考:微信公眾號支付(二)H5調起支付 https://blog.csdn.net/zsm15623544116/article/details/79392263
通用demo: https://gitee.com/1600875665/weixinPay
然后需要實現iframe內調起支付
在iframe內發起
top.postMessage(data,'*');
外部做業務處理,可以做支付調起等
window.addEventListener("message", function (e) { wxPay(JSON.parse(e.data)) })
微信支付方法封裝
function wxPay(wxParams) { // 微信支付API function onBridgeReady() { WeixinJSBridge.invoke( 'getBrandWCPayRequest', wxParams, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { // 使用以上方式判斷前端返回,微信團隊鄭重提示: //res.err_msg將在用戶支付成功后返回ok,但並不保證它絕對可靠。 console.log(res) alert("成功") } else if (res.err_msg == "get_brand_wcpay_request:cancel") { console.log(res) alert("失敗") // window.history.go(-1) } }); } if (typeof WeixinJSBridge == "undefined") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } } else { onBridgeReady(); } }
注:想在iframe調起window.WeixinJSBridge是不行的,會返回undefined
1.設置監聽 window.addEventListener('message', function (msg) { console.log(msg.data); }) 2.發送 message window.postMessage(”message“, '*'); 實現多頁面通訊; 使用postMessage 需要精確的目標origin,不要用 *。
iframe: https://www.w3school.com.cn/tags/tag_iframe.asp
跨域iframe實例: https://www.jb51.net/article/123740.htm https://www.cnblogs.com/qidian10/p/3316714.html
調用parent頁面的方法: https://blog.csdn.net/shuaidao_wupengyou/article/details/73497528?locationNum=10&fps=1
window.addeventlistener使用方法:https://www.cnblogs.com/ConfidentLiu/p/7815624.html