微信公众号支付
1.首先公众号授权获取code
// 如果已经拿到code并且获取到openid以后就停止重定向
if (localOpenid) {
return
} else {
// 如果浏览器地址栏参数没有code,那就控制重定向
if (!localtion.search) {
//企业应用ID
const appId = 'xxxxxxx'
//重定向域名(需要在微信商户后台配置jsapi支付回调域名)
const url = `${process.env.REACT_APP_REDIRECT_BASEURL}%2Ftopup%2F`
// 微信授权的重定向链接
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=divtoss#wechat_redirect`
}
// 如果浏览器地址栏参数code存在,去请求后端获取openId
if (localtion.search) {
const paramsObj = urlParamsToObject(localtion.search)
if (paramsObj.code) {
// 去请求后端获取openId的方法
queryOpenId(paramsObj)
}
}
}
- 第二步、请求后端接口下单
- 第三部调起公众号支付
officiaLAccountPay({
appId: 'xxxxxx', // 公众号ID,由商户传入
timeStamp: 'xxxxxx', // 时间戳,自1970年以来的秒数
nonceStr: 'xxxxxx', // 随机串
package: 'prepay_id=' + thirdTradeInfo.package.split('=')[1],
signType: 'xxxxxxx', // 微信签名方式:
paySign: '' // 微信签名
})
// 公众号支付
const officiaLAccountPay = (options: any) => {
// @ts-ignore
if (typeof WeixinJSBridge === "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
// @ts-ignore
} else if (document.attachEvent) {
// @ts-ignore
document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
// @ts-ignore
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
}
} else {
onBridgeReady(options)
}
}
const onBridgeReady = (options: any) => {
Toast.hide()
// @ts-ignore
WeixinJSBridge.invoke('getBrandWCPayRequest', options, // eslint-disable-line
function (res: any) {
if (res.err_msg === "get_brand_wcpay_request:ok") {
history.push('/topup/success')
}
if (res.err_msg === "get_brand_wcpay_request:cancel") {
Toast.fail('支付取消')
}
if (res.err_msg === "get_brand_wcpay_request:fail") {
Toast.fail('支付失败')
}
})
}
微信H5支付
- 第一步、先请求后端接口下单
- 第二部重定向到微信H5支付页面
//xxx 是回调域名(需在微信商家后台配置),支付完成后跳转的页面
const redirect = `${xxx}%2Ftopup%2Fwaite`
//h5_url: 下单完成,后端反悔的重定向的页面
window.location.href = `${h5_url}&redirect_url=${redirect}`
支付宝H5支付
1.第一步,请求后端下单接口,会返回form表单
2.打开这个form表单
const divForm = document.getElementsByTagName('divform')
if (divForm.length) {
document.body.removeChild(divForm[0])
}
const div = document.createElement('divform')
div.innerHTML = thirdTradeInfo.form // data就是接口返回的form 表单字符串
document.body.appendChild(div)
document.forms[0].submit()