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

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:

1. Configure Stripe Credentials

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:
    rails credentials:edit
    
    Then paste in this YAML block (replace the placeholder keys with your actual ones):
    stripe:
      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.rb to 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]
    
2. Build the Frontend (Safe Card Collection)

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>
    
3. Set Up the Backend (Process the Payment)

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.rb to 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.rb to add the necessary routes:
    resources :charges, only: [:create]
    get '/payments/new', to: 'payments#new' # Route for your payment form page
    
4. Test the Integration

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.

5. Pro Tips for Production
  • 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/webhook to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:16:44