基于 Vue 3 和 Stripe 实现在线支付功能

文章目录

  • 一、项目背景与功能概览
  • 二、项目准备与依赖安装
    • 2.1 安装 Vue 3 项目
    • 2.2 安装 Stripe SDK
    • 2.3 安装支付宝和微信支付的 SDK
    • 2.4 获取 Stripe、支付宝和微信支付的 API 密钥
  • 三、集成 Stripe 支付功能
    • 3.1 创建支付组件
      • 3.1.1 创建支付请求
    • 3.2 后端实现支付意图生成
  • 四、支付成功与失败回调处理
    • 4.1 支付成功处理
    • 4.2 支付失败处理
  • 五、订单管理功能实现
    • 5.1 创建订单
    • 5.2 查询订单状态
    • 5.3 支付失败后的订单处理

一、项目背景与功能概览

在线支付已经成为现代互联网应用中不可或缺的功能,Stripe 提供了简便、灵活的 API 接口,帮助开发者在应用中实现支付功能。本项目将结合 Vue 3Stripe,实现一个简易的在线支付功能,支持信用卡支付、支付宝、微信支付等多种方式,并包含订单提交与支付成功回调处理。

主要功能包括:

  • 创建支付订单
  • 支持信用卡支付、支付宝、微信支付等多种支付方式
  • 订单支付成功/失败回调处理
  • 支付方式选择与切换
  • 订单管理功能

二、项目准备与依赖安装

2.1 安装 Vue 3 项目

首先,使用 Vue CLI 或 Vite 创建一个 Vue 3 项目:

npm create vite@latest vue-stripe-payment --template vue-ts
cd vue-stripe-payment
npm install

2.2 安装 Stripe SDK

为了实现支付功能,我们需要安装 Stripe 的 JavaScript SDK。执行以下命令来安装:

npm install @stripe/stripe-js

2.3 安装支付宝和微信支付的 SDK

我们将同时集成支付宝和微信支付的 JS SDK,进行支付方式的扩展。

npm install wechat-pay stripe-alipay-sdk

2.4 获取 Stripe、支付宝和微信支付的 API 密钥

在 Stripe 官网 获取 Publishable KeySecret Key,并根据需求到支付宝和微信支付官网获取相应的 API 密钥。

三、集成 Stripe 支付功能

3.1 创建支付组件

src/components 目录下创建 StripePayment.vue 组件,负责实现支付功能。该组件支持选择不同支付方式并执行相应的支付流程。

3.1.1 创建支付请求

在前端,首先需要调用后端接口,生成支付意图并返回 clientSecret。然后通过 Stripe 的 JS SDK 发起支付请求。

<template>
  <div>
    <h2>选择支付方式</h2>
    <select v-model="selectedPaymentMethod">
      <option value="stripe">Stripe (信用卡)</option>
      <option value="wechat">微信支付</option>
      <option value="alipay">支付宝支付</option>
    </select>

    <button @click="pay">支付</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { loadStripe } from '@stripe/stripe-js'
import axios from 'axios'

const selectedPaymentMethod = ref('stripe')
const stripePromise = loadStripe('your-publishable-key-here') // 替换为你的 Publishable Key

const pay = async () => {
  let response
  let clientSecret

  // 调用后端接口生成 clientSecret
  if (selectedPaymentMethod.value === 'stripe') {
    response = await axios.post('/api/create-payment-intent', { method: 'stripe' })
  } else if (selectedPaymentMethod.value === 'wechat') {
    response = await axios.post('/api/create-payment-intent', { method: 'wechat' })
  } else if (selectedPaymentMethod.value === 'alipay') {
    response = await axios.post('/api/create-payment-intent', { method: 'alipay' })
  }

  clientSecret = response.data.clientSecret

  const stripe = await stripePromise

  if (selectedPaymentMethod.value === 'stripe') {
    const { error } = await stripe.confirmCardPayment(clientSecret, {
      payment_method: {
        card: document.querySelector('input[name="card-element"]'),
      },
    })
    if (error) {
      console.log('支付失败:', error.message)
    } else {
      console.log('支付成功')
    }
  }
}
</script>

3.2 后端实现支付意图生成

后端通过调用 Stripe、支付宝和微信支付的 API 创建支付意图,并根据支付方式返回相应的 clientSecret

// backend/server.js
const express = require('express')
const stripe = require('stripe')('your-secret-key-here') // Stripe Secret Key
const wechatPay = require('wechat-pay')
const alipay = require('stripe-alipay-sdk')

const app = express()
app.use(express.json())

app.post('/api/create-payment-intent', async (req, res) => {
  const { method } = req.body
  try {
    let clientSecret
    if (method === 'stripe') {
      const paymentIntent = await stripe.paymentIntents.create({
        amount: 2000, 
        currency: 'usd',
      })
      clientSecret = paymentIntent.client_secret
    } else if (method === 'wechat') {
      const paymentIntent = await wechatPay.createPaymentIntent({
        amount: 2000, 
        currency: 'CNY',
      })
      clientSecret = paymentIntent.client_secret
    } else if (method === 'alipay') {
      const paymentIntent = await alipay.createPaymentIntent({
        amount: 2000, 
        currency: 'CNY',
      })
      clientSecret = paymentIntent.client_secret
    }

    res.send({ clientSecret })
  } catch (error) {
    res.status(500).send({ error: error.message })
  }
})

app.listen(3000, () => {
  console.log('Server is running on port 3000')
})

四、支付成功与失败回调处理

4.1 支付成功处理

在支付成功后,Stripe、微信支付和支付宝都会触发一个回调,前端可以通过支付状态来判断支付成功与否。

// 支付成功后回调处理
if (paymentIntent.status === 'succeeded') {
  console.log('支付成功!')
  // 订单更新等操作
}

4.2 支付失败处理

如果支付失败,可以通过 error.message 来显示错误信息。

// 处理支付失败
if (error) {
  console.log('支付失败:', error.message)
  // 提示用户支付失败的原因
}

五、订单管理功能实现

5.1 创建订单

支付成功后,我们需要创建订单并将订单状态更新为已支付。在此过程中,我们可以记录支付详情、订单商品信息等。

// 创建订单
const createOrder = async (paymentIntent) => {
  const order = {
    userId: userId,
    items: cartItems,
    totalAmount: totalAmount,
    paymentStatus: 'succeeded',
    paymentId: paymentIntent.id,
  }
  
  // 保存到数据库(假设我们有一个数据库方法)
  await saveOrderToDatabase(order)
}

5.2 查询订单状态

你可以通过订单 ID 来查询订单的支付状态,更新数据库中的订单信息,并进行适当的后续处理。

// 查询订单状态
const checkOrderStatus = async (orderId) => {
  const order = await getOrderFromDatabase(orderId)
  if (order.paymentStatus === 'succeeded') {
    console.log('订单已支付')
  } else {
    console.log('订单未支付')
  }
}

5.3 支付失败后的订单处理

当支付失败时,应该对订单进行相应的处理,例如重试支付、通知用户等。

// 处理支付失败
const handlePaymentFailure = async (orderId) => {
  const order = await getOrderFromDatabase(orderId)
  order.paymentStatus = 'failed'
  await updateOrderInDatabase(order)
  console.log('支付失败,订单状态已更新')
}

到这里,这篇文章就和大家说再见啦!我的主页里还藏着很多 篇 前端 实战干货,感兴趣的话可以点击头像看看,说不定能找到你需要的解决方案~
创作这篇内容花了很多的功夫。如果它帮你解决了问题,或者带来了启发,欢迎:
点个赞❤️ 让更多人看到优质内容
关注「前端极客探险家」 每周解锁新技巧
收藏文章⭐️ 方便随时查阅
特别提醒:
转载请注明原文链接,商业合作请私信联系
感谢你的阅读!我们下篇文章再见~

在这里插入图片描述

你可能感兴趣的:(vue.js,前端,javascript)