uniapp 如何使用stripe进行支付集成

“在UniApp中集成Stripe支付时遇到了问题,具体流程不太清楚。有没有详细步骤或示例代码可以参考?主要是前端如何对接Stripe,后端如何处理支付回调?另外需要注意哪些跨域或配置问题?求大佬解答!”

2 回复

在uniapp中集成Stripe支付,可通过以下步骤:

  1. 使用uni.request调用Stripe API
  2. 创建支付意图(PaymentIntent)
  3. 使用Stripe.js处理支付表单
  4. 验证支付结果

注意:需在服务端处理敏感操作,避免泄露密钥。


在 UniApp 中集成 Stripe 支付,可以通过以下步骤实现。由于 UniApp 本身不直接支持 Stripe,需结合 Web 端或原生插件完成。以下是基于 Web 端集成的推荐方法(适用于 H5 平台),并简要说明原生方案。

步骤 1:准备工作

  1. 注册 Stripe 账户:访问 Stripe 官网 创建账户,获取 Publishable Key(前端用)和 Secret Key(后端用)。
  2. 准备后端环境:Stripe 支付需后端生成支付凭证(如 PaymentIntent),确保有可调用后端 API。

步骤 2:前端集成(H5 平台)

在 UniApp 的 H5 平台中,通过 uni.request 调用后端 API,并使用 Stripe.js 处理支付。

  1. 引入 Stripe.js: 在 index.html 或页面中加载 Stripe.js:

    <script src="https://js.stripe.com/v3/"></script>
    
  2. 创建支付页面

    • 通过后端 API 获取 client_secret(由 Stripe PaymentIntent 生成)。
    • 使用 Stripe.js 确认支付。

    示例代码(Vue 页面):

    <template>
      <view>
        <button @click="handlePayment">支付</button>
      </view>
    </template>
    
    <script>
    export default {
      data() {
        return {
          stripe: null,
          elements: null,
        };
      },
      mounted() {
        // 初始化 Stripe(仅 H5 环境)
        if (typeof Stripe !== 'undefined') {
          this.stripe = Stripe('你的_Publishable_Key');
        }
      },
      methods: {
        async handlePayment() {
          // 1. 调用后端 API 创建 PaymentIntent
          const res = await uni.request({
            url: '你的后端API地址/create-payment-intent',
            method: 'POST',
            data: { amount: 1000, currency: 'usd' }, // 金额(单位:分)和货币
          });
    
          const clientSecret = res.data.client_secret;
    
          // 2. 确认支付
          const { error } = await this.stripe.confirmCardPayment(clientSecret, {
            payment_method: {
              card: elements.getElement('card'), // 需在前端添加卡片输入元素
            },
          });
    
          if (error) {
            uni.showToast({ title: '支付失败', icon: 'none' });
          } else {
            uni.showToast({ title: '支付成功' });
          }
        },
      },
    };
    </script>
    

步骤 3:后端实现(示例使用 Node.js)

后端需创建 PaymentIntent 并返回 client_secret

const stripe = require('stripe')('你的_Secret_Key');

app.post('/create-payment-intent', async (req, res) => {
  const { amount, currency } = req.body;
  const paymentIntent = await stripe.paymentIntents.create({
    amount,
    currency,
  });
  res.send({ client_secret: paymentIntent.client_secret });
});

其他平台说明

  • App 平台(iOS/Android):需使用原生插件(如 stripe-react-native),通过 UniApp 原生插件机制集成。
  • 小程序平台:Stripe 不支持直接集成,可考虑通过 WebView 加载 H5 支付页或使用第三方支付(如支付宝、微信支付)。

注意事项

  • 安全:切勿在前端暴露 Secret Key,所有敏感操作(如创建 PaymentIntent)应在后端完成。
  • 测试:使用 Stripe 测试模式和测试卡号验证流程。
  • 跨平台兼容:代码需根据平台条件编译(如 #ifdef H5 处理 H5 特定逻辑)。

通过以上步骤,即可在 UniApp 中实现 Stripe 支付集成。如有复杂需求(如订阅、支付宝集成),参考 Stripe 文档

回到顶部