业务背景
由于公司业务需求,需对接微信支付和支付宝支付,于是对前端接入第三方支付进行了调研并以此记录,本次讨论微信支付与支付宝支付两种支付方式。
微信支付
- JSAPI支付:仅限在微信内使用,可调用微信的API,直接唤起微信的支付组件。
JSAPI唤起微信支付相关代码
function onBridgeReady () {
WeixinJSBridge.invoke(
"getBrandWCPayRequest",
{
"appId": appId, //公众号名称,由商户传入
"timeStamp": timeStamp, //时间戳,自1970年以来的秒数
"nonceStr": nonceStr, //随机串
"package": package,
"signType": signType, //微信签名方式:
"paySign": paySign //微信签名
},
function (data) {
if (
data.err_msg === "get_brand_wcpay_request:ok"
) {
// 使用以上方式判断前端返回,微信团队郑重提示:
//res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
window.open(res.data.mweburl);
} else {
that.$toast.error("支付失败");
window.open(res.data.mweburl);
}
}
);
}
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();
}
- H5支付:用户在浏览器端打开H5页面,唤起微信支付。
前端发起接口请求,后端响应并返回前端微信支付的链接,同时支付结果的回调地址,会以redirect_url 的形式拼在该链接后面,前端打开这个链接,就可以唤起微信支付。完成支付后,会回到支付结果回调地址。
redirect_url地址格式如下:
https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx1320983386585bfa61437b349e3580000&package=1509339968&redirect_url=回调地址
如果单纯的使用window.location.href 可能存在不同浏览器的兼容性问题,所以改用模拟a标签点击跳转
function createAHref(url) {
const link = document.createElement('a');
link.href = url;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
支付宝支付
- 在微信环境中,没有办法直接唤起支付宝,需要中间页引导用户在外部浏览器中进行支付
- 同时支付分期与支付不分期唤起支付方式不同
-
分期需要在后端接口返回的地址前拼接'https://render.alipay.com/p/s/i?scheme='
-
不分期需要进行form表单提交(form表单提交方法可封装为公共方法,在微信环境、H5环境都可使用)
引导页主要代码如下
<template>
<div :class="$options.name">
<img class="arrow" :src="guidArrow" alt />
<p class="follow">
支付宝支付请使用浏览器进行支付,<br />请在菜单中选择浏览器打开
</p>
</div>
</template>
<script>
import { createAHref, isWeiXin, isMobile,} from "@/publicJs/browser";
import { unifiedOrder } from "@/common/api/api";
export default {
created() {
//获取当前微信浏览器url地址参数
this.getParams();
// 唤起支付
this.invokePay();
},
methods: {
// 获取当前微信浏览器url地址参数
getParams(){
this.theRequest = JSON.parse(this.$route.query.params);
},
invokePay() {
if (isMobile() && isWeiXin()) {
this.is_WeChat = true;
} else if(isMobile() && !isWeiXin()){
this.is_WeChat = false;
unifiedOrder(this.theRequest).then(res=>{
if(this.theRequest.data.contractFlag){
let alipaySignUrl = 'https://render.alipay.com/p/s/i?scheme='+encodeURIComponent(res.data.alipaySignUrl)
createAHref(alipaySignUrl);
}else{
this.createFormSubmit(res.data.alipayForm);
}
})
}
}
}
};
</script>
- 在手机浏览器中
需要前端页面以 Form 表单的形式发起请求,浏览器会自动跳转至支付宝的相关页面(一般是收银台或签约页面),用户在该页面完成相关业务操作后再回跳到商户指定页面
From表单提交代码
createFormSubmit(data) {
var resData = data;
const div = document.createElement("div");
div.id = "alipay";
div.innerHTML = resData;
document.body.appendChild(div);
document.querySelector("#alipay").children[0].submit(); // 执行后会唤起支付宝
},