微信支付JSAPI
阿新 • • 發佈:2021-01-20
交代場景:確認補考報名資訊後點擊“確認支付”按鈕,進入支付繳費介面。支付程式碼就是在支付繳費介面。
- 發起請求(訪問微信介面登入)獲取使用者的code。這個code,微信介面會拼接到當前介面地址返回給你。
// 跳轉至授權地址,該地址只支援微信瀏覽器開啟
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx750b00e3b4bf2737&redirect_uri=" +
encodeURIComponent (window.location.href) +
"&response_type=code&scope=snsapi_base&state=9oJrpQhTVCAzkl2gXZPATSo9kn000002#wechat_redirect";
var url = window.location.href;
this.$http.post(url, {});
2.拿著獲取到code,訪問後端的介面,獲取openid。
// 獲取openid
this.$http.post(
"https://frpc.xiaohm.com/h5_Backstage/wxPay/auth?code=" +
this.code +
"&state=" +
this.$route.query.cj0716id
);
3.拿到openid後下訂單,調微信支付頁面
async pay() {
// 下訂單
const res = await Api.weixinPayInterface({
cj0716id: this.$route.query.cj0716id,
kcmc: this.itemList.kcmc,
bmfysl: this.itemList.bmfysl
});
let that = this;
// 如果下訂單成功,調微信支付中間頁
if (res.code == 1) {
if (this.code !== null && this.code !== "") {
function onBridgeReady() {
WeixinJSBridge.invoke("getBrandWCPayRequest", res.data, function(
res
) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
// 根據state判斷是否支付成功
this.state = 1;
Toast({
message: "支付成功",
duration: 1500,
forbidClick: true,
onClose: function() {
// 跳轉回list介面
that.$router.replace("/student/registRetest");
}
});
}
});
}
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 {
onBridgeReady();
}
}
}
}
4.支付成功後會重新整理回到支付介面
created() {
// 判斷是否支付成功,在資料庫裡更改狀態
if (this.state === 1) {
this.getWeiXinPayStatus();
}
// 一進入介面就獲取code和oppenid
this.getOpenid();
},