H5在微信公眾號里調(diào)用微信支付總結(jié)(前端)

1.JSSDK(chooseWXPay)方法調(diào)用

該方式出現(xiàn)的版本比較晚,需要jssdk注入,不需要參數(shù)appId(個(gè)人理解為了跟其他js API接口統(tǒng)一)
JSSDK使用步驟 請看官網(wǎng):https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
接入前準(zhǔn)備【支付授權(quán)目錄說明】:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_3
因調(diào)用支付的頁面較多,支付授權(quán)目錄 配置時(shí),個(gè)人推薦配置 頂級目錄,可根據(jù)自己需求而定。
confirmPayOrder(orderInfo, pageType) {
        if (isWx()) {
          Toast.loading({
            message: "加載中...",
            forbidClick: true,
          });
          // 將訂單id傳遞給后臺
          orderPayOrder({ id: orderInfo.id })
            .then((resOrder) => {
              getWxConfig().then(() => {
                wx.ready(() => {
                  // chooseWXPay參數(shù)說明文檔 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
                  wx.chooseWXPay({
                    appId: resOrder.result.appId, //公眾號appId,chooseWXPay調(diào)用此處可省略,提醒后端注意大小寫
                    timestamp: resOrder.result.timestamp, // 支付簽名時(shí)間戳,注意微信jssdk中的所有使用timestamp字段均為小,部分系統(tǒng)取到的值為毫秒級,需要轉(zhuǎn)換成秒(10位數(shù)字)
                    nonceStr: resOrder.result.nonceStr, // 支付簽名隨機(jī)串,不長于 32 位
                    package: resOrder.result.payPackage, // 統(tǒng)一支付接口返回的prepay_id參數(shù)值,提交格式如:prepay_id=\*\*\*)
                    signType: resOrder.result.signType, // 簽名方式:MD5,提醒后端用到加密的地方都用MD5
                    paySign: resOrder.result.paySign, // 支付簽名:后端注意生成規(guī)則 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
                    success: (res) => {
                      // 支付成功回調(diào):微信團(tuán)隊(duì)鄭重提示:不保證絕對可靠,切記!
                      // 據(jù)說部分ios手機(jī),成功的回調(diào)不執(zhí)行,所以為了保證回調(diào)執(zhí)行,在complete里也做了回調(diào)執(zhí)行
                      if (res.errMsg === "chooseWXPay:ok") {
                        Toast.success("支付成功");
                        this.refreshData(orderInfo.id, pageType);
                      }
                    },
                    complete: (res) => {
                      // 調(diào)用完成時(shí)的回調(diào):成功或失敗都會(huì)執(zhí)行
                      if (res.errMsg === "chooseWXPay:ok") {
                        Toast.success("支付成功");
                        this.refreshData(orderInfo.id, pageType);
                        console.log("complete支付成功:", res);
                      } /*else if (res.errMsg === "chooseWXPay:cancel") {
                        Toast.fail("取消支付");
                        this.refreshData(orderInfo.id, pageType);
                        console.log("complete取消支付:",res);
                      } else if (res.errMsg === "chooseWXPay:fail") {
                        Toast.fail("支付失敗");
                        this.refreshData(orderInfo.id, pageType);
                        console.log("complete支付失敗:",res);
                      }*/
                    },
                    fail: (res) => {
                      Toast.fail("支付失敗");
                      console.log("支付失敗:", res);
                      this.refreshData(orderInfo.id, pageType);
                    },
                    cancel: (res) => {
                      Toast.fail("取消支付");
                      console.log("取消支付:", res);
                      this.refreshData(orderInfo.id, pageType);
                    },
                  });
                });
              });
            })
            .catch((err) => {
              // 后臺報(bào)錯(cuò) 彈框提示
              this.showTipDialog = true;
              this.errTip = err.errorDesc;
            });
        } else {
          Dialog.alert({
            message: "請?jiān)谖⑿怒h(huán)境下打開,否則無法付款",
            className: "dialog-alert",
          }).then(() => {
            // close
          });
        }
    },

// 獲取微信配置信息
export function getWxConfig() {
  return new Promise((resolve, reject) => {
    const url = encodeURIComponent(location.href.split("#")[0]); //獲取當(dāng)前頁面路由
    // 調(diào)用接口獲取微信簽名,入?yún)rl一般是當(dāng)前頁面的url(不包括#及后面部分)
    getWxSignature({ url })
      .then((res) => {
        if (Object.keys(res.result)) {
          const { appId, nonceStr, signature, timestamp } = res.result;
          wx.config({
            debug: false, // 開啟調(diào)試模式
            appId: appId, // appId 必填,公眾號的唯一標(biāo)識
            timestamp: "" + timestamp, // 必填,生成簽名的時(shí)間戳
            nonceStr: nonceStr, // 必填,生成簽名的隨機(jī)串
            signature: signature, // 必填,簽名
            jsApiList: ["getLocation", "chooseWXPay", "scanQRCode"], // 必填,需要使用的JS接口列表
          });
        }
        resolve(res);
      })
      .catch((e) => {
        reject(e);
        console.log("微信配置信息調(diào)用失敗:" + e);
      });
  });
}

2.JSAPI調(diào)用支付(僅針對微信支付這個(gè)功能)

JSAPI出現(xiàn)的版本更早,無需引用jssdk,無需wx.config方法注入,需要參數(shù)appId
confirmPayOrder(orderInfo, pageType) {
  if (isWx()) {   
      Toast.loading({
            message: "加載中...",
            forbidClick: true,
          });
          orderPayOrder({ id: orderInfo.id }).then((resOrder) => {
            let _this = this;
            var onBridgeReady = () => {
              // eslint-disable-next-line
              WeixinJSBridge.invoke(
                "getBrandWCPayRequest",
                {
                  appId: resOrder.result.appId, //公眾號ID,此處必傳
                  timeStamp: resOrder.result.timestamp, //時(shí)間戳,timeStamp S需要大寫
                  nonceStr: resOrder.result.nonceStr, //隨機(jī)串
                  package: resOrder.result.payPackage,
                  signType: resOrder.result.signType, //微信簽名方式MD5
                  paySign: resOrder.result.paySign, //微信簽名
                },
                function (res) {
                  if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // 使用以上方式判斷前端返回,微信團(tuán)隊(duì)鄭重提示:res.err_msg將在用戶支付成功后返回ok,但并不保證它絕對可靠。
                    _this.refreshData(orderInfo.id, pageType);
                  }
                  if (res.err_msg == "get_brand_wcpay_request:fail") {
                    Toast.fail("支付失敗");
                    _this.refreshData(orderInfo.id, pageType);
                  }
                  if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    Toast.fail("支付取消");
                    _this.refreshData(orderInfo.id, pageType);
                  }
                }
              );
            };
            //調(diào)用微信支付接口
            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();
            }
          });
        } else {
          Dialog.alert({
            message: "請?jiān)谖⑿怒h(huán)境下打開,否則無法付款",
            className: "dialog-alert",
          }).then(() => {
            // close
          });
        }
  }

3.在調(diào)試過程報(bào)錯(cuò)解決

調(diào)用支付JSAPI,很多錯(cuò)誤都會(huì)報(bào)缺少參數(shù):total_fee

1、請檢查預(yù)支付會(huì)話標(biāo)識prepay_id是否已失效,如果已經(jīng)操作的訂單,可能在微信有記錄,最好換一條數(shù)據(jù)測試。
2、請求的appid與下單接口的appid是否一致,appid 是H5所在公眾號的appId,此處需要注意,后端調(diào)用微信返回的是appid,前臺需要配置的參數(shù)是appId,注意大小寫。
3、以下幾點(diǎn)都注意核對以下,金額是“分”等等.


image.png
支付簽名失敗

image.png

讓后端確認(rèn)簽名生成規(guī)則,參考官網(wǎng):https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
簽名校驗(yàn)驗(yàn)證:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=20_1

當(dāng)前頁面URL未注冊

原因就是:授權(quán)目錄配置的不對,請仔細(xì)核對,配置好后,一般5分鐘內(nèi)生效。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容