前端微信支付代码(公众号支付)

一.场景 (完成代码见附录)

        其他商户跳转到我们支付页面,传入参数openId,fromTradeType,订单号,流水号,借由我们页面进行微信支付。具体在小程序后台如何配置,见微信官方文档。

二.包引入部分

import _ from "lodash";

引入lodash主要使用防抖功能

 三.控制微信支付按钮显示隐藏的代码

this.showWxPay = this.isWeChat() && tmp.subOpenId;

isWeChat() {
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true; //是微信内部
      } else {
        return false;
      }
    },

满足1.是在微信内核进入。2.传入了openId

四.点击微信支付后的流程代码

 wxPay: _.debounce(function () {
      let url = "";        //接口获取后端timeStamp,nonceStr等微信支付拉起的参数
      let data = this.wxParams;

      if (!this.passJudge(data)) {        //对进入的数据进行判读,必须每一个数据都是存在的
        //对参数做一次校验
        return;
      }

      this.$axios
        .post({
          url,
          data,
          headers: { "Content-Type": "application/json" },
        })
        .then((res) => {
          this.$emit(
            "getPayResult",
          );
          let judge =
            res.hasOwnProperty("data") &&
            res.data.hasOwnProperty("ERRCODE") &&
            res.data.ERRCODE == "000000" &&
            res.status == "SUCCESS";
          if (judge) {
            let _data = res.data;
            this.weChatParameter = {        //记录拉起支付的参数
              //微信搭桥需要的数据
              appid: _data.appId || "",
              timeStamp: _data.timeStamp || "",
              nonceStr: _data.nonceStr || "",
              package: _data.package || "",
              signType: _data.signType || "",
              paySign: _data.paySign || "",
            };
            this.weixinPay(); //微信内置对象判断
          } else {
            this.$message({
              message: res.retMsg || "提交订单失败",
              type: "warning",
            });
          }
        })
        .catch((error) => {
          this.$message({
            message: "提交订单失败",
            type: "warning",
          });
        });
    }, 240),

其中,passJudge函数为:

 passJudge(data) {
      if (!data) {
        this.$message.error("缺少请求参数");
        return false;
      }
      if (!data.reOrderNo) {
        this.$message.error("缺失参数:reOrderNo");
        return false;
      }
      if (!data.tranNo) {
        this.$message.error("缺失参数:tranNo");
        return false;
      }
      if (!data.subOpenId) {
        this.$message.error("缺失参数:subOpenId");
        return false;
      }
      if (!data.fromTradeType) {
        this.$message.error("缺失参数:fromTradeType");
        return false;
      }
      return true;
    },

五.进行微信搭桥,进行环境处理 

let that = this;
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady(),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", that.onBridgeReady());
        }
      } else {
        that.onBridgeReady();
      }

 六.环境准备好后,拉起支付

onBridgeReady() {
      let that = this;
      let timestamp = Math.round(this.weChatParameter.timeStamp).toString();

      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: that.weChatParameter.appid, //公众号名称,由商户传入
          timeStamp: timestamp, //时间戳,自1970年以来的秒数
          nonceStr: that.weChatParameter.nonceStr, //随机串
          package: that.weChatParameter.package,
          signType: that.weChatParameter.signType, //微信签名方式:
          paySign: that.weChatParameter.paySign, //微信签名
          // jsApiList: ["chooseWXPay"],
        },
        function (res) {
          that.$emit(
            "getPayResult",
            `拉起支付返回结果为:${JSON.stringify(res)}`
          );
          // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            //支付成功
            that.$emit("toSuccess");
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            //取消支付
          } else {
            //支付失败
            that.$emit("toFail");
          }
        }
      );
    },

七.附录:完整代码

<template>
  <div class="check-box" @click="wxPay">
    <img src="../../../assets/images/normal/pay/phone.png" class="check-img" />
    <div class="check-word">微信支付</div>
  </div>
</template>
  
<script>
import _ from "lodash";
import Bus from "@/utils/bus.js";
export default {
  data() {
    return {
      weChatParameter: "",
    };
  },
  props: {
    wxParams: {
      type: Object,
      default: {},
    },
  },
  created() {},
  mounted() {
    Bus.$on("getDetail", (amount, settlementNo, reconciliationTime) => {
      this.payAmount = amount;
      this.amount = amount;
      this.settlementNo = settlementNo;
      this.reconciliationTime = reconciliationTime;
    });
  },
  components: {},
  computed: {},
  watch: {},
  methods: {
    wxPay: _.debounce(function () {
      let url = "";
      let data = this.wxParams;
      this.$emit("changeWay", 3);

      if (!this.passJudge(data)) {
        //对参数做一次校验
        return;
      }

      this.$axios
        .post({
          url,
          data,
          headers: { "Content-Type": "application/json" },
        })
        .then((res) => {
          this.$emit(
            "getPayResult",
            "进入/cashier/PublicPay,数据为:" + JSON.stringify(res)
          );
          let judge =
            res.hasOwnProperty("data") &&
            res.data.hasOwnProperty("ERRCODE") &&
            res.data.ERRCODE == "000000" &&
            res.status == "SUCCESS";
          if (judge) {
            let _data = res.data;
            this.weChatParameter = {
              //微信搭桥需要的数据
              appid: _data.appId || "",
              timeStamp: _data.timeStamp || "",
              nonceStr: _data.nonceStr || "",
              package: _data.package || "",
              signType: _data.signType || "",
              paySign: _data.paySign || "",
            };
            this.weixinPay(); //微信内置对象判断
          } else {
            this.$message({
              message: res.retMsg || "提交订单失败",
              type: "warning",
            });
          }
        })
        .catch((error) => {
          this.$message({
            message: "提交订单失败",
            type: "warning",
          });
        });
    }, 240),

    weixinPay() {
      let that = this;
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady(),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", that.onBridgeReady());
        }
      } else {
        that.onBridgeReady();
      }
    },

    //微信内置浏览器类
    onBridgeReady() {
      let that = this;
      let timestamp = Math.round(this.weChatParameter.timeStamp).toString();
      this.$emit(
        "getPayResult",
        "进入onBridgeReady,数据为:" + JSON.stringify(that.weChatParameter)
      );
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: that.weChatParameter.appid, //公众号名称,由商户传入
          timeStamp: timestamp, //时间戳,自1970年以来的秒数
          nonceStr: that.weChatParameter.nonceStr, //随机串
          package: that.weChatParameter.package,
          signType: that.weChatParameter.signType, //微信签名方式:
          paySign: that.weChatParameter.paySign, //微信签名
          // jsApiList: ["chooseWXPay"],
        },
        function (res) {
          that.$emit(
            "getPayResult",
            `拉起支付返回结果为:${JSON.stringify(res)}`
          );
          // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            //支付成功
            that.$emit("toSuccess");
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            //取消支付
          } else {
            //支付失败
            that.$emit("toFail");
          }
        }
      );
    },

    passJudge(data) {
      if (!data) {
        this.$message.error("缺少请求参数");
        return false;
      }
      if (!data.reOrderNo) {
        this.$message.error("缺失参数:reOrderNo");
        return false;
      }
      if (!data.tranNo) {
        this.$message.error("缺失参数:tranNo");
        return false;
      }
      if (!data.subOpenId) {
        this.$message.error("缺失参数:subOpenId");
        return false;
      }
      if (!data.fromTradeType) {
        this.$message.error("缺失参数:fromTradeType");
        return false;
      }
      return true;
    },
  },
};
</script>
  
<style lang="scss" scoped>
.check-box {
  padding: 0px 10px;
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgb(220, 220, 220);
  margin-left: 10px;
  cursor: pointer;

  .check-img {
    width: 18px;
    height: 18px;
  }

  .check-word {
    margin-left: 5px;
    font-size: 14px;
  }
}
</style>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
前端微信公众号开发流程一般包括以下步骤: 1. 注册微信公众号:首先,你需要在微信公众平台上注册一个公众号。根据你的需求,可以选择订阅号、服务号或企业号。 2. 设置服务器:在公众平台上,你需要设置服务器用于接收和处理微信服务器发送的消息。你需要提供一个能够响应微信服务器验证的URL,并配置合法域名。 3. 开发公众号后台:你可以选择使用开发框架(如Node.js、Java等)来开发公众号后台,用于处理微信服务器发送的消息和事件。根据需求,你可能需要实现菜单管理、自动回复、素材管理等功能。 4. 开发前端页面:根据你的设计需求和业务逻辑,开发前端页面。你可以使用HTML、CSS和JavaScript等技术来构建用户界面,并与后台交互获取数据。 5. 微信JS-SDK的使用:如果你需要在公众号中使用微信的JS-SDK功能(如分享、支付等),你需要在前端页面中引入相应的JS文件,并按照文档说明进行相应的配置和调用。 6. 调试和测试:在开发过程中,及时进行调试和测试,确保公众号的正常运行和符合预期的功能。 7. 提交审核和发布:当你开发完成并测试通过后,可以在微信公众平台上提交审核。审核通过后,你可以正式发布你的公众号。 请注意,以上仅为一般的开发流程,具体的步骤和实现方式可能因个人需求和技术栈而异。在开发过程中,你可以参考微信公众平台的开发文档和示例代码,以便更好地理解和实现相应功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一路追求匠人精神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值