介绍
前端调用paypal 钱包支付流程和代码示例
# 🎏 使用场景
注册 PayPal 商家账户:访问 PayPal 官方网站
从home 首页 点击 paypal Checkout 根据指示 获取client_id 并创建沙盒凭证client Id
安装前端paypal的 SDK
npm install @paypal/paypal-js
支付按钮的组件
<!-- components/PaypalCheckout.vue -->
<template>
<div>
<!-- PayPal 按钮容器 -->
<div id="paypal-button-container" ref="paypalButton"></div>
<!-- 支付状态提示 -->
<div v-if="status" :class="statusClass">
{{ statusMessage }}
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { loadScript } from '@paypal/paypal-js'
const props = defineProps({
// 金额(必须)
amount: {
type: Number,
required: true,
validator: value => value > 0
},
// 商品描述
description: {
type: String,
default: 'Purchase Item'
},
// 货币类型
currency: {
type: String,
default: 'USD'
}
})
// 状态管理
const status = ref('') // idle | loading | success | error
const statusMessage = ref('')
const statusClass = computed(() => ({
'text-green-500': status.value === 'success',
'text-red-500': status.value === 'error',
'text-gray-600': status.value === 'idle'
}))
/**
* 创建 PayPal 订单
*/
const createOrder = async () => {
status.value = 'loading'
statusMessage.value = 'Creating order...'
try {
// 调用后端接口创建订单
const { orderID } = await $fetch('/api/paypal/createOrder', {
method: 'POST',
body: {
amount: props.amount,
currency: props.currency,
description: props.description
}
})
statusMessage.value = 'Order created, redirecting...'
return orderID // 返回订单ID给 PayPal
} catch (error) {
status.value = 'error'
statusMessage.value = 'Failed to create order'
throw error // 抛出错误以触发 PayPal 的 onError
}
}
/**
* 支付成功处理
*/
const onApprove = async (data) => {
status.value = 'loading'
statusMessage.value = 'Processing payment...'
try {
// 调用后端捕获订单
const result = await $fetch('/api/paypal/captureOrder', {
method: 'POST',
body: { orderID: data.orderID }
})
status.value = 'success'
statusMessage.value = 'Payment successful! Redirecting...'
// 2秒后跳转到成功页面
setTimeout(() => {
navigateTo('/payment/success')
}, 2000)
} catch (error) {
status.value = 'error'
statusMessage.value = 'Payment processing failed'
}
}
/**
* 初始化 PayPal 按钮
*/
onMounted(async () => {
try {
// 动态加载 PayPal JS SDK
const paypal = await loadScript({
clientId: process.env.PAYPAL_CLIENT_ID, // 从环境变量获取 从paypal 官网中获取的client id
currency: props.currency, // 使用传入的货币类型
intent: 'capture', // 明确支付意图
commit: true, // 显示立即支付按钮
})
// 渲染支付按钮
paypal.Buttons({
style: {
color: 'gold',
shape: 'rect',
label: 'paypal',
height: 40
},
createOrder, // 绑定订单创建方法
onApprove, // 绑定支付成功处理
onError: (err) => {
status.value = 'error'
statusMessage.value = `Payment error: ${err.message}`
},
onCancel: (data) => {
status.value = 'idle'
statusMessage.value = 'Payment canceled'
}
}).render('#paypal-button-container')
} catch (error) {
console.error('Failed to load PayPal SDK:', error)
status.value = 'error'
statusMessage.value = 'Payment system unavailable'
}
})
</script>
<style scoped>
/* 基础样式 */
#paypal-button-container {
min-height: 80px;
position: relative;
}
.text-green-500 { color: #10B981; }
.text-red-500 { color: #EF4444; }
.text-gray-600 { color: #4B5563; }
</style>
