PC端实现微信支付功能(Vue2.0)
簡介
? ? ? ? 在實現微信支付之前,我們要知道,在提交訂單是我們需要攜帶一個query參數去支付頁面
為什么要攜帶參數?
? ? ? ? 1.為了要獲取支付信息,支付信息包含:
? ? ? ? ? ? ? ? 1.1 需要支付多少錢,并渲染到支付界面,提示用戶
? ? ? ? ? ? ? ? 1.2 服務器返回的url,用于生成二維碼????????????????????????
? ? ? ? 2.為了下次請求查詢支付狀態(需要定時發請求檢查支付狀態)
獲取支付信息:
// 獲取需要花多少錢async getPayInfo() {let result = await this.$API.reqPayInfo(this.$route.query.orderId);if (result.code == 200) {this.totalFee = result.data.totalFee;this.payInfo = result.data;} else {alert("失敗");}},?由上圖我們可以看到,數據已經拿到了,價格為18486,???codeUrl就是可以生成二維碼的url
?這里我們使用ElementUI組件庫中的Message Box彈窗
點擊支付按鈕,進行彈窗,這個過程我就不再贅述了。
彈窗之后我們需要生成一個微信二維碼,我們需要利用qrcode插件
qrcode - npm這是他的指導手冊
import QRCode from "qrcode";
當我們點擊支付按鈕就應該生成二維碼
// 生成二維碼
let url = await QRCode.toDataURL(this.payInfo.codeUrl);
?此時二維碼已經生成了,但沒有實現支付功能,我們需要借助MessageBox中的beforeClose
——MessageBox 關閉前的回調,會暫停實例的關閉
具體參數可看文檔Element - The world's most popular Vue UI framework
在此之前,我們需要在data中定義兩個變量,code和timer
data() {
? ? ?return {
? ? ? ?totalFee: "",? //價格為18486
? ? ? ?payInfo: {},? //支付信息
? ? ? ?timer: null,? //為定時器準備的,這個不理解也可繼續往下看
? ? ? ?code: ""? ?//我們需要留存請求支付的狀態碼,205的話說明支付成功
};
},
常規來說200是支付成功,205是支付中,我這樣做的目的也是為了能不用付款(但發請求)就可實現功能。
// 點擊打開支付彈窗async open() {// 生成二維碼let url = await QRCode.toDataURL(this.payInfo.codeUrl);this.$alert(`<img src=${url} />`, "請使用微信掃碼支付", {showClose: false,showCancelButton: true,showConfirmButton: true,confirmButtonText: "支付成功",cancelButtonText: "支付遇到問題",center: true,dangerouslyUseHTMLString: true,beforeClose:(action, instance, done)=>{if (action == "confirm") {console.log("你點擊的是支付成功");// 判斷是否真的支付了if (this.code == 205) {console.log("支付成功啦");clearInterval(this.timer);this.timer = null;}done();} else {clearInterval(this.timer);this.timer = null;done();}}});// 查詢支付狀態if (!this.timer) {this.timer = setInterval(async () => {let result = await this.$API.reqPayStatus(this.$route.query.orderId);console.log(result);if (result.code == 205) {clearInterval(this.timer);this.timer = null;this.code = 205;// 關閉彈出框this.$msgbox.close()}}, 3000);}}發現了嗎我這里為什么用箭頭函數
如果不使用箭頭函數或者改變this指向的方法,在beforeClose中的this其實不是組件實例
instance 為 MessageBox 實例,下圖證實想法是正確的
?于是我在上面的代碼中使用的箭頭函數,為什么箭頭函數的this就可以?
this的指向問題_那只貓喝咖啡的博客-CSDN博客
上面鏈接有介紹,放心點開,篇幅非常短。
解決了this問題,基本上已經完成了支付功能,剩下的就是在判斷支付成功的里面加上路由跳轉至支付成功的界面。
總結
以上是生活随笔為你收集整理的PC端实现微信支付功能(Vue2.0)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有道linux安装路径,Ubuntu 1
- 下一篇: html5倒计时秒杀怎么做,vue 设