How integrate Stripe Payments in FARM (Fastapi + React(Next JS)) stack

patwarinetra

May 11th, 2024 01:12 AM

I am building a saas application using farm stack , now i want to integrate stripe payment to it. and I even want to add a custom stripe form to it..

If anyone can help it will be grateful

bobbyiliev

May 11th, 2024 07:44 AM

Hey!

I think that for FrastAPI you could just use the Stripe package directly:

https://pypi.org/project/stripe/

You can add Stripe to your FastAPI project by installing the Stripe Python library.

pip install stripe

Then in your FastAPI app, configure Stripe with your secret key (obtain this from your Stripe Dashboard).

import stripe
# Set your secret key: remember to change this to your live secret key in production
stripe.api_key = 'sk_test_yourkey'

After that define an endpoint in FastAPI to process payments. This will involve creating a charge or a payment intent depending on your Stripe integration choice.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class PaymentData(BaseModel):
    amount: int
    currency: str
    description: str
    source: str  # token created using Stripe Checkout or Elements

@app.post("/create-charge/")
def create_charge(payment_data: PaymentData):
    try:
        # Create a charge
        charge = stripe.Charge.create(
            amount=payment_data.amount,
            currency=payment_data.currency,
            description=payment_data.description,
            source=payment_data.source
        )
        return {"status": "success", "charge": charge}
    except stripe.error.StripeError as e:
        return HTTPException(status_code=400, detail=str(e))

On the frontend side, you can add Stripe.js to your Next.js project to manage client-side Stripe functionality.

npm install @stripe/stripe-js

Then use the Stripe Elements to build a custom form for card details.

import { loadStripe } from '@stripe/stripe-js';
import { Elements, CardElement } from '@stripe/react-stripe-js';

const stripePromise = loadStripe('pk_test_yourPublishableKey');

const CheckoutForm = () => {
  const handleSubmit = async (event) => {
    event.preventDefault();
    // Implement Stripe payment logic here
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <button type="submit">Pay</button>
    </form>
  );
};

const StripeContainer = () => (
  <Elements stripe={stripePromise}>
    <CheckoutForm />
  </Elements>
);

export default StripeContainer;

Finally connect your React form to the FastAPI endpoint you created for charges.

const handleSubmit = async (event) => {
  event.preventDefault();
  const { stripe, elements } = stripe;
  const cardElement = elements.getElement(CardElement);

  const {token} = await stripe.createToken(cardElement);
  const response = await fetch('/create-charge/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ 
      source: token.id, 
      amount: 1000,  // Example amount
      currency: 'usd',
      description: 'Example charge'
    }),
  });

  const paymentResult = await response.json();
  console.log(paymentResult);
};

Here is a quick fastapi demo project that you can use as a reference:

https://github.com/rsusik/stripe-fastapi-demo