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