Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
30 Oct
2022

How to implement Paypal in Asp.Net Core

by Shubham Batra

2154

Download Attachment

Paypal

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

First of all take one Asp.net Core mvc application and we will install paypal nuget package which is showed in the image below

After you have done installing paypal nuget package we will have to take one new controller where we will add 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 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 models folder and add new class file PaypalConfiguration.cs . And add 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 appsettings for clientid 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 add one view and add following code there for 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 

Click on the button and it will call Action PaymentWithPaypal on HomeController. Now , it will create one default item and redirect on the payment page as showed below

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

You can fill the follow details in 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 guest and it will hit back the same method Here , you can add a breakpoint and check if your payment is approved

For, 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.

  • |
  • Aspnet Core , Paypal , Paypal in Aspnet core

Comments

Follow Us On Social Media - Like Us On Facebook

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Image Optimize in C#
Scheduler
Web Api in Aspnet MVC
Web API CRUD Operations
Web API CRUD Operations In ASPNET MVC Application
create a read only MySQL user
Scheduler Service
Task scheduler in AspNet
Task Scheduler
Git Tutorial for Beginners and Intermediate
Git Tutorial
Git
Github
commit
repository
push
pull request
branches
Git Branching and Merging
Branching
Merging
compress images csharp
compress jpeg csharp
compress png csharp
compress tiff csharp
Slick Slider
Slick Slider Responsive
Csharp
OpenJson
Sql server
Json
Numbers validation javascript
Allow only numbers to be typed in a textbox
Number validation in JavaScript
Numric only validation in javascript
Alphanumeric validation javascript
Allow only Alphanumeric to be typed in a textbox
Alphanumeric validation in JavaScript
Number And Decimal validation javascript
Allow only Number And Decimal to be typed in a textbox
Number And Decimal validation in JavaScriptA
Alphabets validation javascript
Allow only Alphabets to be typed in a textbox
Alphabets validation in JavaScript
Aphabet validations using js
Jquery
Validations
AspNet Core MVC Publish using FTP (File Transfer Protocol)
AspNet MVC Publish using FTP (File Transfer Protocol)
AspNet MVC Publish using FTP
AspNet Core MVC Publish using FTP
Publish using FTP
How to add whatsapp share button on a website
How to add a WhatsApp share button on a website
apiwhatsappcom
Share to whatsapp
HTTP Error 50031 Failed to load ASP NET Core runtime
Http Error
The Extender Provider failed to return an Extender for this object
Twilio SMS and ASPNET Core 60
How to Send an SMS with ASPNET Core
Using Dependency Injection with Twilio SMS and ASPNET Core 21
Twillio
Twillio in AspNet
Twillio SMS Integration
Number And Decimal validation in JavaScript
Quickblox
Quickblox javascript sdk
javascript sdk
Audio and video call using js
Quickblox audio call
Quickblox video call
Winforms
DevExpress
Net
Reading Values From Appsettingsjson In ASPNET Core 31 and 60
appsettingsjson
ASPNET Core
Reading Values From appsettingsjson
countdown timer
Timer in js
Jquery InputMask
Input masking
Masking using jquery
Phone mask
Email mask
Input mask using jquery
Firebase
Firebase Database
Firesharp
Firebase using Aspnet
Neo4J
Neo4j Driver
Neo4J in Aspnet
Graph Database
JWT
JWT Token
JWT in AspNet
JWT in Aspnet MVC
Validate jwt token
Twilio SMS And ASPNET MVC
How To Send An SMS With ASPNET MVC
Twillio In AspNet
Implementation Of SignalR With NET Core
Build Real time Applications with ASPNET Core SignalR
NET Core
SignalR
SignalR With NET Core
signalr in aspnet core
Owin Authentication
Owin
Microsoft Owin
Owin in Api
Owin authentication in Api
Twillio Logs
Get Twillio Logs
Paypal
Paypal Integration in AspNet MVC
Paypal Integration
Unable to connect to any of the specified MySQL hosts
Aspnet Core
Paypal in Aspnet core
Payout in Paypal
Paypal Payment Gateway
Payouts
Hangfire with ASPNET Core
Hangfire in ASPNET Core 31
Hangfire in ASPNET
Hangfire
Web Api
Api
Aspnet core
AutoMapper
Automapper in Aspnet MVC
Angular Material Select Dropdown with Image
StreamReader
Json to C#
JWT Token Authentication And Authorizations In Web API
C# Collections
Collections (C#)
Fibonacci series in Java
Display Fibonacci Series
First C# Program
What is C?
C
C Programming
Narrowing Casting
Widening Casting
Java Type Casting
How to Connect to a Database with MySQL Workbench
read only MySQL user
GROUP_CONCAT()
Multiple rows to one comma separated value in Sql Server
Converting commas or other delimiters to a Table or List in SQL Server
Sql Server
Finding table references
T Sql
Finding tables by column name
Renaming column in Sql
RazorPay in Aspnet MVC
RazorPay in net
RazorPay in MVC
RazorPay Integration in AspNet
Implementing RazorPay in Aspnet
aspnetmvc
Ninject In ASPNET MVC
csharp
designpattern
ef
Python
OpenCV
Face Detection
Realtime face detection
AI
fixed header and scrollable body
Simple Pagination
Pagination in mvc
Pagination in Aspnet MVC
MVC Paging
HttpClient
Web Api from Server Side
Calling web api
Consuming web api
Azure Blob Storage in an ASPNET Core
How to upload files to Azure Blob Storage in an ASPNET Core Web
How to delete files to Azure Blob Storage in an ASPNET Core Web
Record HTML Element In aspnet MVC using Jquery
Screen Recording with Audio using JavaScript in ASPNET MVC
Screen recording
How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider Example
responsive carousels
Entity Framework
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
Url Rewriting
Implement Stripe Payment Gateway In ASPNET Core
Stripe Payment Gateway
StripeNet
Convert HTML String To Image In C#
HTMLtoImage
Convert Html to Image in AspNet
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Caching in ASPNET Core using Redis Cache
Redis Cache
Caching in ASPNET Core
ASPNET Core Redis Cache
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
AspNet core 31
Aspnet core 21
HttpCookies in AspNet Core
Custom FIlter attribute
Custom Authentication
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption
Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
SSRS
SSRS Report
ASPNET MVC
ASPNET MVC SSRS Report
ssrs report
XlWorkbook
ClosedXml
Excel Export
Blazor
Syncfusion
SFGrid
Syncfusion SFgrid
Net core 60
DataTable to List
Extension Methods
Microsoft Access Database Engine
Ace Ole Db 120
MicrosoftACEOLEDB120
OLE DB
Aspnet MVC
Ace OLE DB
rdlc
Report Viewer
RDLC Report
Max Request Length
Thank you for Downloading....!

Subscribe for more tutorials

Support our team

Continue with Downloading

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2023 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Privacy Policy
  • Json Beautifier