微信公眾號h5使用微信支付及支付寶支付的步驟(前端)
方案:
一、微信支付
考慮到授權的問題,微信支付使用JS-SDK進行支付
二、支付寶支付
問題:h5微信授權后是無法再微信瀏覽器直接打開支付寶的付款鏈接
解決:使用一個中間頁 指向通過跳轉到瀏覽器進行支付
實施:
一、微信支付:
第一步微信授權,在main.js中添加路由攔截,獲取code,具體代碼如下 ↓
// main.js
router.beforeEach(async (to: RouteLocationNormalized,from: RouteLocationNormalized,next) => {
// 判斷有沒有openId 即授權了直接放行
if (store.state.openId) {
next()
} else {
// 沒有授權去授權獲取code 再放行
const code = await getCode()
await queryInfo(code)
next()
}
})
// 獲取code
function getCode() {
const code = getUrlCode()?.code
if (!code) {
// 沒有code 請求后端接口進行鏈接跳轉獲取code(鏈接值微信的授權鏈接,成功授權后會跳回 回調地址,在回調地址上 會攜帶code參數(shù))
return getWxOauthUrl({
redirectUrl: window.location.href
}).then(async ({data}) => {
if (data.statusCode === 0) {
window.location.replace(data.msg)
}
})
} else {
return code
}
}
// 通過code 獲取用戶信息
function queryInfo(code: string) {
return getUserInfo([code]).then(({data}) => {
const result = data.data || {}
store.commit('getUserInfo', result)
store.commit('getUserOpenId', result.openId)
})
}
// 獲取url 參數(shù)的通用方法
function getUrlCode() {
// 截取url中的code方法
const url = location.search;
const theRequest = new Object();
if (url.indexOf("?") !== -1) {
const str = url.substr(1);
const strs = str.split("&");
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
}授權成功后即可以進行支付環(huán)節(jié)
核心代碼
// 首先在index.html 中引入微信JS-SDK
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
// 然后在支付邏輯中添加以下代碼即可~
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();
}
function onBridgeReady(result) {
WeixinJSBridge.invoke('getBrandWCPayRequest', {
"appId": , //公眾號ID,由商戶傳入
"timeStamp": , //時間戳,自1970年以來的秒數(shù)
"nonceStr": , //隨機串
"package": ,
"signType": , //微信簽名方式:
"paySign":
},
function (res) {
if ((res.errMsg || res.err_msg) === "get_brand_wcpay_request:ok") {
// 使用以上方式判斷前端返回,微信團隊鄭重提示:
//res.err_msg將在用戶支付成功后返回ok,但并不保證它絕對可靠。
}
});
}這樣 微信支付就已經(jīng)結束了
二、支付寶支付:
因為是在微信授權后的h5頁面,所以不能直接在微信頁面直接進行支付
所以第一步就是在點擊支付的時候,進行跳轉到中間頁,
先定義一個中間頁: pay.html
注意:要把這個頁面放到publish目錄下
// 跳轉中間頁,把請求支付的參數(shù)一并帶過去
window.open(`${location.origin}/pay.htm?params=${encodeURIComponent(JSON.stringify(params))}`)pay.html核心內容如下
let getQueryString = function (url, name) {
let reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
if (reg.test(url)) return RegExp.$2.replace(/\+/g, " ");
};
// 獲取接口返回的表單 進行支付
function handlePayForm(data) {
const div = document.createElement("div");
div.setAttribute("id", "payContainer");
div.innerHTML = data
document.body.appendChild(div);
const payContainer = document.querySelector("#payContainer");
const submit = payContainer.querySelector(
'form[name="punchout_form"] input[type="submit"]'
);
submit.click();
setTimeout(function () {
div.remove();
}, 500);
};
if (location.hash.indexOf('error') !== -1) {
alert('參數(shù)錯誤,請檢查');
} else {
// 判斷當前的瀏覽器環(huán)境是不是微信瀏覽器
let ua = navigator.userAgent.toLowerCase();
let tip = document.querySelector(".weixin-tip");
let tipImg = document.querySelector(".J-weixin-tip-img");
const query = JSON.parse(decodeURIComponent(getQueryString(location.href, 'params')))
if (ua.indexOf('micromessenger') !== -1) {
// 如果是微信里的頁面,做個指引(請通過瀏覽器進行支付)
// 這個頁面自己定義即可
} else {
// 好的,這是外部瀏覽器,請求接口獲取支付的from表單
axios({
url: '',
data: query,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(({data}) => {
if (data.statusCode === 0) {
// 后端返回的form表單進行支付
if (data.data && data.data.returnCode === "SUCCESS") {
// data.data.result ==> 是一個支付的from表單
handlePayForm(data.data.result)
}
}
})
}
}這樣即可 跳轉到微信外部瀏覽器進行正常的支付功能
總結
到此這篇關于微信公眾號h5使用微信支付及支付寶支付的文章就介紹到這了,更多相關公眾號h5使用微信及支付寶支付內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript防抖與節(jié)流的實現(xiàn)與注意事項
防抖和節(jié)流嚴格算起來應該屬于性能優(yōu)化的知識,但實際上遇到的頻率相當高,處理不當或者放任不管就容易引起瀏覽器卡死,下面這篇文章主要給大家介紹了關于JavaScript防抖與節(jié)流的實現(xiàn)與注意事項,需要的朋友可以參考下2022-03-03
js判斷復選框是否選中及選中個數(shù)的實現(xiàn)代碼
下面小編就為大家?guī)硪黄猨s判斷復選框是否選中及選中個數(shù)的實現(xiàn)代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05
web開發(fā)js字符串拼接占位符及conlose對象Api詳解
本篇文章主要為大家介紹了web開發(fā)中字符串的拼接,占位符的使用以及conlose對象Api的使用,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09
JavaScript中使用Async實現(xiàn)異步控制
async提供了很多函數(shù)用于異步流程控制,下面是async核心的幾個函數(shù),大家通過本文學習下,對使用async 實現(xiàn)異步控制相關知識,感興趣的朋友一起看看吧2017-08-08
JavaScript異步編程:異步數(shù)據(jù)收集的具體方法
我們先嘗試在不借助任何工具函數(shù)的情況下來解決這個問題。筆者能想到的最簡單的方法是:因前一個readFile的回調運行下一個readFile,同時跟蹤記錄迄今已觸發(fā)的回調次數(shù),并最終顯示輸出。下面是筆者的實現(xiàn)結果。2013-08-08

