top of page

Online Payment Gateway Integration With ASP.NET Core

A step-by-step guide on how to implement payment gateways in ASP.NET Core apps using popular payment services: Braintree


A payment gateway is an e-commerce software that authorizes payment for online merchants. it’s consumer-facing interfaces used to collect payments. the online stores, the payment gateways are the checkout portals used to enter the credit card information.


I expect you to have knowledge of object-oriented programming concepts in C#. I assume you know .NET Core concepts especially the MVC pattern also.

To code along with me, you will have to install the .NET Core 2.2, as well as Visual Studio. You can also use another IDE instead of a visual studio. You can find a link to the Github repository end of this article.

Braintree Implementation

1.Set up Braintree account 2.Set up the development environment 3.Generate client tokens 4.Card payments

1. Set up Braintree account

First of all, in our browser, we have to go to for signup. for that Braintree will create us a sandbox account. so we can test the API and before to decide our push our app to production. after successfully all things, we have to login into

After the first login, when you scroll down, you will find 3 keys(MarchantId, PublicKey, PrivateKey). we actually will use these keys on configuring the .net core application.

2. Set up the development environment

    "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;
    "Logging": {
        "LogLevel": {
            "Default": "Warning"    
    "BraintreeGateway": {
        "Environment": "SANDBOX",
        "MerchantId": "br9XXXXXXXxyfj",
        "PublicKey": "8jXXXXXXXXXXXXfzp",
        "PrivateKey": "91XXXXXXXXXXXXXX23"  },
        "AllowedHosts": "*"

So above all the key value what we need. we found these key values from our sandbox.braintreegatway account.

Let’s get started by opening the existing application, first of all, we are going to add the Braintree package. Go to NuGet to install Braintree .NET Client Library which is supported by both .NET Framework, .NET Core.

Now we will be going to create a Braintree service. we have to create an interface file in our created services folder.

public interface IBraintreeService    
    IBraintreeGateway CreateGateway();
    IBraintreeGateway GetGateway();    

Above code, don’t forget to make public this interface. Now we are going to implement members of this interface.

Now we have to create a class file in our created services folder.

namespace Hellow_payment.Services
    public class BraintreeService : IBraintreeService    
        private readonly IConfiguration _config;
        public BraintreeService(IConfiguration config)        
            _config = config;        
        public IBraintreeGateway CreateGateway()        
            var newGateway = new BraintreeGateway()            
                Environment = Braintree.Environment.SANDBOX,
                MerchantId = _config.GetValue<string>
                PublicKey = _config.GetValue<string>
                PrivateKey = _config.GetValue<string>
            return newGateway;        
        public IBraintreeGateway GetGateway()        
            return CreateGateway();        

Above code, To access our key’s from appsettings.json file for that we used the IConfiguration interface.

We have to configure this new service in our startup.cs file. then we are able to inject this service into our controllers.

services.AddTransient<IBraintreeService, BraintreeService>();

3. Generates client tokens and Card payments

A client token contains all the necessary information to set up the client SDKs.So before that, I think it’s better to create some model for storing data.

public class Book    
    [Key]public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Description { get; set; }
    public string Thumbnail { get; set; }
    public string Price { get; set; }    

public class BookPurchaseVM : Book    
    public string Nonce { get; set; }    

Now we are generating a token and storing some data in our Controller.

public class HomeController : Controller    
    private readonly IBraintreeService _braintreeService;
    public HomeController(IBraintreeService braintreeService)        
    public IActionResult Index()        
        var gateway = _braintreeService.GetGateway();
        var clientToken = gateway.ClientToken.Generate();  
        //Genarate a token
        var data = new BookPurchaseVM            
            Id = 2,
            Description = "Hellow man",
            Author = "Me",
            Thumbnail = "This is thumbnail",
            Title = "This is title",
            Price = "230",Nonce=""            
    return View(data);        

Now Index view:-

@model Hellow_payment.Models.BookPurchaseVM

    ViewData["Title"] = "Purchase";

<div class="wrapper">    
    <div class="checkout container">        
        <form id="payment-form" method="post" asp-
                    controller="Home" asp-action="Create">            
            @Html.HiddenFor(n => n.Id)            
            <div class="card">                
                <div class="card-body">                    
                    <h5 class="card-title" name="Title" asp-
                    <p class="card-text">@Model.Description</p>                    
                    <p class="card-text"><small class="text-
                       muted">Author: @Model.Author</small></p>                    
                    <p class="card-text"><small class="text-
                        muted">Price: @Model.Price</small></p>                
                <img style="width: 90%" class="card-img-bottom" 
                   src="@Model.Thumbnail" alt="Card image cap">            
                <div class="bt-drop-in-wrapper">                    
                    <div id="bt-dropin"></div>                
            @Html.HiddenFor(n => n.Nonce, new { @id = "nonce" })            
            <hr />            
            <button class="btn btn-success" type="submit">
            <span>Confirm payment - $@Model.Price</span>

<script src=""></script>
    var client_token = "@ViewBag.ClientToken";    
    var form = document.querySelector('#payment-form');    
        authorization: client_token,        
        container: '#bt-dropin'    
    }, function (createErr, instance) {        
        form.addEventListener('submit', function (event) {            
            instance.requestPaymentMethod(function (err, payload) {                
                if (err) {                    
                document.querySelector('#nonce').value = payload.nonce;                

Above view code, we have actually used some Braintree reference in the script. also, we have first created a reference to the client token and Nonce property is the secured one-time user reference to payment information.

Now after when we run our application, then we will find this output:-

So if we input the test card number and expiration date, nothing will happen because we did not create Create method yet in our Controller.

Now we will be going to Create method in our controller.

public IActionResult Create(BookPurchaseVM model)        
    var gateway = _braintreeService.GetGateway();
    var request = new TransactionRequest            
        Amount = Convert.ToDecimal("250"),
        PaymentMethodNonce = model.Nonce,
        Options = new TransactionOptionsRequest                
            SubmitForSettlement = true                
    Result<Transaction> result = 
    if (result.IsSuccess())            
        return View("Success");            
        return View("Failure");            

After that, you have to create a view for success. I assumed that you will create it easily.

So now if you run the application and will click Confirm Payment. you will see your success view.

And now if you want to see your transaction, then you have to go to and log in after login, go to the transaction menu and scroll down. then select This Month and after scrolling a little bit, you will find a search button. click here. after that, you will find like below image.

I actually do many transactions for testing purposes and that’s why above image you have seen 5 transactions. but you will see 1 transaction if you are the first time in this.

Source: Medium - Delushaan Delu

The Tech Platform


2 kommentarer

16. feb.

Integrating an online payment gateway with ASP.NET Core is a critical step for businesses looking to streamline their e-commerce operations. With the rise of online shopping, providing customers with secure and efficient payment options is essential for driving sales and enhancing user experience. As the all-in-one payment platform for SMEs, HitPay offers a seamless solution for integrating online payments into ASP.NET Core applications. With HitPay's unified payment processing system, businesses can access a full range of domestic and cross-border payment methods on a single platform, ensuring maximum convenience for both merchants and customers. Whether it's accepting payments for online purchases or processing transactions in-person, HitPay's secure and cost-effective payment solutions are designed to meet the needs of businesses across Southeast…


bottom of page