You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用原生JavaScript调用Stripe API添加客户数据的疑问

使用原生JS调用Stripe API添加客户的完整指南

首先得划个关键红线:绝对不能在前端JavaScript里直接使用Stripe的Secret API密钥!前端代码是完全暴露给用户的,密钥一旦泄露,别人就能用你的账号做任何操作(比如扣款、删数据),后果不堪设想。正确的流程是:前端收集客户数据,通过Ajax发给你自己的后端服务,再由后端用Secret Key调用Stripe的API创建客户。

下面逐个解答你的疑问:

a) API密钥应放置在何处?

  • 你的Stripe Secret Key(开头是sk_)必须放在后端代码里(比如Node.js、Python、PHP等服务端环境),绝对不能出现在前端JS或HTML中。
  • 前端可以使用Stripe的Publishable Key(开头是pk_),但这个密钥只能用于安全的前端操作(比如创建支付元素),不能用来创建客户——创建客户的接口必须用Secret Key调用。

b) 如何发送数据,具体应在脚本的哪个位置输入数据?

分前端和后端两部分拆解:

前端(原生JS):收集数据并发送到你的后端

假设你有一个表单收集客户信息,用fetch API发送POST请求:

// 绑定表单提交事件
document.getElementById('customer-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  // 从表单字段中提取客户数据
  const customerData = {
    email: document.getElementById('email').value,
    name: document.getElementById('name').value,
    phone: document.getElementById('phone').value
  };
  
  try {
    // 发送请求到自己的后端接口
    const response = await fetch('/api/create-stripe-customer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(customerData)
    });
    
    const result = await response.json();
    if (result.success) {
      console.log('客户创建成功!Stripe客户ID:', result.customerId);
      // 这里可以做后续操作,比如跳转到支付页面
    } else {
      console.error('创建客户失败:', result.error);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
});

后端(以Node.js/Express为例):接收数据并调用Stripe API

首先安装Stripe的Node.js SDK:npm install stripe

const express = require('express');
const stripe = require('stripe')('你的Stripe Secret Key'); // 这里安全放置Secret Key
const app = express();

app.use(express.json());

// 处理前端的创建客户请求
app.post('/api/create-stripe-customer', async (req, res) => {
  try {
    // 从前端请求体中获取客户数据
    const { email, name, phone } = req.body;
    
    // 调用Stripe API创建客户
    const customer = await stripe.customers.create({
      email: email,
      name: name,
      phone: phone
      // 还可以按需添加address、description等参数
    });
    
    res.json({
      success: true,
      customerId: customer.id
    });
  } catch (error) {
    res.json({
      success: false,
      error: error.message
    });
  }
});

app.listen(3000, () => console.log('后端服务运行在3000端口'));

简单来说:前端负责收集用户输入的数据,通过Ajax把数据传给你的后端;后端拿到数据后,用Secret Key调用Stripe官方SDK创建客户,最后把结果返回给前端。

c) 必须使用哪些参数?

严格来说,Stripe的创建客户API(POST /v1/customers没有强制必填参数——你甚至可以不传任何参数就能创建一个空客户。但在实际业务中,至少需要传以下参数保证客户的可识别性:

  • email:客户邮箱地址,这是最核心的参数,方便你在Stripe后台识别客户,也是后续发送收据、付款通知的必要信息。
  • 其他常用可选参数:
    • name:客户姓名
    • phone:客户电话
    • address:客户地址(对象格式,包含line1citypostal_code等字段)
    • description:客户描述(比如关联你自己系统的用户ID、订单号,方便后续对账)

如果需要关联支付方式,还可以在创建客户时传入payment_method参数,但这一步通常放在后续支付流程中,不是创建客户的必须项。


内容的提问来源于stack exchange,提问作者David Johnson

火山引擎 最新活动