h5接入微信支付
-
支付一般是有兩個按鈕 一個是進入充值頁面的入口(此時的入口應該是后台提供的用於回調那微信中的openid用於在微信中支付)進入充值界面之后會有一個選擇金額的頁面選擇好金額以后會有一個確定按鈕 微信中內置的方法就是用戶點擊完確定按鈕之后才進行調用
定時器用於顯示提示語(支付成功/失敗...)
setTimeDate() {
window.clearInterval(this.timers);
this.isPopup = true;
this.timers = setInterval(() => {
this.isPopup = false;
// 用於清楚定時器
this.isPopup == false ? window.clearInterval(this.timers) : null;
},this.sumTime ? 2000 : 60000);
}, -
金幣接口 (當前金額)
goldPort() { this.$get("v1.gold/getMyGold").then(res => { if (res.code == 2000) { this.allGold = res.data.all_gold; } }); },//確定按鈕
confirm() {
//執行后端接口 用於請求微信內置方法需要傳入的參數
this.getWxPay();
}, -
請求接口
getWxPay() {
//傳入 openid token 和 金幣金額
this.$post("v1.gold/wePay", {
openid: this.obj.open,
token: sessionStorage.getItem("token"),
shopname: "金幣充值",
money: this.goldSelect
})
.then(res => {
//成功之后調用微信方法 此時返回的內容 需要放在微信提供的方法里
if (res.status) {
this.resData = JSON.parse(res.data);
this.orders = res.order;
this.isWx();
}
}) //.catch用於捕獲錯誤
.catch(err => {
console.log("請求充值接口Error Info:" + JSON.stringify(err));
});
},
- 判斷是否是微信瀏覽器(微信提供的方法)
isWx() {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener(
"WeixinJSBridgeReady",
onBridgeReady,
false
);
} else if (document.attachEvent) {
document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
}
} else {
this.onBridgeReady().catch(err => {
console.log("Error Info:" + JSON.stringify(err));
});
}
},
- 微信支付
onBridgeReady() {
let that = this;
//that.resData 應該是this.resData 但是這是微信內置的一個方法所以this在函數體內不生效
//此時的that.resData是一個對象 內容是由后端返回提供的
WeixinJSBridge.invoke("getBrandWCPayRequest", that.resData, function(
res
) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
//點擊成功之后
that.sumTime = false;
that.setTimeDate(); //調用提示語
window.clearInterval(that.timer)
that.timer = setInterval(() => {
- 調用查詢訂單接口(后台提供)如果微信瀏覽器支付成功就走這一步
- 這個方法使用來判斷是否有支付到自己服務器(如果是微信支付錯誤微信會自動返現)
that.queryOrder();
}, 2000);
} else {
that.isPopup = true;
that.title = "支付關閉";
that.sumTime = true;
that.setTimeDate();
}
})
},
- 查詢訂單是否成功
queryOrder() {
this.$get("v1.gold/getOrderInfo?order=" + this.orders)
.then(res => {
// 進行判斷code值
if (res.code == 2000) {
//支付成功
// 從新賦值並調用
this.title = "支付成功";
window.clearInterval(this.timer)
this.sumTime = true;
this.setTimeDate();
} else if (res.code == 2003) {
//未支付
this.title = "未支付";
this.sumTime = true;
window.clearInterval(this.timer)
this.setTimeDate();
} else if (res.code == 2004) {
//支付關閉
this.title = "支付關閉";
this.sumTime = true;
window.clearInterval(this.timer)
this.setTimeDate();
} else if (res.code == 2005) {
//支付撤銷
this.title = "支付撤銷";
this.sumTime = true;
window.clearInterval(this.timer)
this.setTimeDate();
} else if (res.code == 2007) {
//支付失敗
this.title = "支付失敗";
window.clearInterval(this.timer)
this.sumTime = true;
this.setTimeDate();
} else {
this.sumTime = true;
this.setTimeDate();
window.clearInterval(this.timer)
}
this.goldPort();
})
}
},
created() {
this.goldPort(); //當前金額
}
