I need help integrating Flutterwave into my React and express Node Application

18 Views Asked by At

I have a react application and an express node js application and i am trying to implement Flutterwave into it so user can triggered a function in the frontend and send a http request to the backend and if the payment was initiated, user proceed to make the payment but, it's my first time using Flutterwave, so i dont actually see in their documentation on how to implement it in a full-stack app. The below code is what i have been trying with:

        import React, { useEffect, useState } from "react";
    import axios from "axios";
    import { useFlutterwave, closePaymentModal } from "flutterwave-react-v3";

const ProductDisplay = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handlePurchase = async () => {
    setLoading(true);
    try {
      const cartItems = [
        {
          productId: "65fbde3849818eb7f1818db9",
          quantity: 2,
          name: "Product 1 Name",
          description: "Product 1 Description",
          price: 50,
          category: "Category 1",
          brand: "Brand 1",
          images: [
            "https://buffer.com/library/content/images/size/w1200/2023/10/free-images.jpg",
          ],
        },
        {
          productId: "65fbfe7f91b83e84b97e1113",
          quantity: 1,
          name: "Product 2 Name",
          description: "Product 2 Description",
          price: 120,
          category: "Category 2",
          brand: "Brand 2",
          images: [
            "https://images.unsplash.com/photo-1575936123452-b67c3203c357?q=80&w=1000&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mnx8aW1hZ2V8ZW58MHx8MHx8fDA%3D",
          ],
        },
      ];

      const response = await axios.post(
        "http://localhost:5000/api/create-checkout-session",
        {
          cartItems: cartItems,
          email: "[email protected]",
          userId: "65fbfce047301309ca6f5264",
        }
      );


      console.log(response.data);
      setPaymentCallback(response.data.callbackUrl);

    } catch (error) {
      setError("Error initiating payment: " + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="d-flex flex-column">
      {loading ? (
        <p>Loading...</p>
      ) : (
        <button onClick={handlePurchase}>Purchase Product</button>
      )}
      <small className="text-danger bg-light mt-5 text-center">{error}</small>
    </div>
  );
};

export default ProductDisplay;

import Flutterwave from 'flutterwave-node-v3'; const flw = new Flutterwave(process.env.FLW_PUBLIC_KEY, process.env.FLW_SECRET_KEY);

export const buyProduct = async (req, res) => {
  const { cartItems, email, userId } = req.body;
  try {
    let totalAmount = 0;
    cartItems.forEach(item => {
      totalAmount += item.quantity * item.price;
    });

    

    // Prepare payment payload
    const paymentPayload = {
      "tx_ref": "unique-transaction-ref", // Generate unique transaction reference
      "amount": totalAmount,
      "currency": "NGN",
      // "payment_options": "card,mobilemoney,ussd",
      "customer": {
        "email": email,
        "phonenumber": "070********",
        "name": "Adeolu Amole"
      },
      "customizations": {
        "title": "Product Purchase",
        "description": "Payment for items in cart",
        "logo": "https://buffer.com/library/content/images/size/w1200/2023/10/free-images.jpg"
      }
    };

    // Initiate payment with Flutterwave
    const paymentResponse = await flw.Transaction.fetch(paymentPayload);
    console.log(paymentResponse);

    // Return the callback URL to frontend
    res.json({ callbackUrl: paymentResponse.data.meta.authorization.redirect });
  } catch (error) {
    console.error("Error processing payment:", error);
    res.status(500).json({ error: "Error processing payment" });
  }
};
0

There are 0 best solutions below