demo圖
前置操作
1、微信平臺(tái)要配置支付域名
2、申請(qǐng)appid
支付流程
1涨冀、微信支付在微信環(huán)境會(huì)直接喚起支付
2、微信支付在瀏覽器會(huì)先跳轉(zhuǎn)到微信支付麦萤、支付成功與否都會(huì)調(diào)轉(zhuǎn)到你寫的頁(yè)面鹿鳖、加個(gè)彈窗、讓用戶點(diǎn)擊是否支付來(lái)獲取支付狀態(tài)
3频鉴、支付寶在任何環(huán)境下都可以支付
<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() // 自己申請(qǐng)
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('訂單獲取失敗')
}
}
//判斷當(dāng)前環(huán)境(微信/其他)
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 {
// 微信回調(diào)地址
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]
// 通過(guò)code去拿openId
// code作為換取access_token的票據(jù)栓辜,每次用戶授權(quán)帶上的code將不一樣,code只能使用一次垛孔,5分鐘未被使用自動(dòng)過(guò)期
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獲取失敗')
}
}
// 關(guān)閉回調(diào)
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('未支付成功,請(qǐng)重新支付藕甩!')
}
}
return true
}
// 是否支付彈窗
const isPay = () => {
showConfirmDialog({
title: '',
confirmButtonText: '支付完成',
cancelButtonText: '未支付',
confirmButtonColor: 'rgb(206, 51, 58)',
beforeClose,
message:
'請(qǐng)確認(rèn)支付是否完成!',
})
}
// 支付寶支付
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('未支付成功!')
}
},
)
}
}
// 檢測(cè)支付環(huán)境中的 WeixinJSBridge
if (typeof WeixinJSBridge == "undefined"){
if (document.addEventListener) {
//android機(jī)型,調(diào)取支付支付環(huán)境偶爾有延遲狭莱,這里增加延時(shí)器處理
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>