Stripe Payment Gateway Integration with Ruby on Rails

Customize this app
23
import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import stripe
import uvicorn

# Constants
STRIPE_SECRET_KEY = os.environ['STRIPE_SECRET_KEY']
YOUR_DOMAIN = os.environ['YOUR_DOMAIN']

# Configure Stripe API key
stripe.api_key = STRIPE_SECRET_KEY

# FastAPI app initialization
app = FastAPI()

# CORS configuration
origins = ["*"]
app.add_middleware(
   CORSMiddleware,
   allow_origins=origins,
   allow_credentials=True,
Get full code

Stripe Payment Gateway Integration with Ruby on Rails

Created: | Last Updated:

Introduction to the Stripe Payment Gateway Integration with Ruby on Rails Template

This template is designed to help you integrate a custom Stripe payment gateway into your Ruby on Rails application. It provides a backend service for Stripe checkout, which is compatible with any price point established through the Stripe API. The template includes a FastAPI backend written in Python to handle the creation of Stripe checkout sessions and a frontend JavaScript snippet to be included in your Rails application for initiating the checkout process.

Getting Started with the Template

To begin using this template, click "Start with this Template" on the Lazy platform. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy, paste, or delete any code.

Initial Setup: Adding Environment Secrets

Before testing the application, you need to set up the following environment secrets in the Environment Secrets tab within the Lazy Builder:

1. `STRIPE_SECRET_KEY`: This is your Stripe secret API key, which you can find in your Stripe dashboard under Developers > API keys. 2. `YOUR_DOMAIN`: This is the domain where your Ruby on Rails application is hosted. It will be used to construct the return URL after a successful payment.

Make sure to obtain these values from your Stripe account and your hosting setup before proceeding.

Test: Pressing the Test Button

Once you have added the necessary environment secrets, press the "Test" button on the Lazy platform. This will deploy the app and launch the Lazy CLI. If the code requires any user input, you will be prompted to provide it through the Lazy CLI.

Using the App

After pressing the "Test" button, Lazy will provide you with a dedicated server link to use the API. If you're using FastAPI, Lazy will also provide a docs link, which you can use to interact with the app and understand the available endpoints.

Integrating the App into Your Ruby on Rails Application

To integrate the backend service into your Ruby on Rails application, follow these steps:

1. Insert the following script tags in the `` section of your `application.html.erb` file:

```html

\<%\= javascript_include_tag "checkout" %> ```

2. Create a `checkout.js` file in your `app/javascript` folder and include the following JavaScript code, replacing placeholders with your actual publishable API key from Stripe, your price ID, and the server URL provided by Lazy:

```javascript // Initialize stripe with your publishable stripe api key const stripe \= Stripe('YOUR_PUBLISHABLE_STRIPE_API_KEY');

// Create a checkout session async function checkout() { const response \= await fetch("'LAZY SERVER URL'/create-checkout-session", { method: 'POST', headers: { 'Content-Type': 'application/json', // Add any other headers your Rails app needs for CSRF, etc. }, body: JSON.stringify({ price_id: 'YOUR_PRICE_ID', months: 1, }), })

const { sessionId } \= await response.json();

stripe.redirectToCheckout({ sessionId: sessionId }).then(function (result) { if (result.error) { console.error(result.error.message); } }); }

document.addEventListener('DOMContentLoaded', function () { var checkoutButton \= document.getElementById('stripe-checkout-button'); checkoutButton.addEventListener('click', checkout); }) ```

3. Add a button with the ID `stripe-checkout-button` in your Rails view file where you want customers to initiate the checkout process:

```html Checkout ```

By following these steps, you will have successfully integrated the Stripe payment gateway into your Ruby on Rails application using the Lazy template. Customers can now click the "Checkout" button to initiate the payment process.

Technologies

Ruby Ruby
Stripe Stripe