Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Integrating Cashfree Payment Gateway in ASP.NET Core: A Comprehensive Guide

Integrating Cashfree Payment Gateway in ASP.NET Core: A Comprehensive Guide

Date- Apr 10,2026 94
cashfree payment gateway

Overview

The Cashfree Payment Gateway is a robust solution designed to facilitate online transactions for businesses in India and beyond. By providing a comprehensive suite of payment processing capabilities, Cashfree helps merchants accept payments through various methods including credit cards, debit cards, net banking, and UPI. The need for such a service arises from the growing demand for secure, reliable, and efficient payment solutions in the digital economy, where businesses seek to offer their customers a seamless checkout experience.

In real-world scenarios, companies ranging from e-commerce platforms to service providers leverage the Cashfree Payment Gateway to streamline their payment processes. For instance, an online retailer can integrate Cashfree to allow customers to pay for their purchases with ease, thereby reducing cart abandonment rates and increasing conversion rates. Furthermore, Cashfree’s support for features like refunds and recurring payments makes it a versatile choice for various business models.

Prerequisites

  • ASP.NET Core SDK: Ensure you have the latest version of the .NET SDK installed on your machine.
  • Visual Studio: A suitable integrated development environment for building ASP.NET Core applications.
  • Cashfree Account: Sign up for a Cashfree merchant account to obtain your API keys.
  • Basic C# Knowledge: Familiarity with C# programming language and ASP.NET Core framework.
  • Postman: A tool for testing API endpoints, useful for simulating payment requests.

Setting Up Cashfree SDK

Before integrating the Cashfree Payment Gateway, it’s essential to set up the Cashfree SDK in your ASP.NET Core application. This SDK simplifies the process of making API calls to Cashfree by providing convenient methods and handling authentication.

To install the Cashfree SDK, you can use NuGet Package Manager. Open your terminal or package manager console in Visual Studio and run the following command:

Install-Package Cashfree.SDK

This command downloads and installs the Cashfree SDK package into your project, making it accessible for use. After installation, you will need to configure the SDK with your merchant credentials.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ICashfreeClient>(new CashfreeClient(new CashfreeClientOptions
    {
        AppId = "YOUR_APP_ID",
        SecretKey = "YOUR_SECRET_KEY"
    }));
}

The above code snippet demonstrates how to register the Cashfree client in the ASP.NET Core dependency injection container. Replace YOUR_APP_ID and YOUR_SECRET_KEY with the credentials obtained from your Cashfree merchant account. This setup allows you to inject the Cashfree client into your controllers or services for making payment requests.

Why Use Dependency Injection?

Dependency Injection (DI) promotes loose coupling in your application architecture, making it easier to manage and test your code. By registering the Cashfree client as a singleton, it ensures that a single instance is reused throughout the application lifecycle, optimizing resource usage.

Creating Payment Requests

The next step in integrating the Cashfree Payment Gateway is to create payment requests. This is done by constructing a payment order with necessary details such as the amount, currency, and customer information.

public async Task<IActionResult> CreatePayment(decimal amount, string orderId, string customerEmail)
{
    var paymentOrder = new PaymentOrder
    {
        OrderId = orderId,
        OrderAmount = amount,
        CustomerEmail = customerEmail,
        // Additional parameters as needed
    };

    var response = await _cashfreeClient.CreatePaymentAsync(paymentOrder);

    if (response.IsSuccess)
    {
        return Redirect(response.PaymentUrl);
    }
    else
    {
        return View("Error", response.ErrorMessage);
    }
}

This method constructs a PaymentOrder object containing essential details for the payment, including OrderId, OrderAmount, and CustomerEmail. It then calls the CreatePaymentAsync method of the Cashfree client to initiate the payment process. Depending on the success of the request, it redirects the user to the payment URL or displays an error message.

Handling Response

Once the payment is processed, Cashfree will redirect the user back to your application with the payment status. It is crucial to handle this response appropriately to update your order status and provide feedback to the user.

public async Task<IActionResult> PaymentCallback(string orderId, string paymentStatus)
{
    // Verify the payment status
    var isValid = await _cashfreeClient.VerifyPaymentAsync(orderId);

    if (isValid)
    {
        // Update order status to successful
    }
    else
    {
        // Handle payment failure
    }

    return View("PaymentResult");
}

This method accepts parameters from the callback URL, verifies the payment status, and updates the order accordingly. The VerifyPaymentAsync method checks the validity of the payment, ensuring that the transaction was completed successfully before proceeding with order fulfillment.

Security Considerations

When handling payment integrations, security is paramount. Using HTTPS for all transactions is a non-negotiable requirement, as it encrypts data in transit, protecting sensitive customer information. Additionally, it is vital to validate all incoming data from Cashfree to prevent malicious attacks.

[HttpPost]
public async Task<IActionResult> PaymentCallback([FromForm] PaymentCallbackModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest();
    }

    // Proceed with verification and order processing
}

In this example, the PaymentCallback method checks the validity of the incoming model before proceeding. This ensures that only valid requests are processed, thereby enhancing the security of your application.

Using Webhooks for Asynchronous Notifications

Cashfree supports webhooks to notify your application of payment status changes. Implementing webhooks allows your application to handle payment notifications asynchronously, improving reliability.

[HttpPost]
[Route("api/webhook/cashfree")]
public async Task<IActionResult> CashfreeWebhook([FromBody] WebhookNotification notification)
{
    // Validate the notification

    // Update order status based on notification type

    return Ok();
}

This method listens for webhook notifications from Cashfree, validates the incoming data, and updates the order status based on the notification type (e.g., payment completed, refunded). It is essential to ensure that your webhook endpoint is secured and properly validated.

Edge Cases & Gotchas

When integrating payment gateways, there are several edge cases and potential pitfalls that developers should be aware of. One common issue is handling payment failures due to network interruptions or validation errors.

if (response.Status == PaymentStatus.Failed)
{
    // Log the error
    _logger.LogError($"Payment failed for Order ID: {orderId}, Error: {response.ErrorMessage}");
    // Notify the user
}

In the code above, logging the error and notifying the user helps maintain transparency and improves the customer experience. Additionally, ensure that your application can handle expired sessions or stale payment links gracefully.

Performance & Best Practices

Performance is critical in payment processing. Optimize your application's response times by minimizing external API calls where possible. Cache frequently accessed data, such as payment configurations or transaction statuses, to reduce latency.

services.AddMemoryCache();

public class PaymentService
{
    private readonly IMemoryCache _cache;

    public PaymentService(IMemoryCache cache)
    {
        _cache = cache;
    }

    public async Task<PaymentDetails> GetPaymentDetailsAsync(string orderId)
    {
        if (!_cache.TryGetValue(orderId, out PaymentDetails paymentDetails))
        {
            paymentDetails = await _dbContext.Payments.FindAsync(orderId);
            _cache.Set(orderId, paymentDetails, TimeSpan.FromMinutes(10));
        }
        return paymentDetails;
    }
}

This code snippet demonstrates how to use in-memory caching to store payment details. By caching the results for a specified duration, you reduce database load and improve the overall performance of your application.

Testing Payment Integrations

Thorough testing is essential to ensure reliability in payment processing. Utilize unit tests to verify the behavior of your payment services and integration tests to simulate real-world scenarios.

[Fact]
public async Task CreatePayment_Should_Return_Redirect_When_Success()
{
    // Arrange
    var service = new PaymentService(mockCashfreeClient.Object);

    // Act
    var result = await service.CreatePayment(100, "TEST_ORDER_1", "customer@example.com");

    // Assert
    var redirectResult = Assert.IsType<RedirectResult>(result);
    Assert.Equal("expectedPaymentUrl", redirectResult.Url);
}

The test above checks that the CreatePayment method returns a redirect result when the payment is successful. This ensures that your integration behaves as expected under various conditions.

Real-World Scenario: E-Commerce Payment Integration

To tie all these concepts together, let’s consider a mini-project that integrates Cashfree into an e-commerce application. The project will consist of a simplified checkout process where users can add items to their cart and proceed to payment.

public class CheckoutController : Controller
{
    private readonly ICashfreeClient _cashfreeClient;

    public CheckoutController(ICashfreeClient cashfreeClient)
    {
        _cashfreeClient = cashfreeClient;
    }

    public async Task<IActionResult> Checkout(Cart cart)
    {
        decimal totalAmount = cart.Items.Sum(item => item.Price);
        string orderId = Guid.NewGuid().ToString();
        var result = await CreatePayment(totalAmount, orderId, User.Email);
        return result;
    }
}

This CheckoutController class demonstrates a simple checkout process where the total amount from the user's cart is calculated, an order ID is generated, and a payment request is created. The controller manages the entire flow, from calculating the total to initiating the payment.

Enhancing User Experience

Consider implementing features such as payment history, order tracking, and customer notifications to enhance user experience. Providing users with a dashboard to view their transactions can significantly improve engagement and satisfaction.

Conclusion

  • Understanding the Cashfree Payment Gateway and its integration into ASP.NET Core applications is crucial for modern e-commerce solutions.
  • Setting up the Cashfree SDK and creating payment requests can be done efficiently with dependency injection.
  • Security practices, including HTTPS and data validation, are essential to protect user information.
  • Performance optimization through caching and thorough testing ensures a reliable payment processing experience.
  • Real-world application of these concepts in an e-commerce scenario demonstrates the practical benefits of Cashfree integration.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Integrating CCAvenue Payment Gateway in ASP.NET Core Applications
Apr 24, 2026
Stripe Payment Gateway Integration in ASP.NET Core: Comprehensive Guide to Checkout, Webhooks, and Refunds
Apr 22, 2026
Integrating Razorpay Payment Gateway in ASP.NET Core with Webhook Verification
Apr 19, 2026
Integrating PayU Payment Gateway in ASP.NET Core: A Comprehensive Guide
Apr 23, 2026
Previous in ASP.NET Core
How to Fix Accessibility Issues in ASP.NET Core Applications
Next in ASP.NET Core
Integrating Google Calendar API in ASP.NET Core: A Comprehensive …
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 367 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views
  • 8
    How to get fcm server key 4,849 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26191 views
  • Exception Handling Asp.Net Core 20938 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20391 views
  • How to implement Paypal in Asp.Net Core 19753 views
  • Task Scheduler in Asp.Net core 17705 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor