Rails应用集成Stripe支付网关:已安装Gem,求开发流程指引
Hey there! Since you’ve already added the stripe gem and run bundle install, let’s break down the rest of the integration step by step—no confusion allowed. Here’s how to get your app processing payments smoothly:
First off, you’ll need your Stripe API keys. Head over to your Stripe dashboard, go to Developers > API Keys, and grab your publishable key (for the frontend) and secret key (for the backend—keep this one private!).
- Add these keys to your Rails credentials. Run this command in your terminal:
Then paste in this YAML block (replace the placeholder keys with your actual ones):rails credentials:editstripe: publishable_key: pk_test_your_actual_key_here secret_key: sk_test_your_actual_key_here - Create a Stripe initializer file at
config/initializers/stripe.rbto load your keys:Rails.configuration.stripe = { publishable_key: Rails.application.credentials.dig(:stripe, :publishable_key), secret_key: Rails.application.credentials.dig(:stripe, :secret_key) } Stripe.api_key = Rails.configuration.stripe[:secret_key]
Never handle raw card data directly—Stripe’s Elements do the heavy lifting to keep payments secure. Here’s how to set up the payment form:
- Add Stripe’s JavaScript library to your layout or payment view:
<script src="https://js.stripe.com/v3/"></script> - Create a payment form (e.g.,
app/views/payments/new.html.erb) that uses Stripe Elements:<%= form_tag charges_path, id: 'payment-form' do %> <div class="form-group"> <label>Credit or Debit Card</label> <div id="card-element"> <!-- Stripe's card input will appear here --> </div> <div id="card-errors" class="text-danger" role="alert"></div> </div> <%= submit_tag 'Complete Payment', id: 'submit-payment', class: 'btn btn-primary' %> <% end %> <script> // Initialize Stripe with your publishable key const stripe = Stripe('<%= Rails.configuration.stripe[:publishable_key] %>'); const elements = stripe.elements(); // Create and mount the card element const cardElement = elements.create('card'); cardElement.mount('#card-element'); // Handle form submission const form = document.getElementById('payment-form'); form.addEventListener('submit', async (e) => { e.preventDefault(); // Create a token from the card details const { token, error } = await stripe.createToken(cardElement); if (error) { // Show error message to the user const errorElement = document.getElementById('card-errors'); errorElement.textContent = error.message; } else { // Add the token to the form and submit it to your backend const hiddenTokenInput = document.createElement('input'); hiddenTokenInput.type = 'hidden'; hiddenTokenInput.name = 'stripeToken'; hiddenTokenInput.value = token.id; form.appendChild(hiddenTokenInput); form.submit(); } }); </script>
Now you need a controller to handle the payment using the token from the frontend:
- Generate a Charges controller:
rails generate controller Charges create - Update
app/controllers/charges_controller.rbto process the charge:class ChargesController < ApplicationController def create stripe_token = params[:stripeToken] # Amount is in cents (e.g., $49.99 = 4999 cents) charge_amount = 4999 begin # Create the charge with Stripe charge = Stripe::Charge.create( amount: charge_amount, currency: 'usd', source: stripe_token, description: 'Customer payment for your service' ) # Handle successful payment (e.g., save to DB, show success message) flash[:success] = 'Payment processed successfully! 🎉' redirect_to root_path rescue Stripe::CardError => e # Handle card-specific errors (insufficient funds, expired card, etc.) flash[:error] = e.message redirect_to new_payment_path rescue Stripe::StripeError => e # Catch other Stripe-related errors flash[:error] = 'Oops, something went wrong with your payment. Please try again.' redirect_to new_payment_path end end - Update your
config/routes.rbto add the necessary routes:resources :charges, only: [:create] get '/payments/new', to: 'payments#new' # Route for your payment form page
Stripe makes testing easy with dummy card numbers. Use this test card to simulate a successful payment:
- Card number:
4242 4242 4242 4242 - Expiration date: Any future date (e.g.,
12/30) - CVC: Any 3-digit number (e.g.,
123)
Run your Rails server, navigate to /payments/new, fill in the test card details, and submit. You’ll see the successful charge show up in your Stripe dashboard’s test mode.
- Webhooks: Set up Stripe webhooks to handle events like failed payments, refunds, or subscription updates. In development, use
stripe listen --forward-to localhost:3000/stripe/webhookto test webhook events. - Subscriptions: If you need recurring payments, use Stripe’s Subscription API instead of one-time charges—it handles billing cycles, retries, and invoices automatically.
- Logging: Add logging for Stripe events to debug issues easily in production.
内容的提问来源于stack exchange,提问作者Pooja M

