Thumb

Part-18(Final): eCommerce PayPal Payment complete using ASP.NET MVC | Payment Gateway in asp.net

Part-0 (introduction ): E-Commerce introduction using asp.net mvc Part-1: Ecommerce website design using Bootstrap | Building an Ecommerce website | ASP.NET MVC Part-2: Ecommerce website design using HTML, CSS, Bootstrap, JavaScript | ASP.NET MVC Part-3: Ecommerce DataBase design in SQL Server | ASP.NET MVC | JQUERY Ajax Json Part-4: Ecommerce website Entity Framework data model integration | ASP.NET MVC | JQUERY Ajax Json Part-5: Repository pattern in eCommerce project | ASP NET MVC | C# Part-6: Ecommerce Dashboard or admin using Bootstrap CSS | ASP.NET MVC Part-7: eCommerce Add and Edit Category into Admin Panel using ASP.NET MVC | Jquery Part-8: eCommerce Add and Edit Product into Admin Panel using ASP.NET MVC | Jquery Part-9: eCommerce Products Load and File upload ASP.NET MVC | Razor Dropdown Part-10: eCommerce Product Search using Store Procedure Entity Framework | ASP.NET MVC Part-11: eCommerce Paging Filtering with Entity Framework using ASP.NET MVC | Razor Paging Part-12: eCommerce Product Add to Shopping Cart in ASP.NET MVC | Dynamic Shopping Cart ASP.NET Part-13: eCommerce Product Remove from Shopping Cart in ASP.NET MVC | Dynamic Shopping Cart ASP.NET Part-14: eCommerce Manage Duplicate Entry Shopping Cart in ASP.NET MVC | Dynamic Shopping Cart Part-15: eCommerce Checkout manage in ASP.NET MVC | Razor | Jquery Part-16: eCommerce PayPal payment gateway integration in ASP.NET MVC|Free payment gateway Part-18(Final): eCommerce PayPal Payment complete using ASP.NET MVC | Payment Gateway in asp.net Part-17: eCommerce PayPal Payment Logic implementation in ASP.NET MVC | using C#

1/4/2020 12:00:00 AM

Download Project  (Full Project)

Step-1

In this tutorial I will show how to PayPal payment complete using asp.net MVC. First open visual studio then opens the ecommerce tutorial project then go to   PaymentController this controller contains many methods. We first create success and failed view. So write a return view and add the view of the controller. This view is representing the fail and success or fail notification. Now given bellow the controller code:

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

namespace PayPalApplicetion.Controllers
{
    public class PaymentWithPaypalController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        

        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);
        }
    }
}

Step-2

Success view is representing the success text and redirect the success view. We can redesign the view html code. Now given bellow the success view code:

@{
    ViewBag.Title = "PaymentWithPaypal";
}

<h2>PaymentWithPaypal</h2>

Step-3

fail view is representing the fail text and redirect the fail view. We can redesign the view html code. Now given bellow the fail view code:

@{
    ViewBag.Title = "PaymentWithPaypal";
}

<h2>PaymentWithPaypal</h2>

Step-3

Now run the project