[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);
}
}