Recently, one of my blog's readers asked me to show how to implement a PayPal payment gateway in ASP.NET MVC applications, so I decided to write an article on the same topic. This article is only for guidance purposes, a person who is going to implement/integrate will have to change the code according to his/her requirement. I am not going to log the exception in this article, but you can use log4net for capturing the exception as well as to maintain the log.
Let's begin.
Go to https://www.paypal.com/

Click on the sign up button in order to register. It will ask some basic question, like whether you want to use it for business or for personal use. In case of business, PayPal will ask you for your PAN Card and GST details.

Go to https://www.paypal.com/

Click on the sign up button in order to register. It will ask some basic question, like whether you want to use it for business or for personal use. In case of business, PayPal will ask you for your PAN Card and GST details.

Paypal will ask to link your bank account which will be used for withdrawing the amount from PayPal to the bank. For bank account verification, PayPal will send two small deposits to your linked bank account.
Once your account is created, click on the gear icon (for setting up the payment gateway). Click on Business Setup.
Or you can directly visit the PayPal developer section (https://developer.paypal.com/developer/applications/). Click on the My Apps & Credential menu and then click on create an app.
Provide App Name and Sandbox developer account in order to create an app.
Provide App Name and Sandbox developer account in order to create an app.
If you don't have a Sandbox account, you have to click on the account menu under the Sandbox section. For testing purposes, we need two accounts: one is for business and another is a merchant account.
Now, click on the App Name created in the previous step in order to get ClientID and Secret key (for the sandbox as well as live). We will use the sandbox ClientID as well as the Secret key for testing purposes .
Let's create a new empty MVC Project and install the PayPal library from the nuget package manager.
You can also visit http://paypal.github.io/PayPal-NET-SDK/ for the supporting documents, samples, codebase.
Add the below code in the configuration section of web.config in order to configure PayPal.
Add a new class and name it PaypalConfiguration and add the below code.
Add the below code in the configuration section of web.config in order to configure PayPal.
- <configSections>
- <section name="paypal" type="PayPal.SDKConfigHandler, PayPal" /> </configSections>
- <!-- PayPal SDK settings -->
- <paypal>
- <settings>
- <add name="mode" value="sandbox" />
- <add name="connectionTimeout" value="360000" />
- <add name="requestRetries" value="1" />
- <add name="clientId" value="Add-Your-ClientID-Here" />
- <add name="clientSecret" value="Add-Your-ClientSecret-Key-Here" /> </settings>
- </paypal>
- public static class PaypalConfiguration {
- //Variables for storing the clientID and clientSecret key
- public readonly static string ClientId;
- public readonly static string ClientSecret;
- //Constructor
- static PaypalConfiguration() {
- var config = GetConfig();
- ClientId = config["clientId"];
- ClientSecret = config["clientSecret"];
- }
- // getting properties from the web.config
- public static Dictionary < string, string > GetConfig() {
- return PayPal.Api.ConfigManager.Instance.GetProperties();
- }
- private static string GetAccessToken() {
- // getting accesstocken from paypal
- string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();
- return accessToken;
- }
- public static APIContext GetAPIContext() {
- // return apicontext object by invoking it with the accesstoken
- APIContext apiContext = new APIContext(GetAccessToken());
- apiContext.Config = GetConfig();
- return apiContext;
- }
- }
Now add an action method named PaymentWithPaypal which will be used for redirecting to the PayPal payment gateway and for executing the transaction. Basically PaymentWithPaypal action redirects users to PayPal's payment page and once the user clicks on pay, it will provide PayerID which will be used for executing the transction.
Now build and call the PaymentWithPaypal action of Home controller. You will be redirected to the sandbox payment page of PayPal. Login here with the Business account created on the sandbox in earlier steps.
- public ActionResult PaymentWithPaypal(string Cancel = null) {
- //getting the apiContext
- APIContext apiContext = PaypalConfiguration.GetAPIContext();
- 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 = Request.Params["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 = Request.Url.Scheme + "://" + Request.Url.Authority + "/Home/PaymentWithPayPal?";
- //here we are generating guid for storing the paymentID received in session
- //which will be used in the payment execution
- var guid = Convert.ToString((new Random()).Next(100000));
- //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);
- //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
- Session.Add(guid, createdPayment.id);
- return Redirect(paypalRedirectUrl);
- } else {
- // This function exectues after receving all parameters for the payment
- var guid = Request.Params["guid"];
- var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
- //If executed payment failed then we will show payment failure message to user
- if (executedPayment.state.ToLower() != "approved") {
- return View("FailureView");
- }
- }
- } catch (Exception ex) {
- return View("FailureView");
- }
- //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) {
- //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 Name comes here",
- currency = "USD",
- price = "1",
- quantity = "1",
- sku = "sku"
- });
- 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 = "3", // 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 = "your generated invoice number", //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);
- }
On expanding the Amount, you will see the details like description, items, subtotal, shipping charges, VAT etc. applied to the transaction. Click on Login.
Click on Continue in order to pay the amount.
You will get a successful payment message or payment failed in case of exception as the final result of the completion of the transaction.
You can also check notifications for the payment made under the sandbox account by expanding and clicking on the notification link.

I hope this will help you.

Sabir HussainPosted Nov 10, 2021, 11:18 AM
How can i subtract a discount amount from the final amount???? e.g i have three items Item1: 200; item2: 300; item3: 400, tax:50, shipping:100, totalamount will be 1050. so wi wanna give 120 discount, how can i subtract if from total?? as this above code calculates and matches subtotal, tax with total, and items amount with total as well!
Sabir HussainPosted Nov 10, 2021, 11:17 AM
How can i subtract a discount amount from the final amount????
Sudhan R JayPosted Oct 31, 2020, 1:41 PM
I'm getting failure in paypal executepayment method. getting bad request exception
Mohammad SanatiPosted Sep 21, 2020, 10:21 PM
Thanks for demonstration. Looks like important part of the project is missing from download: Home/Index.chtml
Roshan RathodPosted Sep 16, 2020, 1:54 AM
Keep it up
lnicolaePosted Aug 27, 2020, 5:40 AM
Csc.exe not found !
Rathod BharatPosted Jul 1, 2020, 5:41 AM
Sir is working good in my project .
Victor VincentPosted Mar 26, 2020, 10:52 AM
The ApiContext Does not exist in my mvc project. i followed the above steps
syspro userPosted Jan 17, 2020, 4:03 PM
Can we Integrate PayPal with multiple business accounts(two or three live accounts) in a single MVC application.
Anthony SchrothPosted Dec 23, 2019, 11:28 PM
I tried your sample code and it works for me. Good job! I am wondering if you have a sample code to cancel or refund a PayPal transaction in ASP.Net MVC?
James DickinsonPosted Sep 2, 2019, 12:00 AM
Hi, I have used your example in my vb.net site however I'm getting errors with the Request object. It is not ever initialized?
Pushpendra BhardwajPosted Aug 25, 2019, 10:06 PM
Hi, i have integrated Paypal in asp.net website. My code is working perfectly on local machine. i have hosted website on godaddy, .On live site website throws an error "The type initializer for 'PaypalConfiguration' threw an exception." I have no clue how to fix this issue. Could you help me to fix this issue on Godaddy.
sanny rautelaPosted Aug 23, 2019, 4:38 AM
I can not see Pay with Credit or Debit Card option on the bottom. Can you please tell me why?
adnan shafiPosted Jun 14, 2019, 12:45 PM
Brother i want to integration Asp.net only not MVC how can i create it?
Shraddha SinghPosted Jun 1, 2019, 8:30 AM
Hi Anup for hotel website i want to integrate paypal so it is ok this much code i will implement
Shabeeb MTPosted May 9, 2019, 1:24 AM
I want display my cart items and details in the followint code using a foreach loop,,itemList.items.Add(new Item() { name = "Item Name comes here", currency = "USD", price = "1", quantity = "1", sku = "sku" });
Maurice KingPosted Jan 12, 2019, 4:43 PM
I keep getting FailureView for new users on my site, it was working fine before. Not sure whats going on, would like some help
Jainav SuranaPosted Dec 23, 2018, 9:46 AM
I am facing issue with Paypal integration with Live account. Can please someone help me. It is really urgent.
zia khanPosted Dec 19, 2018, 5:33 AM
Good job Sir
saroj dsaPosted Nov 27, 2018, 4:34 AM
Pay with debit and credit card,please tell the procedure.but now is is not working say We aren't able to process your payment using your PayPal account at this time. Please go back to the merchant and try using a different payment method.
Syed Munawar HussainPosted Nov 5, 2018, 9:02 AM
Hello bro, where is the index view, you have written controller but there is no index view
Akshay singhPosted Sep 30, 2018, 2:08 PM
Please tell me how to integratepayment gateway with payumoney in my asp.net web api application
Peter JackelPosted Sep 9, 2018, 11:36 PM
There is no INDEX view for this ... doesn't work.
purav shahPosted Aug 22, 2018, 2:25 AM
Hii anoop i get error of merchant cant accept your payment. please let me know how can i solve this issue.
zeeshan amanatPosted Jun 30, 2018, 2:51 AM
Hi Anoop, Thanks for the code. It works fine on the first attempt but after that, I'm getting "Payment failed!" error on every single attempt. What's the issue? Any Idea?
Nicholas LeongPosted Jun 26, 2018, 12:31 AM
Hi Anoop Kumar Sharma, error line: string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken(); Descrition: PayPal.IdentityException: The remote server returned an error: (401) Unauthorized. Please help
Varghese MathewPosted Jun 21, 2018, 11:53 AM
Hi Anoop , I have downloaded the code and executed , there is no index view ..
Rashed MamunPosted May 15, 2018, 7:41 AM
That code dosn't work for Live account. Works fine in sandbox account. Any Idea?
ravan rajPosted Mar 26, 2018, 8:56 AM
This Code is not working
Sheikh Abdul MateenPosted Mar 20, 2018, 12:23 AM
Dear how can check payment is success or not in success url in mvc C#