In the modern digital economy, it is very important for any business to have a secure and stable payment gateway. One such prominent payment gateway in India is Cashfree, which provides instant and hassle-free payment options for websites and mobile applications.

In this blog post, we will guide you through integrating Cashfree Payment Gateway into your web application using their Payment Gateway (PG) API. Whether you are a developer or a business owner trying to figure out the process, this guide will ensure a smooth start.

First of all, we need to two things.
  • appId
  • secretKey
You can generate above key from given link i.e Cashfree

Please note that the appId and secretKey are configured accordingly for use in both production and test environments.

For testing purpose need to create a HTML page for button and other JS code which will be used for process.

HTML
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Cashfree Checkout Integration</title>
  </head>
  <body>
      <div class="row">
          <p>Click below to open payment page</p>
          <button id="renderBtn">Pay Now</button>
      </div>

      <script type="text/javascript" src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>
      <script type="text/javascript">
          const cashfree = Cashfree({
              mode: "sandbox" // Use "sandbox" for test environment. Use "production" for Live
          });

          document.getElementById("renderBtn").addEventListener("click", async () => {
              try {
                  console.log("Creating payment session...");

                  const response = await fetch('/CashfreeController/CreateSession', {
                      method: 'POST',
                      headers: {
                          'Content-Type': 'application/json',
                      }
                  });

                  if (!response.ok) {
                      throw new Error(`HTTP error! status: ${response.status}`);
                  }

                  const data = await response.json();
                  console.log("Response data:", data);

                  if (data.sessionId) {
                      console.log("Received session ID:", data.sessionId);

                      const checkoutOptions = {
                          paymentSessionId: data.sessionId,
                          redirectTarget: "_self"
                      };

                      console.log("Calling checkout with options:", checkoutOptions);

                      cashfree.checkout(checkoutOptions)
                          .then(result => {
                              console.log("Checkout initiated successfully", result);
                          })
                          .catch(error => {
                              console.error("Checkout error:", error);
                              alert("Payment failed: " + error.message);
                          });

                  } else {
                      console.error("No session ID received:", data);
                      alert("Error: " + (data.error || "Unable to get session ID"));
                  }
              } catch (error) {
                  console.error("Error in payment process:", error);
                  alert("Error: " + error.message);
              }
          });
      </script>
  </body>
  </html>


Now Write back end code for generating session Id , order_id, callback (When payment successful or failed) 
C# 
[HttpPost]
public async Task<JsonResult> CreateSession()
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var orderId = "order_" + Guid.NewGuid().ToString("N").Substring(0, 12);

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://sandbox.cashfree.com");
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("x-client-id", appId);
            client.DefaultRequestHeaders.Add("x-client-secret", secretKey);
            client.DefaultRequestHeaders.Add("x-api-version", "2022-09-01");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Build return URL
            string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
            string callbackPath = Url.Action("Callback", "CashfreeController");

            string returnUrl = baseUrl + callbackPath +
                                "?order_id={order_id}" +
                                "&payment_status={payment_status}" +
                                "&tx_status={tx_status}" +
                                "&tx_msg={tx_msg}" +
                                "&reference_id={reference_id}";

            var orderData = new
            {
                order_id = orderId,
                order_amount = 1.0,
                order_currency = "INR",
                customer_details = new
                {
                    customer_id = "cust_001",
                    customer_email = "test@example.com",
                    customer_phone = "9999999999"
                },
                order_meta = new
                {
                    return_url = returnUrl
                }
            };

            var jsonData = JsonConvert.SerializeObject(orderData);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            var response = await client.PostAsync("/pg/orders", content);
            var responseContent = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                var jsonObj = JObject.Parse(responseContent);
                var paymentSessionId = jsonObj["payment_session_id"] != null ? jsonObj["payment_session_id"].Value<string>() : null;

                if (!string.IsNullOrEmpty(paymentSessionId))
                {
                    return Json(new
                    {
                        success = true,
                        sessionId = paymentSessionId,
                        orderId = orderId
                    }, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(new
            {
                success = false,
                error = "Failed to create session"
            }, JsonRequestBehavior.AllowGet);
        }
    }
    catch (Exception ex)
    {
        return Json(new
        {
            success = false,
            error = ex.Message
        }, JsonRequestBehavior.AllowGet);
    }
}

You can receive call back data after successful payment or failed and show it on page as your requirement or save to DataBase.
 // Step 2: Callback Method
        public ActionResult Callback()
        {
            try
            {
                // Get parameters from QueryString
                string order_id = Request.QueryString["order_id"];
                 var a= GetPaymentDetails(order_id);
                string payment_status = Request.QueryString["payment_status"];
                string tx_status = Request.QueryString["tx_status"];
                string tx_msg = Request.QueryString["tx_msg"];
                string reference_id = Request.QueryString["reference_id"];

                string finalStatus = "PENDING";
                string finalMessage = "Payment status not received";

                if (!string.IsNullOrEmpty(payment_status))
                {
                    finalStatus = payment_status.ToUpper();
                    finalMessage = tx_msg ?? GetStatusMessage(finalStatus);
                }
                else if (!string.IsNullOrEmpty(tx_status))
                {
                    finalStatus = tx_status.ToUpper();
                    finalMessage = tx_msg ?? GetStatusMessage(finalStatus);
                }

                ViewBag.OrderId = order_id ?? "N/A";
                ViewBag.PaymentStatus = finalStatus;
                ViewBag.Message = finalMessage;
                ViewBag.ReferenceId = reference_id;
                ViewBag.TransactionTime = DateTime.Now.ToString("dd MMM yyyy hh:mm:ss tt");
                ViewBag.IsSuccess = finalStatus == "SUCCESS";
                ViewBag.IsFailed = finalStatus == "FAILED" || finalStatus == "CANCELLED";
                ViewBag.IsPending = finalStatus == "PENDING";
                ViewBag.RawQueryString = Request.Url.Query;

                return View();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Callback Error: " + ex.Message);
                ViewBag.Error = ex.Message;
                ViewBag.PaymentStatus = "ERROR";
                return View();
            }
        }

🙏 Thank You for Reading!

Thank you for taking the time to read this blog!

If you have any questions or need help with something, feel free to drop a message in the comments or contact section. I’ll get back to you as soon as possible.

Happy Learning! 😊

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions