articles

Home / DeveloperSection / Articles / How to integrate PayPal API in ASP.NET MVC Application?

How to integrate PayPal API in ASP.NET MVC Application?

How to integrate PayPal API in ASP.NET MVC Application?

Ashutosh Patel 1243 25-Apr-2023

To integrate the PayPal API in the ASP.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 before going live.

If you don’t have an account on PayPal first create an account on PayPal.

2. Create a PayPal REST 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 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?

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.

How to integrate PayPal API in ASP.NET MVC Application?

After completing the above process successfully you need to add the following code in web.config file in your ASP.NET MVC Application.

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

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

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

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

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?

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?

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?

 

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

Thank you!

 


I am a software developer at MindStick soft. Pvt. ltd. I joined this company in august 2021 after completing my post-graduation course. I love to see the historical places of my country.

Leave Comment

Comments

Liked By