Django电商网站集成Stripe问题:自定义Token无法被接受
Hey there! Let’s walk through some practical fixes for the Stripe token problem you’re facing—since tok_visa works but your own generated tokens don’t, there are a few key areas to check:
1. Verify Your Stripe Environment & Keys
First, double-check that you’re using test mode keys consistently across your frontend and backend:
- Your frontend should initialize Stripe with a
pk_test_publishable key - Your Django
settings.pyshould have aSTRIPE_SECRET_KEYstarting withsk_test_
If you mix test and production keys, tok_visa (a test-only token) will work, but any tokens generated with a production publishable key will fail in test mode, and vice versa.
2. Debug Frontend Token Generation
In your jQuery code, make sure you’re catching errors when creating the token—Stripe will tell you exactly why a token isn’t valid before it even reaches your backend. Here’s an example with error handling:
// Initialize Stripe with your test publishable key Stripe('pk_test_yourPublishableKey').createToken('card', { number: $('#card-number').val(), exp_month: $('#exp-month').val(), exp_year: $('#exp-year').val(), cvc: $('#cvc').val() }, function(status, response) { if (response.error) { // Log the error to your browser console console.error('Token generation failed:', response.error.message); // Show this error to your user too! alert('Oops: ' + response.error.message); } else { // Send the valid token to your Django backend var token = response.id; $('#payment-form').append('<input type="hidden" name="stripeToken" value="' + token + '">'); $('#payment-form').submit(); } });
If you see errors here (like "Invalid card number" or "Expired card"), that’s the root of your problem—your frontend is generating invalid tokens because of incorrect card details.
3. Check Backend Token Handling in views.py
Make sure your Django view is properly using the Stripe Python library and capturing errors to see why charges fail. Here’s a robust example:
import stripe from django.conf import settings from django.shortcuts import render, redirect stripe.api_key = settings.STRIPE_SECRET_KEY def process_payment(request): if request.method == 'POST': stripe_token = request.POST.get('stripeToken') amount = 5000 # $50.00 (Stripe uses cents as units) try: # Create a charge with the token charge = stripe.Charge.create( amount=amount, currency='usd', source=stripe_token, description='Order #123' ) # If successful, handle order confirmation return render(request, 'payment_success.html') except stripe.error.CardError as e: # Card was declined (insufficient funds, expired, etc.) error_message = e.json_body['error']['message'] return render(request, 'payment_failed.html', {'error': error_message}) except stripe.error.InvalidRequestError as e: # Invalid parameters (e.g., invalid token, wrong amount) error_message = 'Invalid payment details: ' + str(e) return render(request, 'payment_failed.html', {'error': error_message}) except stripe.error.StripeError as e: # Generic Stripe API error error_message = 'Payment service error. Please try again later.' return render(request, 'payment_failed.html', {'error': error_message}) return render(request, 'payment_form.html')
By catching these exceptions, you’ll get specific error messages that tell you if the token is invalid, if your secret key is wrong, or if there’s another issue with the charge.
4. Validate Manual Token Input
If manually entering your generated token doesn’t work:
- Confirm the token was generated in test mode (tokens start with
tok_test_for test mode) - Ensure you’re pasting the full token string (no extra spaces or typos)
- Check that the token hasn’t already been used—Stripe tokens are one-time use, even in test mode!
5. Use Stripe Dashboard Logs
Head to your Stripe Test Dashboard and go to Events & Logs—here you’ll find a detailed record of every API request your site makes. Look for failed charge events, and click into them to see the exact error code and message from Stripe. This is often the fastest way to pinpoint issues like invalid keys or token errors.
内容的提问来源于stack exchange,提问作者ranjith

