Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Saturday, 31 March 2018

PayPal payment gateway integration in ASP.NET MVC

Recently, someone on my blog asked me to How to implement PayPal payment gateway in an ASP.NET MVC application. This Article is only for guidance purpose, 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 any kind of exception in this article, but people can use log4net etc. for capturing the exception as well as to maintain the log.

Let's Begin:
Visit https://www.paypal.com/
and click on the Signup button in order to register. It will ask some basic question, like whether you want to use for Business or for personal. In the case of Business, PayPal will ask your PAN Card details, GST etc. 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 bank.
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 My Apps & credential menu and then click on create an App.
Provide App Name and Sandbox developer account in order to create App.
If you don't have Sandbox account, you have to click on Account menu under the sandbox section. For the Testing purpose, we need two accounts: One is Business and another is 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 purpose.
Let's create a new empty MVC Project and install the PayPal library reference from the nugget package manager.
You can also visit http://paypal.github.io/PayPal-NET-SDK/ for the supporting documents, samples, codebase.

Add below code in the configuration section of web.config in order to configure the 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>
Add a new class named it as PaypalConfiguration and add below code.
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 it as PaymentWithPaypal which will be used for redirecting to PayPal payment gateway and for executing the transaction. Basically PaymentWithPaypal action redirect used to the PayPal’s payment page and once user click on pay, it will provide Payer ID which will be used for executing the transaction.
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);
        }
Now build and call PaymentWithPaypal action of Home controller. You will be redirected to the sandbox payment page of PayPal. Login here with the Business account created on sandbox in earlier steps.
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 payment successful message or payment failed in case of exception as the final result of the completion of the transaction.
You can also check notification for the payment made under the sandbox account by expanding and clicking on notification link.
Hope this will help you.
Thanks.

Protected by Copyscape Plagiarism Checker - Do not copy content from this page.

[Download Source Code via Google Drive]

13 comments:

  1. HI
    Very Interesting Blog ...

    I downloaded the source and updated my clientid and secret when I go to the Home/PayPalPayment i get error unathorized at string accessToken = new OAuthTokenCredential

    What am I missing ??

    Regards

    ReplyDelete
  2. Sorry My Silly Mistake.. One of the keys wasn't copied fully ... SORRY

    ReplyDelete
  3. I got an error when login in paypal to pay.
    credential right, what can be? My account not well set?

    Regards

    ReplyDelete
  4. I got an error when login in paypal to pay.
    credential right, what can be? My account not well set?

    Regards

    ReplyDelete
  5. hi sir,
    i have followed this article and make integration but it's going on paypal login screen. we don't wan't login screen. we need to go direct payment screen.please help me.

    ReplyDelete
    Replies
    1. I suppose you can't.
      Or try to set the same payerID (string payerId = Request.Params["PayerID"];) and set automatic payment of account you have to use to pay.

      Regards

      Delete
  6. Thanks for sharing this post. I'm very interested in this topic. https://onlineconvertfree.com/convert-format/wav-to-mp3/ Check out this awesome useful online file converter that can come handy for use.

    ReplyDelete
  7. Wow good job i Complete this

    ReplyDelete
  8. Hi, I have a question: Now I'm using ASP.NET Core project, and I don't have file web.config.What should I do.
    please help me!!

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hi, i follow this tutorial and it works fine!
    Now ho to go live? i suppose i need to change something..
    maybe here ? :
    i need to click in my paypal account to "live"? or others thing to do?

    And anyone can help me to improve this code in order pass by form the following data to the controller? :
    price
    shipping
    name of item
    and quantity
    what to modify?

    And last thing, do i have access to the successview only if the token is valid? if not how to improve this page?

    Thanks

    ReplyDelete
    Replies
    1. got any solution already?? i also faced the same question with u
      which don't know how to pass the value to controller.

      Delete
  11. For the latest solution of PayPal server-side integration in ASP.NET Web Forms using Orders v2 REST API with PayPal JavaScript SDK, test the demo on: https://techtolia.com/PayPal/

    Receive payments from PayPal, PayPal Credit, credit or debit cards, Bancontact, BLIK, eps, giropay, iDEAL, MyBank, Przelewy24, SEPA-Lastschrift, Sofort, Venmo via PayPal.

    ReplyDelete

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook