How to Implement Stripe Payment Gateway into Wordpress

By
 import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
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

This template integrates a custom Stripe payment gateway in WordPress. It includes both a backend and a frontend. The backend service is set up using FastAPI and is compatible with any price point established through the Stripe API. The backend service creates a Stripe checkout session and retrieves the status of a checkout session. It also allows all CORS and logs sent requests and checkout session statuses. The price ID is fetched during the request from the user. After adding the Stripe API key and directing the backend service to the price ID, the backend service can be activated by clicking the test button. The frontend code can be integrated into a WordPress page to create a custom payment gateway page with a payment button in WordPress. This method can be used to set up various types of payment pages in WordPress, including one-time payments and subscriptions. The required environment secrets for this app are STRIPE_SECRET_KEY and YOUR_DOMAIN.

Introduction to the Stripe Payment Gateway Integration Template for WordPress

This template is designed to help you integrate a custom Stripe payment gateway into your WordPress site. It includes a backend service built with FastAPI, which handles the creation of Stripe checkout sessions and the retrieval of their statuses. The frontend code can be embedded into your WordPress payment page to allow users to make payments directly on your site. This solution is suitable for various payment setups, including one-time payments and subscriptions.

Getting Started with the Template

To begin using this template, click "Start with this Template" on the Lazy platform. This will set up the template in your Lazy Builder interface, ready for customization and deployment.

Initial Setup: Adding Environment Secrets

Before testing and deploying your app, you need to set up the required environment secrets. These are: 1. `STRIPE_SECRET_KEY`: Your Stripe secret API key, which you can find in your Stripe dashboard under Developers > API keys. 2. `YOUR_DOMAIN`: The domain where your WordPress site is hosted (e.g., https://www.yourwebsite.com). To add these environment secrets in the Lazy Builder: - Navigate to the Environment Secrets tab within the Lazy Builder. - Click on "Add Secret" and enter `STRIPE_SECRET_KEY` as the name and your Stripe secret API key as the value. - Add another secret with the name `YOUR_DOMAIN` and your website's domain as the value.

Test: Pressing the Test Button

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

Using the App

After testing, Lazy will provide you with a dedicated server link to use the API. This link is crucial for integrating the backend service with your WordPress site.

Integrating the App into WordPress

To integrate the backend service into your WordPress site, follow these steps: 1. Insert the provided frontend code into your WordPress payment page. You should place this script just before the `` tag in the HTML of your page. 2. Replace `"PUBLISHABLE STRIPE API KEY"` with your actual publishable API key from Stripe. 3. Replace `"LAZY SERVER LINK"` with the endpoint URL of your published app that you received after pressing the test button. 4. Replace `"PRICE_ID"` with the actual price ID you want to use for the transaction. You can find this in your Stripe dashboard under Products. Here is the frontend code snippet you'll need to add to your WordPress page:
<script src="https://js.stripe.com/v3/"></script>
<script>
    const stripe = Stripe("PUBLISHABLE STRIPE API KEY");

    initialize();

    function getUTMParameters() {
        const params = new URLSearchParams(window.location.search);
        return {
            utm_source: params.get('utm_source') || '',
            utm_medium: params.get('utm_medium') || '',
            utm_campaign: params.get('utm_campaign') || '',
            utm_term: params.get('utm_term') || '',
            utm_content: params.get('utm_content') || ''
        };
    }

    async function initialize() {
        const months = 1;
        const utmParams = getUTMParameters();

        const response = await fetch("LAZY SERVER LINK/create-checkout-session", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                months,
                price: 'PRICE_ID',
                ...utmParams
            })
        });

        const { clientSecret } = await response.json();

        const checkout = await stripe.initEmbeddedCheckout({
            clientSecret,
        });

        checkout.mount('#checkout');
    }
</script>
By following these steps, you will have successfully integrated a custom Stripe payment gateway into your WordPress site using the Lazy template. Your users will now be able to make secure payments directly on your site.
Category
Last published
April 7, 2024

More templates like this

Backend Server

This skeleton is streamlined for creating backend services using FastAPI. It's an excellent choice for building microservices or APIs with minimal frontend requirements.

Fast API
Python

Search Email with GMail API

This is a FastAPI-based application that uses Google’s Gmail API to fetch and display emails based on user-defined search queries. It provides a /search_emails endpoint for email searches and a /oauth2callback endpoint for OAuth2 callbacks. The app requires the environment variables CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI for OAuth2 authentication. These credentials pertain to your Google API and must be set correctly for the application to function as expected.

Fast API
Python
Gmail

Moderate Comments on Facebook Page

An app that moderates comments on your page feed using Facebook API and webhooks. This app uses the FastAPI to create a webhook endpoint for moderating posts on your page. A facebook access token for the page will be needed to make the API call. The permission scopes you will need for the access token are `pages_read_engagement` and `pages_manage_posts permissions` as an admin of the page you are posting to. The app moderates comments on Facebook ads/posts by removing and flagging hateful speech.

Fast API
Python
Home
/
How to Implement Stripe Payment Gateway into Wordpress