Paypal Payment Integration In ASP.NET MVC

In this article, we will learn how to implement a Paypal payment gateway in ASP.NET MVC

Now first Get Paypal client id and client secret Key using following  link.

create ASP.NET MVC Project

Now, Install PayPal SDK in your application

Add client id and client secret in web.config

<settings>
      <add name="mode" value="sandbox" />
      <add name="connectionTimeout" value="360000" />
      <add name="requestRetries" value="1" />
      <add name="clientId" value="Your client Id" />
      <add name="clientSecret" value="Your client Secret" />
</settings>

Now Add controller and insert below code in controller

using PayPal.Api;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace PayPalPayment.Controllers
{
    public class PaymentController : Controller
    {
        public ActionResult PaymentWithPaypal(string Cancel = null)
        {           
            APIContext apiContext = PayPalPayment.GetAPIContext();
            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {            
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Payment/PaymentWithPayPal?";                   
                    var guid = Convert.ToString((new Random()).Next(100000));
                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);        
                    var links = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {                         
                            paypalRedirectUrl = lnk.href;
                        }
                    }             
                    Session.Add(guid, createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {                  
                    var guid = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);                  
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return View("FailureView");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            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)
        {
      
            var itemList = new ItemList()
            {
                items = new List<Item>()
            };
     
            itemList.items.Add(new Item()
            {
                name = "Item Name comes here",
                currency = "USD",
                price = "10",
                quantity = "1",
                //sku = "abc"
            });
            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 = "10"
            };
            //Final amount with details  
            var amount = new Amount()
            {
                currency = "USD",
                total = "12", // 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 = "#200000", //Every Time Change
                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);
        }
    }
}

Add View

@{
    ViewBag.Title = "PaymentWithPaypal";
}

<h2>PaymentWithPaypal</h2>

Add Success View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SuccessView</title>
</head>
<body>
    <div> 
        <h1>Success</h1>
    </div>
</body>
</html>

Add Failure View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>FailureView</title>
</head>
<body>
    <div>
        <h1>Failure</h1>
    </div>
</body>
</html>

5 Comments

  1. Fong Chun Yuan

    hi there, i had tried your code, but when i want to checkout, it shows failureview but not paypal

    0
    0
    Reply
    1. Hello @Fong Chun Yuan
      Can you please check your Paypal account. Because your executed payment is not approved. I think some step is missing to setup your Paypal account. Let me know if you have any query

      0
      0
      Reply
  2. You need to set unique invoice number

    0
    0
    Reply
  3. NamLe

    i code same same it but have error:”One or more errors occurred. (The remote server returned an error: (404) Not Found.) please me

    0
    0
    Reply
    1. Priyank

      You need to set unique invoice number

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories