Ruby on Rails集成Stripe报错:未设置有效的发布密钥
Hey there, let's troubleshoot that frustrating publishable key error you're hitting with Stripe Checkout in your Rails app. Even though the tutorial doesn't explicitly call Stripe.setPublishableKey(), the root issue almost always boils down to your publishable key not being loaded correctly in the frontend, or a missing configuration step the tutorial assumes you've covered. Here's how to fix it:
1. Double-Check Your .env File Setup
- Make sure your
.envfile (in the Rails root directory) has the correct publishable key entry:STRIPE_PUBLISHABLE_KEY=pk_test_your_actual_test_key_here - Verify you've added the
dotenv-railsgem to your Gemfile (it's required to load environment variables from.env):
Rungem 'dotenv-rails', groups: [:development, :test]bundle installif you haven't already. - Ensure
.envisn't accidentally excluded by.gitignore(though it should be ignored for security, it needs to exist locally for your app to read the keys).
2. Confirm the Key is Passed to the Frontend
Newer Stripe Checkout implementations use the data-key attribute in the Stripe button script instead of Stripe.setPublishableKey(). Make sure your view file (e.g., app/views/charges/new.html.erb) correctly injects the environment variable:
<%= form_tag charges_path do %> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="<%= ENV['STRIPE_PUBLISHABLE_KEY'] %>" data-amount="500" data-name="Your App Name" data-description="Sample Product" data-currency="usd"> </script> <% end %>
- Quick test: Load the page in your browser, right-click > "View Page Source", and check if the
data-keyvalue matches yourpk_testkey. If it's empty or showsnil, your app isn't loading the environment variable properly.
3. Restart Your Rails Server
Environment variables from .env are only loaded when your Rails server starts. If you added or modified the key after starting the server, you need to restart it for changes to take effect.
4. Verify Your Stripe Initializer (Backend Configuration)
While frontend keys are handled via the view, your backend needs the secret key for API calls. Make sure you have a config/initializers/stripe.rb file with:
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
This ensures your server can communicate with Stripe's API, but the frontend publishable key issue is separate—this just prevents additional backend errors.
5. Don't Mix Up Keys!
Double-check that you're using a publishable key (starts with pk_test) in the frontend, not a secret key (starts with sk_test). Secret keys should never be exposed in the frontend, and using one here will throw an invalid key error.
If you follow these steps, the error should disappear. The most common culprits are an unloaded environment variable (fixed by restarting the server) or a typo in your .env file.
内容的提问来源于stack exchange,提问作者Malus_khanot

