ruby

Is Integrating Stripe with Ruby on Rails Really This Simple?

Stripe Meets Ruby on Rails: A Simplified Symphony of Seamless Payment Integration

Is Integrating Stripe with Ruby on Rails Really This Simple?

When it comes to integrating Stripe into a Ruby on Rails application, it’s way simpler than you might think. Here’s an easy-to-follow guide to get you set up without any hassle.

First up, you need to get your hands on those API keys, which means creating a developer profile on Stripe. Once you’re logged into Stripe, head over to the Account Settings and locate the API keys section. You’ll find your test and live secret keys, along with your publishable keys there. Using test keys during development is super important so you don’t accidentally charge any real customers.

Now, it’s time to add the Stripe gem into your Rails application. Open up your Gemfile and punch in the following line:

gem 'stripe'

After that, just run the bundle command in your terminal to get the gem installed. Easy peasy.

Next, you gotta set up your API keys in the application. Create a secrets.yml file in your config directory and add your test and live keys:

development:
  stripe_secret_key: 'sk_test_your_test_secret_key'
  stripe_publishable_key: 'pk_test_your_test_publishable_key'

production:
  stripe_secret_key: 'sk_live_your_live_secret_key'
  stripe_publishable_key: 'pk_live_your_live_publishable_key'

Make sure to replace the placeholder keys with your actual keys from the Stripe dashboard.

You’ll also need to get your Stripe configuration sorted. Create a new file in config/initializers named stripe.rb and toss in:

Stripe.api_key = Rails.application.secrets.stripe_secret_key

This is just setting your Stripe API key based on your environment.

To accept payments, you need a payment form. You can use Stripe’s pre-built Checkout form, or you can go for a custom form if that better fits your needs. Here’s an example of a very simple custom form:

<%= form_tag charges_path, id: "payment-form" do %>
  <script src="https://js.stripe.com/v3/"></script>
  <div id="card-element"></div>
  <button id="submit">Submit Payment</button>
  <div id="card-errors" role="alert"></div>

  <script>
    const stripe = Stripe('<%= Rails.application.secrets.stripe_publishable_key %>');
    const elements = stripe.elements();

    const card = elements.create('card', { hidePostalCode: true });
    card.mount('#card-element');

    const form = document.getElementById('payment-form');
    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      const { token, error } = await stripe.createToken(card);
      if (error) {
        document.getElementById('card-errors').textContent = error.message;
      } else {
        const hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'stripeToken');
        hiddenInput.setAttribute('value', token.id);
        form.appendChild(hiddenInput);
        form.submit();
      }
    });
  </script>
<% end %>

This form uses Stripe.js to securely handle the credit card info and create a token that you can send to your server.

On the server side, to process the payment, you’ll need a controller action to handle that Stripe token. Here’s a starter example:

class ChargesController < ApplicationController
  def create
    @amount = 500 # Amount in cents

    customer = Stripe::Customer.create(
      email: params[:stripeEmail],
      source: params[:stripeToken]
    )

    charge = Stripe::Charge.create(
      customer: customer.id,
      amount: @amount,
      description: 'Rails Stripe customer',
      currency: 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end
end

This bit of code creates a new customer and charges their card with the given token.

Stripe also makes it super easy to handle recurring subscriptions. For this, you’ll need to create a subscription model and manage creation and updates. Here’s a basic example to get you rolling:

class SubscriptionsController < ApplicationController
  def create
    @plan = 'monthly' 

    customer = Stripe::Customer.create(
      email: params[:stripeEmail],
      source: params[:stripeToken]
    )

    subscription = Stripe::Subscription.create(
      customer: customer.id,
      items: [{ plan: @plan }],
      expand: ['latest_invoice.payment_intent']
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_subscription_path
  end
end

This creates a new customer and subscribes them to a specific plan.

Now, let’s talk about handling webhooks. Webhooks let Stripe notify you about events happening in your Stripe account. To handle them, you need an endpoint in your app. An example endpoint set up to receive and verify webhooks looks like this:

class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def create
    payload = request.body.read
    sig_header = request.env['HTTP_STRIPE_SIGNATURE']
    endpoint_secret = Rails.application.secrets.stripe_webhook_secret

    begin
      event = Stripe::Webhook.construct_event(payload, sig_header, endpoint_secret)
      # Handle the event
      case event.type
      when 'invoice.payment_succeeded'
        # Handle successful payment
      when 'invoice.payment_failed'
        # Handle failed payment
      end
    rescue JSON::ParserError => e
      # Invalid payload
      render json: { error: 'Invalid payload' }, status: 400
    rescue Stripe::SignatureVerificationError => e
      # Invalid signature
      render json: { error: 'Invalid signature' }, status: 400
    end

    render json: { received: true }
  end
end

This code snippet verifies the webhook signature and processes the event accordingly.

To wrap it all up, integrating Stripe into a Ruby on Rails application is an amazing way to streamline transactions and subscriptions. By following these steps, you can securely handle payments, manage subscriptions, and get notifications directly with webhooks. Always use test keys during development and keep your secret keys safe—don’t let them get into source control. With Stripe, you’ve got the tools to build a rock-solid payment solution that scales with your business needs.

Keywords: Stripe API keys, integrate Stripe Rails, Stripe gem Rails, Stripe payment form, Rails Stripe setup, Stripe subscription Rails, Stripe webhooks Rails, Ruby on Rails Stripe, Stripe payments integration, Stripe configuration Rails



Similar Posts
Blog Image
Mastering Rust's Variance: Boost Your Generic Code's Power and Flexibility

Rust's type system includes variance, a feature that determines subtyping relationships in complex structures. It comes in three forms: covariance, contravariance, and invariance. Variance affects how generic types behave, particularly with lifetimes and references. Understanding variance is crucial for creating flexible, safe abstractions in Rust, especially when designing APIs and plugin systems.

Blog Image
7 Essential Event-Driven Architecture Patterns Every Rails Developer Should Master for Scalable Applications

Build resilient Rails event-driven architectures with 7 proven patterns. Master publishers, event buses, idempotency, and fault tolerance. Scale smoothly while maintaining data integrity. Learn practical implementation today.

Blog Image
7 Proven Rails API Versioning Strategies That Prevent Breaking Changes

Learn 7 proven Rails API versioning techniques to evolve features without breaking client integrations. Path-based, header, and content negotiation methods included.

Blog Image
Building Robust Ruby Data Pipelines: 7 Essential Patterns for Modern Applications

Master Ruby data pipeline patterns for scalable ETL systems. Learn stage-based, event-driven, and stream processing with practical code examples. Build reliable data workflows today.

Blog Image
7 Proven Patterns for Building Bulletproof Background Job Systems in Ruby on Rails

Build bulletproof Ruby on Rails background jobs with 7 proven patterns: idempotent design, exponential backoff, dependency chains & more. Learn from real production failures.

Blog Image
5 Advanced Full-Text Search Techniques for Ruby on Rails: Boost Performance and User Experience

Discover 5 advanced Ruby on Rails techniques for efficient full-text search. Learn to leverage PostgreSQL, Elasticsearch, faceted search, fuzzy matching, and autocomplete. Boost your app's UX now!