---
title: "How to integrate PayPal API in ASP.NET MVC Application?"  
description: "Integrate PayPal Payment gateway for sending and receiving amounts over the internet through a PayPal account in the asp.net MVC application."  
author: "Ashutosh Patel"  
published: 2023-04-25  
updated: 2023-11-08  
canonical: https://www.mindstick.com/articles/332472/how-to-integrate-paypal-api-in-asp-dot-net-mvc-application  
category: "asp.net mvc"  
tags: ["api(s)", "asp.net mvc", "asp.net web api", "Payment Gateway"]  
reading_time: 8 minutes  

---

# How to integrate PayPal API in ASP.NET MVC Application?

To integrate the PayPal API in the ASP.NET [MVC application](https://www.mindstick.com/forum/12862/require-authorization-within-whole-asp-dot-net-mvc-application) follow the below steps:

## 1. Create a PayPal developer account:

When you start integrating PayPal API into your ASP.NET MVC application you need to create a developer account on PayPal. This will give you access to the PayPal sandbox, which helps you to test [your application](https://answers.mindstick.com/qa/97584/how-do-you-choose-the-correct-camera-for-your-application) before going live.

If you don’t have an account on PayPal first [create an account on PayPal.](https://www.mindstick.com/articles/332465/how-to-create-an-account-on-paypal)

**2. Create a PayPal REST [API application](https://www.mindstick.com/forum/161611/how-do-you-save-user-uploaded-files-to-disk-in-an-asp-dot-net-mvc-or-web-api-application):** Once you create an account on PayPal then you need to visit **https://developer.paypal.com/** and log in with your **PayPal credential** to find the **Client ID** and **Client** **Secret** and also you can [create a sandbox account](https://www.mindstick.com/articles/332461/how-to-create-a-sandbox-account-on-paypal-for-testing) to test your application before going live.

To create a new sandbox account click on **Create account** then choose account type (Individual and Business) and select your country from the dropdown then click on **Create** button.

You can see your newly created sandbox account in the Sandbox account list given in the below image.

![How to integrate PayPal API in ASP.NET MVC Application?](https://www.mindstick.com/mindstickarticle/834f011d-9d9d-4106-b1b0-428b267da8bd/images/ced6f97b-adcd-4e7a-ab47-3ec00c1a0b6e.png)

**3. Install the PayPal .NET SDK:** The PayPal .NET SDK provides a set of libraries and tools that make it easy to integrate the PayPal API into your ASP.NET MVC application. You can install the SDK using the NuGet [package manager](https://answers.mindstick.com/qa/112022/what-are-the-advantages-of-using-a-package-manager-like-npm-or-yarn-in-javascript-development).

![How to integrate PayPal API in ASP.NET MVC Application?](https://www.mindstick.com/mindstickarticle/834f011d-9d9d-4106-b1b0-428b267da8bd/images/a85f09ca-e79f-42da-acc2-7c38f9e23e3a.png)

After completing the above process successfully you need to add the following code in **web.config** [file in your](https://www.mindstick.com/forum/34276/how-to-call-the-html-file-in-your-java-code) ASP.NET MVC Application.

```html
<configSections>
     <sectionname="paypal" type="PayPal.SDKConfigHandler, PayPal" />
  </configSections>

<paypal>
    <settings>
      <addname="mode" value="sandbox" />
      <addname="connectionTimeout" value="360000" />
      <addname="requestRetries" value="1" />
      <addname="clientId" value="Add Your ClientID Here" />
      <addname="clientSecret" value="Add Your Client Secret Here" />

    </settings>
  </paypal>
```

> In the above code **<add name="mode" value="sandbox" />** is used in PayPal [API integration](https://answers.mindstick.com/qa/104395/how-to-start-coding-with-api-integration) to indicate that the application is being tested in the PayPal Sandbox environment.
>
> **<add name="connectionTimeout" value="360000" /> (**which means 360 seconds or 6 minutes**)**is used in PayPal API integration to set the maximum time limit for the connection to establish with the PayPal servers.

> <add name="requestRetries" value="1" /> is used in PayPal API integration to specify the number of times the client application should retry making a failed API request.

> In a PayPal developer account, a **client ID** and **client secret** are used to identify and authenticate your application when making API calls to PayPal.
>
> *A **client ID** is a unique identifier that is generated by PayPal when you create a new application in your developer account. It is used to identify your application and establish a connection with the PayPal API.*

Add an action link in your **View** page,

```html
<a class="btn btn-primary" href="@Url.Action("ActionName", "ControllerName")">Pay Now</a>
```

and make an **Ajax call** when clicking on the button to call the [controller method](https://www.mindstick.com/forum/34409/controller-method-not-found-error).

```javascript
<script>
 $(document).ready(function() {
     $('#paypal-button').click(function() {
         $.ajax({
              url: '/controllerName/ActionName',
              type: 'POST',
              data: {},
              success: function(data) {
                  console.log(data);
              },
              error: function(xhr, status, error) {
                  console.log(error);
              }
         });
     });
 });
</script>
```

After all, add a new class named “**PaypalConfiguration**“ in Model and add the following code to it.

```cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PayPal.Api;

namespace PaypalApplication.Models
{
    public class PaypalConfiguration
    {
        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 in your controller named **PaymentWithPaypal** which will be used for redirecting to the PayPal [payment gateway](https://answers.mindstick.com/qa/113305/what-is-a-payment-gateway) and for executing the transaction. Basically, the **PaymentWithPaypal** action redirects users to the payment page of PayPal and once the user clicks on pay, it will provide a **PayerId** and **PaymentId** which will be used for executing the transaction.

```cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PayPal.Api;
using PaypalApplication.Models;

namespace PaypalApplication.Controllers
{
    public class PayPalController : Controller
    {
        //
        // GET: /PayPal/

        public ActionResult Index()
        {
            var payment = new Payment();
            return View();
        }

        public ActionResult PaymentWithPaypal(string Cancel = null)
        {
           //getting the apiContext
           APIContext apiContext = PaypalConfiguration.GetAPIContext();
            try
            {
                // Add the CORS header to allow requests from any origin
               Response.AddHeader("Access-Control-Allow-Origin", "*");

                //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 + "/PayPal/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)
            {
                Console.WriteLine("error " + 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
            };
            var payment = new Payment()
            {
                id = paymentId
            };
            var executePayment = payment.Execute(apiContext, paymentExecution);
            return executePayment;
        }
        private Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
           //Generate random invoice number for multiple time payment
            string invoiceId = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 9999);

            //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 or Product name here",
               currency = "USD",
               price = "1",
               quantity = "1",
                sku = "sku"
            });

            // 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 comes here",
               invoice_number = invoiceId, //Generate an Invoice No
                amount = amount,
               item_list = itemList
            });
           this.payment = new Payment()
            {
               intent = "sale",
               payer = new Payer() { payment_method = "paypal" },
               transactions = transactionList,
               redirect_urls = redirUrls
            };
            // Create a payment using a APIContext
            return this.payment.Create(apiContext);
        }

    }
}
```

Now Build and Run your application. When you click on **Pay Now** it will call the **PaymentWithPaypal** action from the controller which redirects you to the payment page of PayPal. Login here with your PayPal sandbox account credentials.

![How to integrate PayPal API in ASP.NET MVC Application?](https://www.mindstick.com/mindstickarticle/834f011d-9d9d-4106-b1b0-428b267da8bd/images/9ebaf848-bc74-4dcc-a70a-2aeaba8535f4.png)

After logging is successful, it will redirect you to the final payment page of PayPal where you can see the amount details with tax, shipping amount, and currency. Click on **continue** order to pay the amount.

![How to integrate PayPal API in ASP.NET MVC Application?](https://www.mindstick.com/mindstickarticle/834f011d-9d9d-4106-b1b0-428b267da8bd/images/fdd7b2bf-d4c2-4a91-a0ae-9c39a9d15d62.png)

After payment successfully from your sandbox account you can check the amount of that account click on **View/Edit account** from the three dots on the right side of the account in the sandbox account list and click on **Funding**.

![How to integrate PayPal API in ASP.NET MVC Application?](https://www.mindstick.com/mindstickarticle/834f011d-9d9d-4106-b1b0-428b267da8bd/images/05838db7-701a-48e6-be04-3fea48547c7e.png)

I hope my content was meaningful. If you have any suggestions, let me know.

## Thank you!

---

Original Source: https://www.mindstick.com/articles/332472/how-to-integrate-paypal-api-in-asp-dot-net-mvc-application

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
