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

使用stripe-node遇报错,如何在Node.js中实现stripe.createToken()?

Got it, let's break this down clearly—you're hitting that error because Stripe explicitly blocks sending raw card numbers to their API from backend servers for critical security reasons. Enabling "unsafe payments" is really not worth the hassle (it exposes you to heavy PCI compliance obligations), so let's walk through the proper, secure approach using frontend token generation paired with your Node.js backend:

Secure Stripe Payment Flow (Frontend Token + Backend Processing)

Stripe's entire design is built to keep sensitive card data away from your servers. The only safe way is to collect card info via Stripe Elements in the frontend, generate a token there, then pass that token to your Node.js backend to process the payment.

1. Frontend: Generate a Payment Token with Stripe Elements

First, set up Stripe Elements to collect card details safely—this handles all PCI-compliant input handling for you:

<!-- Load Stripe.js -->
<script src="https://js.stripe.com/v3/"></script>

<!-- Card input container -->
<div id="card-element" style="border: 1px solid #ccc; padding: 10px; border-radius: 4px;"></div>
<button id="pay-button" style="margin-top: 10px; padding: 8px 16px;">Complete Payment</button>

<script>
// Initialize Stripe with your publishable API key
const stripe = Stripe('pk_test_YOUR_PUBLISHABLE_KEY');
const elements = stripe.elements();

// Create and mount the card input element
const cardElement = elements.create('card');
cardElement.mount('#card-element');

// Handle payment submission
document.getElementById('pay-button').addEventListener('click', async () => {
  try {
    // Generate a token from the card element
    const { token, error } = await stripe.createToken(cardElement);
    
    if (error) {
      // Show error to the user (e.g., invalid card number)
      alert(`Error: ${error.message}`);
    } else {
      // Send the token to your Node.js backend
      const response = await fetch('/api/process-payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ tokenId: token.id })
      });
      
      const result = await response.json();
      if (result.success) {
        alert('Payment successful!');
      } else {
        alert(`Payment failed: ${result.error}`);
      }
    }
  } catch (err) {
    console.error('Payment error:', err);
    alert('Something went wrong with your payment.');
  }
});
</script>

2. Node.js Backend: Process Payment with the Token

Use the stripe-node package to receive the token from the frontend and create a payment (we'll use the modern PaymentIntent API, which is recommended over the older Charge API):

const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
const express = require('express');
const app = express();

// Parse JSON requests
app.use(express.json());

// Endpoint to handle payment processing
app.post('/api/process-payment', async (req, res) => {
  try {
    const { tokenId } = req.body;
    
    // Create a PaymentIntent to confirm the payment
    const paymentIntent = await stripe.paymentIntents.create({
      amount: 2500, // Amount in cents (e.g., $25.00)
      currency: 'usd',
      payment_method: tokenId,
      confirm: true, // Auto-confirm the payment
      automatic_payment_methods: {
        enabled: true,
      },
    });

    res.json({ success: true, paymentId: paymentIntent.id });
  } catch (error) {
    res.json({ success: false, error: error.message });
  }
});

// Start server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Why You Should Avoid "Unsafe Payments"

Sending credit card numbers directly to the Stripe API is generally unsafe. We suggest you use test tokens that map to the test card you are using

Stripe's warning isn't just a suggestion—directly handling raw card numbers means you have to comply with strict PCI DSS requirements, which involves costly audits, secure data storage, and encryption. Using Elements and tokens lets Stripe handle all that heavy lifting, so you never touch sensitive card data.

Testing Without Frontend Code

If you just want to test your backend logic quickly, use Stripe's pre-built test tokens instead of real card numbers. For example:

  • tok_visa = Visa test card
  • tok_mastercard = Mastercard test card
  • tok_amex = American Express test card

Use them directly in your backend code like this:

const paymentIntent = await stripe.paymentIntents.create({
  amount: 2500,
  currency: 'usd',
  payment_method: 'tok_visa', // Test token
  confirm: true,
});

内容的提问来源于stack exchange,提问作者Dilakshan Sooriyanathan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:12:38