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