WeChat Pay Alipay Payment in App

Business scenario introduction

H5 mobile terminal supports WeChat payment [WeChat payment is divided into WeChat internal payment (JSAPI payment official API) and WeChat external payment (H5 payment official API)] && Alipay
[Mobile website payment to APP payment official API]

Order generation logic: the front-end requests the back-end to submit the order, and the back-end connects with WeChat or Alipay to generate the order (subsequent payments are all connected by this logic

1. vue WeChat payment

WeChat payment is divided into WeChat internal payment and WeChat external payment process as follows

  1. After selecting the payment method in the order component, first judge whether it is in WeChat on the payment page
//判断是在微信内
        is_weixn(){
    
    
          var ua = window.navigator.userAgent.toLowerCase();
          if (ua.match(/MicroMessenger/i) == 'micromessenger'){
    
    
            return true;
          } else {
    
    
            return false;
          }
        },
  1. Trigger the immediate payment method, request different back-end interfaces according to different internal and external WeChat, if it is a payment outside of WeChat, it is very simple~

  2. [Payment outside Wechat] Let’s look at the payment outside Wechat first. The official document is also very clear. The backend returns a url address. The front-end job is to get this url address and jump to it. Look at the 2-3 step code. :

 handelPay() {
    
    
          if
          (this.wechatpayType == 'wxpay'){
    
    
           // console.log("微信内支付")
            let data={
    
    
              amount:this.number,
            }
            this.$http.insideWeChatPay(data).then( res => {
    
    
              if(res.data.code === 200){
    
    
                this.weChatParameter=res.data.data
               // console.log(this.weChatParameter,"微信内支付需要参数")
                this.weixinPay()
              }else{
    
    
                Toast({
    
    
                  message: res.data.msg,
                  position: 'middle',
                  duration: 1000
                });
              }
            });
          } else if(this.wechatpayType == 'wxpay_php'){
    
    
           // console.log("微信外支付")
            let data={
    
    
              amount:this.number,
            }
            this.$http.outsideWeChatPay(data).then( res => {
    
    
              if(res.data.code === 200){
    
    
                let url=res.data.data
                window.location.replace(url)   //这里是后端返回的URL直接进行跳转即可完成微信外支付
              }else{
    
    
                Toast({
    
    
                  message: res.data.msg,
                  position: 'middle',
                  duration: 1000
                });
              }
            });
          }
        },
  1. On the page that calls up the payment, listen to the events returned from other pages, and implement some refreshing business logic. So far, the payment outside of WeChat has been completed.
document.addEventListener("返回的事件", function() {
    
    
    //需要的操作
});
  1. [Pay within WeChat] Pay within WeChat is a bit more complicated than outside WeChat, but it is not difficult. (The payment method interface has been requested in the 3-step code to get the parameters required for WeChat internal payment) According to the official API
    WeChat built-in js object WeixinJSBridge , For development, so far, the payment in the WeChat browser has been completed
 //解决微信内置对象报错
        weixinPay(data){
    
    
          var vm= this;
          if (typeof WeixinJSBridge == "undefined"){
    
    
            if( document.addEventListener ){
    
    
              document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false);
            }else if (document.attachEvent){
    
    
              document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data));
              document.attachEvent('onWeixinJSBridgeReady',vm.onBridgeReady(data));
            }
          }else{
    
    
            vm.onBridgeReady();
          }
        },
        //微信内置浏览器类,weChatParameter对象中的参数是3.步骤代码中从后端获取的数据
        onBridgeReady(){
    
    
          var  vm = this;
          var timestamp=Math.round(vm.weChatParameter.timeStamp).toString();
          WeixinJSBridge.invoke(
            'getBrandWCPayRequest',{
    
    
              debug:true,
              "appId":vm.weChatParameter.appId,     //公众号名称,由商户传入
              "timeStamp":timestamp, //时间戳,自1970年以来的秒数
              "nonceStr":vm.weChatParameter.nonceStr, //随机串
              "package":vm.weChatParameter.package,
              "signType":vm.weChatParameter.signType, //微信签名方式:
              "paySign":vm.weChatParameter.paySign, //微信签名
              jsApiList: [
                'chooseWXPay'
              ]
            },
            function(res){
    
    
              // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
              if(res.err_msg == "get_brand_wcpay_request:ok" ){
    
    
                Toast({
    
    
                  message: '支付成功',
                  position: 'middle',
                  duration: 3000
                });
                vm.number=null
                vm.$router.go(-1)
                //window.location.href = vm.BASE_URL + 'index.html#/depositResult'
              }else{
    
    
                Toast({
    
    
                  message: '支付失败',
                  position: 'middle',
                  duration: 3000
                });
              }
            }
          );
        },
  1. WeChat internal browser payment can also be encapsulated, and it can be directly called globally:
//微信浏览器支付
function wxpay(params,callback){
    
    
  if (typeof WeixinJSBridge == "undefined"){
    
    
     if( document.addEventListener ){
    
    
         document.addEventListener('WeixinJSBridgeReady', onBridgeReady(params,callback), false);
     }else if (document.attachEvent){
    
    
         document.attachEvent('WeixinJSBridgeReady', onBridgeReady(params,callback)); 
         document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(params,callback));
     }
  }else{
    
    
     onBridgeReady(params,callback);
  } 
}

function onBridgeReady(params,callback){
    
    
    var that = this
   WeixinJSBridge.invoke(
       'getBrandWCPayRequest', {
    
    
           "appId":params.appId,          
           "timeStamp":params.timeStamp,         
           "nonceStr":params.nonceStr, 
           "package":params.package,     
           "signType":params.signType, 
           "paySign":params.paySign 
       },
       function(res){
    
      
          callback(res)
       }
   ); 
  }
  1. Call WeChat payment in the component:
this.commonUtils.wxpay(res.data.data,function(payResult){
    
    
 	if(payResult.err_msg == "get_brand_wcpay_request:ok" ){
    
    
			//执行
     	} 
})

2. Vue Alipay payment process

In fact, Alipay payment also has H5 payment and Alipay browser payment, here only H5 payment is made.

  1. The H5 payment in Alipay is the same as that on the PC side. It is mainly the workload of the back-end. After the back-end completes the generation of the order, the form is returned to the front-end. The front-end only needs to be responsible for the page jump:
//立即支付按钮
      onSubmit() {
    
    
        if (this.payWay == 1) {
    
    
        	//支付宝支付
          	this.$router.push({
    
    path: '/aliPay', query: {
    
    orderId: this.orderId}});
        } else if (this.payWay == 2) {
    
    
         //微信支付,这里跳转到本文的微信支付模块的3.步骤handelPay方法
        }
      },
  1. After choosing the Alipay method, enter the Alipay bearer page:
<template>
  <div v-html="html"></div>
</template>
<script>
    export default {
    
    
      data(){
    
    
        return{
    
    
          html:''
        }
      },
      methods:{
    
    
        fetchVideoPay(){
    
    
          let param={
    
    
            orderId: this.$route.query.orderId
          };
          this.$api.orderpage.videoAliPay(param).then( res => {
    
    
            this.html = res.data;
            this.$nextTick(() => {
    
    
              document.forms[0].submit()   //渲染支付宝支付页面
            })
          })
        }
      },
      mounted(){
    
    
        this.fetchVideoPay()
      }
    }
</script>

Of course, if you don’t want to write the bearer page, there are other ways to transfer the payment. The specific logic is analyzed in detail, and the adaptation is based on different business types.

const div = document.createElement('div');
div.innerHTML = (res.data);  //res.data是返回的表单
document.body.appendChild(div);
document.forms.alipaysubmit.submit();
  1. Enter the Alipay payment page to pay

Guess you like

Origin blog.csdn.net/t5_5_5_5_5_7_7/article/details/110836122