This commit is contained in:
xingyy 2025-02-28 20:30:45 +08:00
parent 437e74ee86
commit 09bbd9ae14
11 changed files with 698 additions and 10 deletions

View File

@ -56,7 +56,7 @@ export async function offlineQrcode(data) {
export async function createOrder(data) { export async function createOrder(data) {
return await request( { return await request( {
url:'/api/v1/offlineQrcode/createOrder', url:'/api/v1/offlineQrcode/createOrder/V2',
method: 'POST', method: 'POST',
data data
}) })

View File

@ -0,0 +1,280 @@
<template>
<div class="stripe-container">
<form id="payment-form" @submit.prevent="handleSubmit">
<div id="payment-element">
<!--Stripe.js injects the Payment Element-->
</div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay now</span>
</button>
<div id="payment-message" class="hidden"></div>
</form>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
// The items the customer wants to buy
const items = [{ id: "xl-tshirt", amount: 1000 }]
const stripe = ref(null)
const elements = ref(null)
const isLoading = ref(false)
onMounted(async () => {
try {
// Stripe
stripe.value = window.Stripe("pk_test_51QfbSAAB1Vm8VfJq3AWsR4k2mZjnlF7XFrmlbc6XVXrtwXquAUfwzZmOFDbxMIAwqJBgqao8KLt2wmPc4vNOCTeo00WB78KtfV")
await initialize()
} catch (error) {
console.error('Stripe initialization error:', error)
showMessage("Failed to initialize payment system")
}
})
// Fetches a payment intent and captures the client secret
const initialize = async () => {
try {
const response = await fetch("/create-payment-intent", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items }),
})
const { clientSecret } = await response.json()
const appearance = {
theme: 'stripe',
}
// elements
elements.value = stripe.value.elements({
appearance,
clientSecret,
})
// Payment Element
const paymentElement = elements.value.create("payment", {
layout: "accordion",
})
// DOM
const mountElement = document.getElementById("payment-element")
if (mountElement) {
paymentElement.mount(mountElement)
} else {
throw new Error("Payment element mount point not found")
}
} catch (error) {
console.error('Payment Element initialization error:', error)
showMessage("Failed to load payment form")
}
}
const handleSubmit = async () => {
if (!stripe.value || !elements.value) {
console.error('Stripe or Elements not initialized')
showMessage("Payment system not initialized")
return
}
setLoading(true)
try {
const { error } = await stripe.value.confirmPayment({
elements: elements.value,
confirmParams: {
return_url: window.location.origin + "/complete.html",
},
})
if (error) {
if (error.type === "card_error" || error.type === "validation_error") {
showMessage(error.message)
} else {
showMessage("An unexpected error occurred.")
}
}
} catch (e) {
console.error('Payment confirmation error:', e)
showMessage("Payment processing failed")
} finally {
setLoading(false)
}
}
const showMessage = (messageText) => {
const messageContainer = document.querySelector("#payment-message")
messageContainer.classList.remove("hidden")
messageContainer.textContent = messageText
setTimeout(() => {
messageContainer.classList.add("hidden")
messageContainer.textContent = ""
}, 4000)
}
// Show a spinner on payment submission
const setLoading = (isLoading) => {
if (isLoading) {
// Disable the button and show a spinner
document.querySelector("#submit").disabled = true
document.querySelector("#spinner").classList.remove("hidden")
document.querySelector("#button-text").classList.add("hidden")
} else {
document.querySelector("#submit").disabled = false
document.querySelector("#spinner").classList.add("hidden")
document.querySelector("#button-text").classList.remove("hidden")
}
}
</script>
<style scoped>
.stripe-container {
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 16px;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
height: 100vh;
width: 100vw;
}
form {
width: 30vw;
min-width: 500px;
align-self: center;
box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);
border-radius: 7px;
padding: 40px;
margin-top: auto;
margin-bottom: auto;
}
.hidden {
display: none;
}
#payment-message {
color: rgb(105, 115, 134);
font-size: 16px;
line-height: 20px;
padding-top: 12px;
text-align: center;
}
#payment-element {
margin-bottom: 24px;
}
button {
background: #0055DE;
font-family: Arial, sans-serif;
color: #ffffff;
border-radius: 4px;
border: 0;
padding: 12px 16px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
display: block;
transition: all 0.2s ease;
box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
width: 100%;
}
button:hover {
filter: contrast(115%);
}
button:disabled {
opacity: 0.5;
cursor: default;
}
.spinner,
.spinner:before,
.spinner:after {
border-radius: 50%;
}
.spinner {
color: #ffffff;
font-size: 22px;
text-indent: -99999px;
margin: 0px auto;
position: relative;
width: 20px;
height: 20px;
box-shadow: inset 0 0 0 2px;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
}
.spinner:before,
.spinner:after {
position: absolute;
content: "";
}
.spinner:before {
width: 10.4px;
height: 20.4px;
background: #0055DE;
border-radius: 20.4px 0 0 20.4px;
top: -0.2px;
left: -0.2px;
-webkit-transform-origin: 10.4px 10.2px;
transform-origin: 10.4px 10.2px;
-webkit-animation: loading 2s infinite ease 1.5s;
animation: loading 2s infinite ease 1.5s;
}
.spinner:after {
width: 10.4px;
height: 10.2px;
background: #0055DE;
border-radius: 0 10.2px 10.2px 0;
top: -0.1px;
left: 10.2px;
-webkit-transform-origin: 0px 10.2px;
transform-origin: 0px 10.2px;
-webkit-animation: loading 2s infinite ease;
animation: loading 2s infinite ease;
}
@-webkit-keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@media only screen and (max-width: 600px) {
form {
width: 80vw;
min-width: initial;
}
}
</style>

View File

@ -0,0 +1,373 @@
<script setup>
import { onMounted, ref } from 'vue'
import {authStore} from "~/stores/auth/index.js";
import {useRuntimeConfig} from "#app";
import {orderQuery} from "~/api/goods/index.js";
const {checkoutSessionUrl,payUid}= authStore()
const config = useRuntimeConfig()
definePageMeta({
layout: 'default',
title: 'Stripe支付'
})
console.log('config.public.NUXT_PUBLIC_PKEY',config.public.NUXT_PUBLIC_PKEY);
const stripe = Stripe(config.public.NUXT_PUBLIC_PKEY)
const baseURL = config.public.NUXT_PUBLIC_API_BASE
const items = [{ id: "xl-tshirt", amount: 1000 }]
const elements = ref(null)
const paymentMessage = ref('')
const isLoading = ref(false)
const showSpinner = ref(false)
async function initialize() {
const clientSecret = checkoutSessionUrl.value
console.log('clientSecret',clientSecret);
const appearance = {
theme: 'stripe',
}
elements.value = stripe.elements({ appearance, clientSecret })
const paymentElementOptions = {
layout: "accordion",
}
const paymentElement = elements.value.create("payment", paymentElementOptions)
paymentElement.mount("#payment-element")
}
async function handleSubmit(e) {
e.preventDefault()
setLoading(true)
let pollTimer = null
let timeoutTimer = null
const startPolling = () => {
pollTimer = setInterval(async () => {
const res = await orderQuery({
orderNo: payUid.value
})
if (res.status === 0) {
if (res.data.status !== 3) {
clearInterval(pollTimer)
clearTimeout(timeoutTimer)
window.location.href = `${baseURL}/payment/result?orderNo=${payUid.value}`
}
}
}, 1000)
timeoutTimer = setTimeout(() => {
clearInterval(pollTimer)
showMessage('支付超时,请重试')
setLoading(false)
}, 180000) // 3
}
startPolling()
const { error } = await stripe.confirmPayment({
elements: elements.value,
confirmParams: {
return_url: `${baseURL}/payment/result?orderNo=${payUid.value}`,
},
})
if (error) {
clearInterval(pollTimer)
clearTimeout(timeoutTimer)
if (error.type === "card_error" || error.type === "validation_error") {
showMessage(error.message)
} else {
showMessage("An unexpected error occurred.")
}
setLoading(false)
}
}
function showMessage(messageText) {
paymentMessage.value = messageText
setTimeout(() => {
paymentMessage.value = ''
}, 4000)
}
function setLoading(loading) {
isLoading.value = loading
showSpinner.value = loading
}
onMounted(() => {
initialize()
})
</script>
<template>
<form id="payment-form" @submit="handleSubmit">
<div id="payment-element">
</div>
<button id="submit">
<div class="spinner" :class="{ hidden: !showSpinner }" id="spinner"></div>
<span id="button-text" :class="{ hidden: showSpinner }">Pay now</span>
</button>
<div id="payment-message" :class="{ hidden: !paymentMessage }">{{ paymentMessage }}</div>
</form>
</template>
<style scoped>
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 16px;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
height: 100vh;
width: 100vw;
}
form {
align-self: center;
box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);
border-radius: 7px;
padding: 40px;
margin-top: auto;
margin-bottom: auto;
}
.hidden {
display: none;
}
#payment-message {
color: rgb(105, 115, 134);
font-size: 16px;
line-height: 20px;
padding-top: 12px;
text-align: center;
}
#payment-element {
margin-bottom: 24px;
}
/* Buttons and links */
button {
background: #0055DE;
font-family: Arial, sans-serif;
color: #ffffff;
border-radius: 4px;
border: 0;
padding: 12px 16px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
display: block;
transition: all 0.2s ease;
box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
width: 100%;
}
button:hover {
filter: contrast(115%);
}
button:disabled {
opacity: 0.5;
cursor: default;
}
/* spinner/processing state, errors */
.spinner,
.spinner:before,
.spinner:after {
border-radius: 50%;
}
.spinner {
color: #ffffff;
font-size: 22px;
text-indent: -99999px;
margin: 0px auto;
position: relative;
width: 20px;
height: 20px;
box-shadow: inset 0 0 0 2px;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
}
.spinner:before,
.spinner:after {
position: absolute;
content: "";
}
.spinner:before {
width: 10.4px;
height: 20.4px;
background: #0055DE;
border-radius: 20.4px 0 0 20.4px;
top: -0.2px;
left: -0.2px;
-webkit-transform-origin: 10.4px 10.2px;
transform-origin: 10.4px 10.2px;
-webkit-animation: loading 2s infinite ease 1.5s;
animation: loading 2s infinite ease 1.5s;
}
.spinner:after {
width: 10.4px;
height: 10.2px;
background: #0055DE;
border-radius: 0 10.2px 10.2px 0;
top: -0.1px;
left: 10.2px;
-webkit-transform-origin: 0px 10.2px;
transform-origin: 0px 10.2px;
-webkit-animation: loading 2s infinite ease;
animation: loading 2s infinite ease;
}
/* Payment status page */
#payment-status {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
row-gap: 30px;
width: 30vw;
min-width: 500px;
min-height: 380px;
align-self: center;
box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);
border-radius: 7px;
padding: 40px;
opacity: 0;
animation: fadeInAnimation 1s ease forwards;
}
#status-icon {
display: flex;
justify-content: center;
align-items: center;
height: 40px;
width: 40px;
border-radius: 50%;
}
h2 {
margin: 0;
color: #30313D;
text-align: center;
}
a {
text-decoration: none;
font-size: 16px;
font-weight: 600;
font-family: Arial, sans-serif;
display: block;
}
a:hover {
filter: contrast(120%);
}
#details-table {
overflow-x: auto;
width: 100%;
}
table {
width: 100%;
font-size: 14px;
border-collapse: collapse;
}
table tbody tr:first-child td {
border-top: 1px solid #E6E6E6; /* Top border */
padding-top: 10px;
}
table tbody tr:last-child td {
border-bottom: 1px solid #E6E6E6; /* Bottom border */
}
td {
padding-bottom: 10px;
}
.TableContent {
text-align: right;
color: #6D6E78;
}
.TableLabel {
font-weight: 600;
color: #30313D;
}
#view-details {
color: #0055DE;
}
#retry-button {
text-align: center;
background: #0055DE;
color: #ffffff;
border-radius: 4px;
border: 0;
padding: 12px 16px;
transition: all 0.2s ease;
box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
width: 100%;
}
@-webkit-keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes fadeInAnimation {
to {
opacity: 1;
}
}
@media only screen and (max-width: 600px) {
form, #payment-status{
width: 80vw;
min-width: initial;
}
}
.hidden {
display: none;
}
form {
width:100vw;
align-self: center;
box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);
border-radius: 7px;
padding: 40px;
margin-top: auto;
margin-bottom: auto;
}
/* 其他样式保持不变... */
</style>

View File

@ -10,7 +10,7 @@ import {codeAuthStore} from "~/stores-collect-code/auth/index.js";
import {useI18n} from "vue-i18n"; import {useI18n} from "vue-i18n";
const {t} = useI18n(); const {t} = useI18n();
const {checkoutSessionUrl,qrUid,qrData} = codeAuthStore() const {checkoutSessionUrl,qrUid,qrData,codePKey,codePayUid} = codeAuthStore()
const payStatus = ref(0) const payStatus = ref(0)
definePageMeta({ definePageMeta({
i18n: 'payment.title' i18n: 'payment.title'
@ -40,7 +40,11 @@ const confirmPay = async () => {
testReturnEndPoint: '/collectCode/payment/result' testReturnEndPoint: '/collectCode/payment/result'
}) })
if (res.status === 0) { if (res.status === 0) {
window.location.href = res.data.checkoutSessionUrl codePKey.value=res.data.checkoutSessionUrl
codePayUid.value=res.data.payUid
// window.location.href = res.data.checkoutSessionUrl
console.log('res',res);
} }
} }
@ -75,8 +79,8 @@ const handleInput = (e) => {
{{ qrData?.leftPrice }} {{ qrData?.leftPrice }}
</div> </div>
<div class="mb-12px" v-else> <div class="mb-12px" v-else>
<input v-model="amount" class="w-272px h-48px bg-#F3F3F3 px-11px text-16px" type="text" <input v-model="amount" class="w-272px h-48px bg-#F3F3F3 px-11px text-16px" type="text"
:placeholder="$t('collectCode.payment.maxAmount', { currency: qrData.currency, price: qrData?.leftPrice })" @input="handleInput"> :placeholder="`${$t('collectCode.payment.maxAmount')} ${qrData.currency} ${qrData?.leftPrice}`" @input="handleInput">
</div> </div>
<div class="text-#2B53AC text-14px" @click="changePayStatus">{{ payStatus === 1 ? $t('collectCode.payment.fullPayment') : $t('collectCode.payment.partialPayment') }}</div> <div class="text-#2B53AC text-14px" @click="changePayStatus">{{ payStatus === 1 ? $t('collectCode.payment.fullPayment') : $t('collectCode.payment.partialPayment') }}</div>
<div class="w-full mt-auto mb-40px"> <div class="w-full mt-auto mb-40px">

View File

@ -55,7 +55,7 @@ async function handleSubmit(e) {
window.location.href = `${baseURL}/payment/result?orderNo=${payUid.value}` window.location.href = `${baseURL}/payment/result?orderNo=${payUid.value}`
} }
} }
}, 1000) // 3 }, 1000)
timeoutTimer = setTimeout(() => { timeoutTimer = setTimeout(() => {
clearInterval(pollTimer) clearInterval(pollTimer)

View File

@ -26,7 +26,11 @@ export const codeAuthStore = createGlobalState(() => {
currency:'' currency:''
}) })
const qrData=useLocalStorage('qrData',{}) const qrData=useLocalStorage('qrData',{})
const codePKey=useLocalStorage('codePKey','')
const codePayUid=useLocalStorage('codePayUid','')
return{ return{
codePKey,
codePayUid,
qrData, qrData,
qrUid, qrUid,
cpayment, cpayment,

View File

@ -423,7 +423,7 @@
"fullPayment": "Pay in Full", "fullPayment": "Pay in Full",
"partialPayment": "Partial Payment", "partialPayment": "Partial Payment",
"confirmPayment": "Confirm Payment", "confirmPayment": "Confirm Payment",
"maxAmount": "Maximum {currency}{price}", "maxAmount": "most",
"enterAmount": "Please enter amount", "enterAmount": "Please enter amount",
"exceedTotal": "Cannot exceed total amount" "exceedTotal": "Cannot exceed total amount"
}, },

View File

@ -423,7 +423,7 @@
"fullPayment": "全額支払い", "fullPayment": "全額支払い",
"partialPayment": "一部支払い", "partialPayment": "一部支払い",
"confirmPayment": "支払い確認", "confirmPayment": "支払い確認",
"maxAmount": "最大 {currency}{price}", "maxAmount": "ほとんど",
"enterAmount": "金額を入力してください", "enterAmount": "金額を入力してください",
"exceedTotal": "合計金額を超えることはできません" "exceedTotal": "合計金額を超えることはできません"
}, },

View File

@ -426,7 +426,8 @@
"confirmPayment": "确认支付", "confirmPayment": "确认支付",
"text1": "最多", "text1": "最多",
"enterAmount": "请输入金额", "enterAmount": "请输入金额",
"exceedTotal": "不得高于全部金额" "exceedTotal": "不得高于全部金额",
"maxAmount": "最多"
}, },
"signature": { "signature": {
"resultText": "领取您的专属号牌", "resultText": "领取您的专属号牌",

View File

@ -423,7 +423,7 @@
"fullPayment": "支付全部", "fullPayment": "支付全部",
"partialPayment": "支付部分", "partialPayment": "支付部分",
"confirmPayment": "確認支付", "confirmPayment": "確認支付",
"maxAmount": "最多{currency}{price}", "maxAmount": "最多",
"enterAmount": "請輸入金額", "enterAmount": "請輸入金額",
"exceedTotal": "不得高於全部金額" "exceedTotal": "不得高於全部金額"
}, },

View File

@ -0,0 +1,26 @@
export default defineEventHandler(async (event) => {
const url = getRequestURL(event)
// 只处理 create-payment-intent 请求
if (url.pathname === '/create-payment-intent' && event.method === 'POST') {
try {
const body = await readBody(event)
const { items } = body
// 计算总金额
const amount = items.reduce((total: number, item: any) => total + item.amount, 0)
// 模拟创建支付意向的响应
// 注意clientSecret 格式应该类似于 'pi_xxxxx_secret_xxxxx'
return {
clientSecret: `pi_${Math.random().toString(36).substring(2)}_secret_${Math.random().toString(36).substring(2)}`
}
} catch (error) {
console.error('Create payment intent error:', error)
throw createError({
statusCode: 500,
message: '创建支付意向失败'
})
}
}
})