Vue3-pc terminal generates WeChat QR code, scan code payment monitoring payment callback (WebSocket) function realization

Project scenario: The purchase order list in the background system needs to support the WeChat scan payment function, and the payment needs to be returned to the order list after successful payment.

1. Generate a two-dimensional code (QRCode) according to the back-end interface return

Call the interface to receive the data returned by the backend, npm install qrcode --save to install the plug-in, and process the returned data to generate a QR code.

1. The data returned by the backend interface is as follows:

2. The front-end code is as follows:

<template>
  <div class="pay-weixin">
    <img :src="qrCodeImgUrl">
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import QRCode from 'qrcode' // 引入生成二维码插件qrcode
import { weChatNativePay } from '@/api/index'

const qrCodeImgUrl = ref('')

onMounted(() => {
  // 微信支付二维码接口
  weChatNativePay({
    amount: '',
    description: '',
    module: '',
    outTradeNo: ''
  }).then(res => {
    // 使用toDataURL方法 返回的是promise对象 通过.then取值
    let img = QRCode.toDataURL(res.data)
    img.then(t => {
      qrCodeImgUrl.value = t
    })
  })
})

</script>

3. The effect picture is as follows:

The function of generating the QR code is completed here, but at this time, whether the user scans the code to pay, the status of success or failure cannot be obtained in real time, and the interaction to be completed after the scanning action cannot be performed. If the payment is successful, the list must be returned. At this time, a websocket connection needs to be established to receive feedback in real time.

2. Establish websocket monitoring payment callback

1. Establish a websocket connection

// 定义scoket
const socket = ref(null)

// onopen()方法
const open = () => {
  // 注意wss和ws 协议是http的使用ws,是https的使用wss
  socket.value = new WebSocket(`wss://xxx(后端提供接口)/${xxx(要传的参数)}`)
  socket.value.onopen=()=>{
    // 需要处理的逻辑代码
  }
}

2. Receive messages

// onmessage()方法
const message = () => {
  socket.value.onmessage=(e)=>{
    // 后端返回的标识 判断是否支付成功
    let res = JSON.parse(e.data)
    if (res.data=='Payment succeeded') {
      ElMessage.success('支付成功')
    }
  }
}

3. Long polling prevents disconnection

const open = () => {
  // 注意wss和ws 协议是http的使用ws,是https的使用wss
  socket.value = new WebSocket(`wss://xxx(后端提供接口)/${xxx(要传的参数)}`)
  socket.value.onopen=()=>{
    // 接收消息方法
    message()
    // 建立心跳机制防止无操作websocket断开连接  send()方法
    timers.value = setInterval(() => {
      const data = {message: 'heartbeat'} // 给后端传参 无要求可随意
      socket.value.send(JSON.stringify(data))
    },1000*30)
  }
}

4. Leave the page to close the connection

// onclose()方法
const close = ()=>{
  socket.value?.close()
  socket.value.onclose=()=>{
    console.log('关闭了');
  }
  socket.value = null
}

// 页面销毁
onBeforeUnmount(() => {
  close()
})

The complete code and comments are as follows:

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";

// 定义scoket
const socket = ref(null)

onMounted(() => {
  // 微信支付二维码接口
  weChatNativePay({
    amount: '',
    description: '',
    module: '',
    outTradeNo: ''
  }).then(res => {
    // 使用toDataURL方法 返回的是promise对象 通过.then取值
    let img = QRCode.toDataURL(res.data)
    img.then(t => {
      qrCodeImgUrl.value = t
    })
    // 二维码展示成功后开始建立websocket连接
    open()
  })
})


// 关闭websocket连接   onclose()方法
const close = ()=>{
  socket.value?.close()
  socket.value.onclose=()=>{
    console.log('关闭了');
  }
  socket.value = null
}

// 打开websocket   onopen()方法
const open = () => {
  // 注意wss和ws 协议是http的使用ws,是https的使用wss
  socket.value = new WebSocket(`wss://xxx(后端提供接口)/${xxx(要传的参数)}`)
  socket.value.onopen=()=>{
    // 接收消息方法
    message()
    // 建立心跳机制防止无操作websocket断开连接 send()方法
    timers.value = setInterval(() => {
      const data = {message: 'heartbeat'} // 给后端传参 无要求可随意
      socket.value.send(JSON.stringify(data))
    },1000*30)
  }
}

// 接收消息 处理支付成功逻辑   onmessage()方法
const message = () => {
  socket.value.onmessage=(e)=>{
    // 后端返回的标识 判断是否支付成功
    let res = JSON.parse(e.data)
    if (res.data=='Payment succeeded') {
      ElMessage.success('支付成功')
    }
  }
}

// 页面销毁时记得断开websocket连接
onBeforeUnmount(() => {
  close()
})

</script>

The above is the full sharing of the WeChat payment function on the PC side.

Guess you like

Origin blog.csdn.net/fat_shady/article/details/128410910