Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript 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. How to implement Paypal in Asp.Net Core 8.0

How to implement Paypal in Asp.Net Core 8.0

Date- Nov 24,2023

Updated Feb 2026

12911

Free Download Pay & Download
Aspnet Core 80 Paypal

Hello guys and welcome to Code2Night, we often want to integrate payment gateways in our Asp.Net Core 8.0 applications. Some of the most popular payment gateways are PayUMoney, Paypal, stripe, and Razorpay. We have already covered PayUMoney and Stripe in ASP.NET Core 8.0 in our blogs. In this article, we will see how to implement PayPal in Asp.Net Core 8.0.

Paypal is a payment gateway that provides secure payments across the world. It helps you accept international payments at some price per transaction. There is no initial setup fee for implementing PayPal.So for integrating paypal in Asp.Net Core 8.0, we have to follow these steps :

First of all, take one Asp.net Core 8.0 mvc application and we will install the PayPal Nuget package which is shown in the image below

Paypal in ASP.NET Core

Install these packages from Nuget package
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

Newtonsoft.Json

PayPal

System.Configuration.ConfigurationManager

How to implement Paypal in AspNet Core 80
After you have done installing the PayPal Nuget package we will have to take one new controller where we will add the PayPal integration code. You have to add these namespaces on the controller

using PayPal.Api;

So, now we have to add these methods in our controller, this method will help us initialize payment and redirect to the payment page

  public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private IHttpContextAccessor httpContextAccessor;
        IConfiguration _configuration;
        public HomeController(ILogger<HomeController> logger, IHttpContextAccessor context, IConfiguration iconfiguration)
        {
            _logger = logger;
            httpContextAccessor = context;
            _configuration = iconfiguration;
        }

        public IActionResult Index()
        {
            return View();
        }

        public ActionResult PaymentWithPaypal(string Cancel = null, string blogId = "", string PayerID = "", string guid = "")
        {
            //getting the apiContext  
            var ClientID = _configuration.GetValue<string>("PayPal:Key");
            var ClientSecret = _configuration.GetValue<string>("PayPal:Secret");
            var mode = _configuration.GetValue<string>("PayPal:mode");
            APIContext apiContext = PaypalConfiguration.GetAPIContext(ClientID, ClientSecret, mode);
            // apiContext.AccessToken="Bearer access_token$production$j27yms5fthzx9vzm$c123e8e154c510d70ad20e396dd28287";
            try
            {
                //A resource representing a Payer that funds a payment Payment Method as paypal  
                //Payer Id will be returned when payment proceeds or click to pay  
                string payerId = PayerID;
                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist  
                    //it is returned by the create function call of the payment class  
                    // Creating a payment  
                    // baseURL is the url on which paypal sendsback the data.  
                    string baseURI = this.Request.Scheme + "://" + this.Request.Host + "/Home/PaymentWithPayPal?";
                    //here we are generating guid for storing the paymentID received in session  
                    //which will be used in the payment execution  
                    var guidd = Convert.ToString((new Random()).Next(100000));
                    guid = guidd;
                    //CreatePayment function gives us the payment approval url  
                    //on which payer is redirected for paypal account payment  
                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, blogId);
                    //get links returned from paypal in response to Create function call  
                    var links = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment  
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    // saving the paymentID in the key guid  
                    httpContextAccessor.HttpContext.Session.SetString("payment", createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    // This function exectues after receving all parameters for the payment  

                    var paymentId = httpContextAccessor.HttpContext.Session.GetString("payment");
                    var executedPayment = ExecutePayment(apiContext, payerId, paymentId as string);
                    //If executed payment failed then we will show payment failure message to user  
                    if (executedPayment.state.ToLower() != "approved")
                    {

                        return View("PaymentFailed");
                    }
                    var blogIds = executedPayment.transactions[0].item_list.items[0].sku;

                  
                    return View("PaymentSuccess");
                }
            }
            catch (Exception ex)
            {
                return View("PaymentFailed");
            }
            //on successful payment, show success page to user.  
            return View("SuccessView");
        }
        private PayPal.Api.Payment payment;
        private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
        {
            var paymentExecution = new PaymentExecution()
            {
                payer_id = payerId
            };
            this.payment = new Payment()
            {
                id = paymentId
            };
            return this.payment.Execute(apiContext, paymentExecution);
        }
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, string blogId)
        {
            //create itemlist and add item objects to it  
           
            var itemList = new ItemList()
            {
                items = new List<Item>()
            };
            //Adding Item Details like name, currency, price etc  
            itemList.items.Add(new Item()
            {
                name ="Item Detail",
                currency = "USD",
                price = "1.00",
                quantity = "1",
                sku = "asd"
            });
            var payer = new Payer()
            {
                payment_method = "paypal"
            };
            // Configure Redirect Urls here with RedirectUrls object  
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl + "&Cancel=true",
                return_url = redirectUrl
            };
            // Adding Tax, shipping and Subtotal details  
            //var details = new Details()
            //{
            //    tax = "1",
            //    shipping = "1",
            //    subtotal = "1"
            //};
            //Final amount with details  
            var amount = new Amount()
            {
                currency = "USD",
                total = "1.00", // Total must be equal to sum of tax, shipping and subtotal.  
                //details = details
            };
            var transactionList = new List<Transaction>();
            // Adding description about the transaction  
            transactionList.Add(new Transaction()
            {
                description = "Transaction description",
                invoice_number = Guid.NewGuid().ToString(), //Generate an Invoice No  
                amount = amount,
                item_list = itemList
            });
            this.payment = new Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            // Create a payment using a APIContext  
            return this.payment.Create(apiContext);
        }

       
    }

After this now you have to go to the model's folder and add a new class file PaypalConfiguration.cs . And add the following code there

   public static class PaypalConfiguration
    {
        //Variables for storing the clientID and clientSecret key  

        //Constructor  

        static PaypalConfiguration()
        {

        }
        // getting properties from the web.config  
        public static Dictionary<string, string> GetConfig(string mode)
        {
            return new Dictionary<string, string>()
            {
                {"mode",mode}
            };
        }
        private static string GetAccessToken(string ClientId, string ClientSecret, string mode)
        {
            // getting accesstocken from paypal  
            string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, new Dictionary<string, string>()
            {
                {"mode",mode}
            }).GetAccessToken();
            return accessToken;
        }
        public static APIContext GetAPIContext(string clientId, string clientSecret, string mode)
        {
            // return apicontext object by invoking it with the accesstoken  
            APIContext apiContext = new APIContext(GetAccessToken(clientId, clientSecret, mode));
            apiContext.Config = GetConfig(mode);
            return apiContext;
        }
    }

Now go to your web config file and add two app settings for client id and client secret

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "PayPal": {
    "Key": "AfIlrsSZigDDFLni0K2VIUrfLObfNvqtCT2mcBvNUxgLTxPUs_o21gVTjoggSpYFcF2hqkMhfVUSqCv1w",
    "Secret": "ECeznQaEnGGSzbtF1mNvyZPSUIrZxfsA-XJlZgrDwjJSI1hj1lqT5r1nISJLYeR2xwBarEg5Mq4n18Lm7",
    "mode": "sandbox"
  }
}

Here, please replace the credentials with your original credentials.


Now go to your Program.cs file and Replace the code

using Microsoft.Extensions.DependencyInjection.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddControllersWithViews();
builder.Services.AddMvc().AddSessionStateTempDataProvider();
builder.Services.AddSession();
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Now add one view and add the following code there for the payment button


<a class="btn btn-primary" href="/Home/PaymentWithPaypal">Pay Now</a>

Now, we have to run the application and you will see this 

How to implement Paypal in AspNet Core 80 2Click on the button and it will call Action PaymentWithPaypal on HomeController. Now, it will create one default item and redirect to the payment page as shown below

How to implement Paypal in AspNet Core 80 3

Now click on the Pay with credit or debit card button and it will redirect to a screen where you will have to add card details.

How to implement Paypal in AspNet Core 80 4

You can fill in the following details here for sandbox testing


Country - United States
Card Type: Visa
Card Number: 4032034155351326
Expiration Date: 09/24
CVV: 275

Street:  4790 Deer Haven Drive
City:  Greenville
State/province/area:   South Carolina
Phone number  864-353-5437
Zip code  29601
Country calling code  +1

Now click on  continue as a guest and it will hit back the same method How to implement Paypal in AspNet Core 80 5Here, you can add a breakpoint and check if your payment is approved

How to implement Paypal in AspNet Core 80 6

For, the production environment you can use 

 { "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "PayPal": {
    "Key": "AfIlrsSZigDDFLni0K2VIUrfLObfNvqtCT2mcBvNUxgLTxPUs_o21gVTjoggSpYFcF2hqkMhfVUSqCv1w",
    "Secret": "ECeznQaEnGGSzbtF1mNvyZPSUIrZxfsA-XJlZgrDwjJSI1hj1lqT5r1nISJLYeR2xwBarEg5Mq4n18Lm7",
    "mode": "live" //For production
  }
}


So after changing the mode you just have to set live credentials in web.config and you will be able to use this on production.

This is how to implement Paypal in Asp.Net Core 8.0.

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

Related Articles

How to implement Paypal in Asp.Net Core
Oct 30, 2022
Payumoney Integration With Asp.Net MVC
Nov 02, 2020
Payout using Paypal Payment Gateway
Nov 13, 2022
How to Integrate Google Sign in Asp.net Core 8.0
May 05, 2024
Previous in ASP.NET Core
Integrate Stripe Payment Gateway In ASP.NET Core 8.0
Next in ASP.NET Core
Error-An error occurred while processing your request in .Net cor…

Comments

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 25989 views
  • Exception Handling Asp.Net Core 20745 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20231 views
  • Task Scheduler in Asp.Net core 17529 views
  • Implement Stripe Payment Gateway In ASP.NET Core 16769 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#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • 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