Stripe Payment Gateway Integration with Ruby on Rails

By
 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,

About this template

To integrate a custom Stripe payment gateway in Ruby on Rails, you need both a backend and a frontend. This example template enables you to quickly set up the backend service for Stripe checkout. It is compatible with any price point you have established through the Stripe API. After adding the API key and directing the backend service to the price ID, you can activate the backend service by clicking the test button. Then, by integrating the Stripe frontend code into a Rails view file according to the given instructions, you instantly create a custom payment page in Ruby on Rails. This method can be used to set up various types of payment pages in Ruby on Rails, including one-time payments and recurring subscriptions.

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 ``` 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.
Category
Technology
Last published
April 7, 2024

More templates like this

Stripe API Testing

This application utilizes Flask for the backend and JavaScript with Stripe API for the frontend. It allows users to test various Stripe functionalities such as adding a card to a customer, creating a charge, and retrieving customer details. The backend interacts with the Stripe API using the stripe library, while the frontend provides a simple form for users to input their Stripe API secret and an optional customer ID. Upon submitting the form, the frontend sends a POST request to the backend, which then executes the specified tests and returns the results to be displayed on the page. Made by BaranDev[https://github.com/BaranDev]

Flask
Stripe

Connect Payout with Stripe API

This app uses the Stripe API to create payouts for Connect Stripe Accouts and allows users to modify the payout schedule. It includes a Flask web service with an endpoint for this purpose. The backend makes API calls to create a transfer of funds and update the payout schedule using the Stripe API and the submitted form data.

Flask
Stripe
Python

Create Product using Stripe API

This app uses the Stripe API to create a product with it's price. It includes a Flask web service with an endpoint for this purpose. The backend makes API calls to create a product and its price object using the Stripe API and the submitted form data.

Flask
Stripe
Python
Home
/
Stripe Payment Gateway Integration with Ruby on Rails