demo图
前置操作
1、微信平台要配置支付域名
2、申请appid
支付流程
1、微信支付在微信环境会直接唤起支付
2、微信支付在浏览器会先跳转到微信支付、支付成功与否都会调转到你写的页面、加个弹窗、让用户点击是否支付来获取支付状态
3、支付宝在任何环境下都可以支付
<template>
<div class="pay-page">
<div class="pay-moneny">
<span>¥</span>
<span class="pay-account">{{ amount }}</span>
</div>
<div class="pay-title">
{{ tradeItem }}
</div>
<div class="pay-type">
<p>选择支付方式</p>
<van-radio-group v-model="formData.payPlate">
<div class="pay-list">
<div class="left">
<img src="@/assets/images/wxpay.png" alt="微信">
<span>微信</span>
</div>
<van-radio checked-color="rgb(206,51,58)" name="wechat" />
</div>
<div class="pay-list">
<div class="left">
<img src="@/assets/images/zfpay.png" alt="支付宝">
<span>支付宝</span>
</div>
<van-radio checked-color="rgb(206,51,58)" name="alipay" />
</div>
</van-radio-group>
</div>
<div class="btn-bottom">
<van-button style="background: rgb(206,51,58);color: #ffffff;" block @click="pay">立即支付</van-button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue"
import { showToast, showConfirmDialog } from 'vant';
import { getOpenId, allPay, getOrderInfo, getOrderList } from '@/api/pay.ts' // 接口API
import { useRouter, useRoute } from 'vue-router'
useHead({
title: '支付',
meta: [
{ hid: 'keywords', name: 'keywords', content: ' bingbing' }
]
})
const router = useRouter()
const route = useRoute()
const formData = reactive({
openId: '',
payPlate: 'wechat',
productId: '',
tradeId: '',
flowId: '',
tradeType: ''
})
const appId = ref() // 自己申请
const loading = ref(false)
const amount = ref()
const tradeItem = ref()
const redirectUrl = ref()
onMounted(() => {
const query = route.query
const openId = localStorage.getItem('openId')
if(getEnvironment() == 'weixin'){
if(openId) {
formData.openId = openId
}else {
checkCode()
}
}
if(query.tradeId) {
formData.tradeId = query.tradeId
getOrder()
if(query.fromWx == 'y') {
isPay()
}
}
if(query.out_trade_no) {
formData.flowId = route.query.out_trade_no
isPay()
}
})
// 获取订单信息
const getOrder = async () => {
const res = await getOrderInfo({
tradeId: formData.tradeId,
flowId: formData.flowId
})
if(res.code === 'SUCCESS'){
amount.value = res.data.amount
tradeItem.value = res.data.tradeItem
redirectUrl.value = res.data.redirectUrl
}else{
showToast('订单获取失败')
}
}
//判断当前环境(微信/其他)
const getEnvironment = () => {
let ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return 'weixin'
}else {
return 'other'
}
}
// 立即支付
const pay = async () => {
let payInfo = {}
loading.value = true
const res = await allPay({
...formData,
tradeType: formData.payPlate == 'alipay' ? 'MWEB' : getEnvironment() == 'weixin' ? 'JSAPI' : 'MWEB'
})
loading.value = false
if(res.code === 'SUCCESS') {
payInfo = {
nonceStr: res.data.nonceStr,
prepayIdPackage: res.data.prepayIdPackage,
paySign: res.data.paySign,
timeStamp: res.data.timeStamp,
signType: res.data.signType,
mwebUrl: res.data.mwebUrl,
formContent: res.data.formContent
}
}else {
showToast(res.message)
return false
}
if(formData.payPlate == 'wechat') {
// 微信支付的两种方式
if(getEnvironment() == 'weixin') {
pullWchatPay(payInfo)
}else {
// 微信回调地址
location.href = payInfo.mwebUrl + '&redirect_url=' + encodeURIComponent(window.location.href + '&fromWx=y')
}
}else if (formData.payPlate == 'alipay') {
// 支付宝支付
pullAliPay(payInfo.formContent)
}
}
// 获取微信用户code
const checkCode = () =>{
let link = window.location.href;
let code = null;
if(link.indexOf('code=') === -1){
let url = encodeURIComponent(link)
let authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId.value}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
window.location.href = authUrl
}else{
let temp = link.split("code=")[1]
code = temp.split("&")[0]
// 通过code去拿openId
// code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期
getUserOpenId(code)
}
}
// 获取openId
const getUserOpenId = async (code) => {
const res = await getOpenId({code})
if(res.code === 'SUCCESS'){
formData.openId = res.data.openId
localStorage.setItem('openId', formData.openId)
}else{
showToast('openId获取失败')
}
}
// 关闭回调
const beforeClose = async () => {
const res = await getOrderList({tradeId: formData.tradeId})
if(res.code === 'SUCCESS') {
if(res.data.status == 'success') {
router.push({path: '/result', query: {redirectUrl: redirectUrl.value}})
}else {
showToast('未支付成功,请重新支付!')
}
}
return true
}
// 是否支付弹窗
const isPay = () => {
showConfirmDialog({
title: '',
confirmButtonText: '支付完成',
cancelButtonText: '未支付',
confirmButtonColor: 'rgb(206, 51, 58)',
beforeClose,
message:
'请确认支付是否完成!',
})
}
// 支付宝支付
const pullAliPay = (dom) => {
window.open(dom, '_self')
// document.querySelector('body').innerHTML = dom
// nextTick(()=>{
// window.document.forms[0].submit()
// isPay()
// })
}
//拉取微信支付
const pullWchatPay = ({nonceStr, prepayIdPackage, paySign, timeStamp, signType}) => {
let onBridgeReady = () => {
if(WeixinJSBridge && appId.value){
WeixinJSBridge.invoke('getBrandWCPayRequest',{
appId: appId.value,
nonceStr,
package: prepayIdPackage,
paySign,
signType,
timeStamp
},
function (res) {
if(res.err_msg==='get_brand_wcpay_request:ok'){
router.push({path: '/result', query: {redirectUrl: redirectUrl.value}})
}else{
showToast('未支付成功!')
}
},
)
}
}
// 检测支付环境中的 WeixinJSBridge
if (typeof WeixinJSBridge == "undefined"){
if (document.addEventListener) {
//android机型,调取支付支付环境偶尔有延迟,这里增加延时器处理
var timev=setTimeout(()=>{
clearTimeout(timev)
document.addEventListener('WeixinJSBridgeReady', onBridgeReady(),
false);
},1000)
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', onBridgeReady());
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady());
}
} else {
onBridgeReady();
}
}
</script>
<style lang="scss" scoped>
.pay-page {
width: 100%;
.pay-moneny {
display: flex;
justify-content: center;
margin-top: 40px;
margin-bottom: 8px;
span {
font-size: 24px;
font-weight: 600;
box-sizing: border-box;
vertical-align: bottom;
display: flex;
align-items: flex-end;
line-height: 1;
}
.pay-account {
font-size: 40px;
font-weight: 600;
}
}
.pay-title {
display: flex;
justify-content: center;
font-size: 12px;
color: rgba(91, 103, 124, 1);
}
.pay-type {
background: rgba(255, 255, 255, 1);
border-radius: 2px;
padding: 12px;
margin-top: 24px;
p {
font-size: 14px;
color: rgba(5, 5, 6, 1);
line-height: 1;
margin-bottom: 12px;
}
.pay-list {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 0;
.left {
display: flex;
align-items: center;
img {
width: 24px;
height: 24px;
margin-right: 8px;
}
span {
font-size: 14px;
color: rgba(24, 24, 24, 1);
}
}
}
}
.btn-bottom {
width: calc(100% - 48px);
padding: 0 24px;
position: fixed;
bottom: 70px;
left: 0;
}
}
@media screen and (min-width: 1164px) {
.btn-bottom {
position: static !important;
margin-top: 20px;
padding: 0 !important;
width: 100% !important;
}
}
</style>