RAZORPAY FRONTEND CODE

 RAZORPAY FRONTEND CODE

BUYNOW.JS

import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import axios from "axios";
import { Button } from "reactstrap";
import { getCurrentUser, getToken, BASE_URL } from "../Components/Auth";
import Base from "../Components/Base";

const BuyNowPage = () => {
  const { moduleId } = useParams();
  const navigate = useNavigate();
  const [userId, setUserId] = useState("");
  const [currentUser, setCurrentUser] = useState(null);
  const [phoneNumber, setPhoneNumber] = useState("");
  const [loading, setLoading] = useState(false);
  const fixedAmount = 25;

  useEffect(() => {
    const user = getCurrentUser();
    if (user) {
      setUserId(user.userId);
      setCurrentUser(user);
    }
  }, []);

  const handleBuyNow = async () => {
    if (!moduleId || !userId || !phoneNumber || phoneNumber.length !== 10) {
        alert("Please provide a valid 10-digit phone number.");
        return;
    }

    try {
        setLoading(true);
        const token = getToken();

        // Debug logs to check userId and moduleId
        console.log("Debugging IDs before creating order:");
        console.log("User ID:", userId);
        console.log("Module ID:", moduleId);

        const response = await axios.post(
            `${BASE_URL}buy-now/create-order`,
            {
                user: { id: userId },  // Fixed the structure here!
                module: { id: moduleId },  // Fixed the structure here!
                amount: fixedAmount,
                phno: phoneNumber
            },
            { headers: { Authorization: `Bearer ${token}` } }
        );

        console.log("Order created successfully:", response.data);

        const { razorpayOrderId, amount: orderAmount } = response.data;
        if (!razorpayOrderId) throw new Error("Order creation failed!");

        const options = {

            key: "SECRETE KEY ID", //here update your secrete key id

            amount: orderAmount * 100,
            currency: "INR",
            name: "LMS BY SALMAN SIR",
            description: "Purchase access for module",
            order_id: razorpayOrderId,
            handler: async (paymentResponse) => {
                try {
                    await axios.post(
                        `${BASE_URL}buy-now/handle-payment-callback`,
                        paymentResponse,
                        { headers: { Authorization: `Bearer ${token}` } }
                    );
                    alert("Payment successful!");
                    navigate(`/user/module/${moduleId}/topics`);
                } catch (err) {
                    console.error("Payment callback error:", err);
                    alert("Payment verification failed. Please contact support.");
                }
            },
            prefill: {
                name: currentUser?.name || "Your Name",
                email: currentUser?.email || "your-email@example.com",
                contact: phoneNumber,
            },
            theme: { color: "#3399cc" },
        };

        const rzp = new window.Razorpay(options);
        rzp.on("payment.failed", (response) => {
            console.error("Payment failed:", response.error);
            alert("Payment failed: " + response.error.description);
        });
        rzp.open();
    } catch (error) {
        console.error("Purchase error:", error);
        alert("Purchase failed: " + (error.response?.data || error.message));
    } finally {
        setLoading(false);
    }
};

  return (
    <Base>
      <div style={{ maxWidth: "600px", margin: "auto", padding: "30px", backgroundColor: "#f9f9f9", borderRadius: "8px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", fontFamily: "Arial, sans-serif" }}>
        <h1 style={{ textAlign: "center", fontSize: "24px", fontWeight: "600", marginBottom: "20px", color: "#333" }}>Buy Now</h1>
        <div style={{ marginBottom: "15px" }}>
          <label style={{ fontWeight: "bold", color: "#555", marginBottom: "5px", display: "block" }}>Module ID:</label>
          <input type="text" value={moduleId} readOnly style={{ width: "100%", padding: "10px", fontSize: "14px", border: "1px solid #ccc", borderRadius: "4px", marginBottom: "10px" }} />
        </div>
        <div style={{ marginBottom: "15px" }}>
          <label style={{ fontWeight: "bold", color: "#555", marginBottom: "5px", display: "block" }}>User ID:</label>
          <input type="text" value={userId} readOnly style={{ width: "100%", padding: "10px", fontSize: "14px", border: "1px solid #ccc", borderRadius: "4px", marginBottom: "10px" }} />
        </div>
        <div style={{ marginBottom: "15px" }}>
          <label style={{ fontWeight: "bold", color: "#555", marginBottom: "5px", display: "block" }}>Amount:</label>
          <input type="text" value={fixedAmount} readOnly style={{ width: "100%", padding: "10px", fontSize: "14px", border: "1px solid #ccc", borderRadius: "4px", marginBottom: "10px" }} />
        </div>
        <div style={{ marginBottom: "15px" }}>
          <label style={{ fontWeight: "bold", color: "#555", marginBottom: "5px", display: "block" }}>Phone Number:</label>
          <input
            type="text"
            value={phoneNumber}
            onChange={(e) => {
              const input = e.target.value;
              if (/^\d*$/.test(input)) setPhoneNumber(input);
            }}
            placeholder="Enter your phone number"
            style={{ width: "100%", padding: "10px", fontSize: "14px", border: "1px solid #ccc", borderRadius: "4px", marginBottom: "10px" }}
          />
        </div>
        <button
          style={{ width: "100%", padding: "12px", fontSize: "16px", backgroundColor: "#3399cc", color: "white", border: "none", borderRadius: "4px", cursor: "pointer", transition: "background-color 0.3s", ...(loading ? { backgroundColor: "#ccc", cursor: "not-allowed" } : {}) }}
          onClick={handleBuyNow}
          disabled={loading}
        >
          {loading ? "Processing..." : "Buy Now"}
        </button>
        <Button color="secondary" style={{ borderRadius: "50px", padding: "10px 25px", fontSize: "1rem", fontWeight: "bold", marginTop: "20px" }} onClick={() => navigate(-1)}>
          Back
        </Button>
      </div>
    </Base>
  );
};

export default BuyNowPage;

Comments

Popular posts from this blog

JWT Authentication with Spring Boot

RAZORPAY CODE BACKEND