You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Razorpay API保存客户卡片,支持调取及支付、钱包充值

在Web应用中集成Razorpay保存并调取客户卡片信息的实现方法

Razorpay 提供了Customers API和Tokens API专门用于实现客户卡片的存储与复用,完全满足你无需通过结账页面即可管理卡片的需求,具体实现步骤如下:

一、核心前提:创建客户记录

卡片信息必须关联到具体的Razorpay客户对象,所以第一步是通过后端调用Customers API创建客户:

// Node.js 后端示例
const Razorpay = require('razorpay');
const razorpay = new Razorpay({
  key_id: 'YOUR_KEY_ID',
  key_secret: 'YOUR_KEY_SECRET'
});

async function createCustomer(customerDetails) {
  const customer = await razorpay.customers.create({
    name: customerDetails.name,
    email: customerDetails.email,
    contact: customerDetails.phone
  });
  return customer.id; // 保存该customer_id到你的数据库,后续关联卡片用
}

二、安全收集并保存卡片信息

绝对不能在前端直接处理卡片明文(违反PCI合规),必须使用Razorpay Elements组件安全收集卡片信息,然后生成卡片token,再通过后端关联到客户:

1. 前端集成Razorpay Elements

加载Razorpay Elements脚本,渲染卡片收集组件:

<!-- 加载Elements脚本 -->
<script src="https://checkout.razorpay.com/v1/razorpay.js"></script>

<!-- 卡片输入容器 -->
<div id="card-element"></div>
<button id="save-card-btn">保存卡片</button>

<script>
  const options = {
    key: 'YOUR_KEY_ID', // 仅使用公钥
    name: 'Your Business Name',
    description: 'Save Payment Card',
    image: '/your-logo.png',
  };

  const razorpay = new Razorpay(options);
  const cardElement = razorpay.elements.create('card');
  cardElement.mount('#card-element');

  // 点击保存按钮生成卡片token
  document.getElementById('save-card-btn').addEventListener('click', async () => {
    try {
      const token = await razorpay.createToken(cardElement);
      // 将token.id和customer_id传给后端保存
      await fetch('/api/save-card', {
        method: 'POST',
        body: JSON.stringify({
          customerId: 'YOUR_CUSTOMER_ID', // 从你的数据库获取
          tokenId: token.id
        }),
        headers: { 'Content-Type': 'application/json' }
      });
      alert('卡片保存成功');
    } catch (err) {
      console.error('卡片保存失败:', err);
    }
  });
</script>

2. 后端关联卡片token到客户

通过Tokens API将生成的token绑定到指定客户:

async function saveCardToCustomer(customerId, tokenId) {
  await razorpay.customers.addToken(customerId, tokenId);
}

三、调取已存卡片列表

通过后端调用Customers API的fetch tokens接口,获取该客户下所有有效卡片信息:

async function getCustomerCards(customerId) {
  const tokens = await razorpay.customers.fetchTokens(customerId, {
    type: 'card' // 只筛选卡片类型的token
  });
  // 处理返回的tokens数据,提取卡片后4位、品牌等信息返回给前端展示
  return tokens.items.map(token => ({
    id: token.id,
    last4: token.card.last4,
    brand: token.card.network,
    expiry: `${token.card.expiry_month}/${token.card.expiry_year}`
  }));
}

前端拿到这些信息后,就可以渲染卡片选择列表供用户选择。

四、使用已存卡片完成支付/充值

创建订单后,直接使用已保存的卡片token发起支付,无需再次输入卡片信息:

1. 后端创建订单

async function createOrder(amount, currency = 'INR') {
  const order = await razorpay.orders.create({
    amount: amount * 100, // Razorpay使用最小货币单位(如印度卢比为派萨)
    currency: currency,
    payment_capture: 1 // 自动捕获支付
  });
  return order.id;
}

2. 前端发起支付(使用已存卡片token)

async function payWithSavedCard(orderId, tokenId) {
  const options = {
    key: 'YOUR_KEY_ID',
    order_id: orderId,
    token: tokenId, // 传入已保存的卡片token
    name: 'Your Business Name',
    description: 'Wallet Recharge',
    handler: function(response) {
      // 支付成功后的回调,通知后端验证支付状态
      fetch('/api/verify-payment', {
        method: 'POST',
        body: JSON.stringify({
          orderId: response.razorpay_order_id,
          paymentId: response.razorpay_payment_id,
          signature: response.razorpay_signature
        }),
        headers: { 'Content-Type': 'application/json' }
      });
    }
  };

  const razorpay = new Razorpay(options);
  razorpay.open();
}

关键注意事项

  • PCI合规:所有卡片信息收集必须通过Razorpay Elements或Checkout,禁止自行收集卡号、CVV等敏感信息。
  • Token有效期:卡片token长期有效,除非卡片过期、被注销或用户主动删除。
  • 权限控制:所有API调用必须通过后端发起,绝对不能在前端暴露API密钥。

内容的提问来源于stack exchange,提问作者Sunil Yerra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:45:18