PayPal Payment Gateway Integration In ASP.NET MVC

Recently, one of my blog's readers asked me to show how to implement a PayPal payment gateway in ASP.NET MVC applications, so I decided to write an article on the same topic. This article is only for guidance purposes, 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 the exception in this article, but you can use log4net for capturing the exception as well as to maintain the log. 
 
Let's begin.

Go to https://www.paypal.com/



Click on the sign up button in order to register. It will ask some basic question, like whether you want to use it for business or for personal use. In case of business, PayPal will ask you for your PAN Card and GST 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 linked bank account.

 

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 the My Apps & Credential menu and then click on create an app. 

 

Provide App Name and Sandbox developer account in order to create an app.

 

If you don't have a Sandbox account, you have to click on the account menu under the Sandbox section. For testing purposes, we need two accounts: one is for business and another is a 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 purposes . 

 

Let's create a new empty MVC Project and install the PayPal library from the nuget package manager. 

 
You can also visit http://paypal.github.io/PayPal-NET-SDK/ for the supporting documents, samples, codebase. 

 

 

Add the below code in the configuration section of web.config in order to configure PayPal.
  1. <configSections>  
  2.     <section name="paypal" type="PayPal.SDKConfigHandler, PayPal" /> </configSections>  
  3. <!-- PayPal SDK settings -->  
  4. <paypal>  
  5.     <settings>  
  6.         <add name="mode" value="sandbox" />  
  7.         <add name="connectionTimeout" value="360000" />  
  8.         <add name="requestRetries" value="1" />  
  9.         <add name="clientId" value="Add-Your-ClientID-Here" />  
  10.         <add name="clientSecret" value="Add-Your-ClientSecret-Key-Here" /> </settings>  
  11. </paypal>  
Add a new class and name it PaypalConfiguration and add the below code.
  1. public static class PaypalConfiguration {  
  2.     //Variables for storing the clientID and clientSecret key  
  3.     public readonly static string ClientId;  
  4.     public readonly static string ClientSecret;  
  5.     //Constructor  
  6.     static PaypalConfiguration() {  
  7.         var config = GetConfig();  
  8.         ClientId = config["clientId"];  
  9.         ClientSecret = config["clientSecret"];  
  10.     }  
  11.     // getting properties from the web.config  
  12.     public static Dictionary < string, string > GetConfig() {  
  13.         return PayPal.Api.ConfigManager.Instance.GetProperties();  
  14.     }  
  15.     private static string GetAccessToken() {  
  16.         // getting accesstocken from paypal  
  17.         string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();  
  18.         return accessToken;  
  19.     }  
  20.     public static APIContext GetAPIContext() {  
  21.         // return apicontext object by invoking it with the accesstoken  
  22.         APIContext apiContext = new APIContext(GetAccessToken());  
  23.         apiContext.Config = GetConfig();  
  24.         return apiContext;  
  25.     }  
  26. }  
Now add an action method named  PaymentWithPaypal which will be used for redirecting to the PayPal payment gateway and for executing the transaction. Basically PaymentWithPaypal action redirects users to PayPal's payment page and once the user clicks on pay, it will provide PayerID which will be used for executing the transction.
  1. public ActionResult PaymentWithPaypal(string Cancel = null) {  
  2.     //getting the apiContext  
  3.     APIContext apiContext = PaypalConfiguration.GetAPIContext();  
  4.     try {  
  5.         //A resource representing a Payer that funds a payment Payment Method as paypal  
  6.         //Payer Id will be returned when payment proceeds or click to pay  
  7.         string payerId = Request.Params["PayerID"];  
  8.         if (string.IsNullOrEmpty(payerId)) {  
  9.             //this section will be executed first because PayerID doesn't exist  
  10.             //it is returned by the create function call of the payment class  
  11.             // Creating a payment  
  12.             // baseURL is the url on which paypal sendsback the data.  
  13.             string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Home/PaymentWithPayPal?";  
  14.             //here we are generating guid for storing the paymentID received in session  
  15.             //which will be used in the payment execution  
  16.             var guid = Convert.ToString((new Random()).Next(100000));  
  17.             //CreatePayment function gives us the payment approval url  
  18.             //on which payer is redirected for paypal account payment  
  19.             var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);  
  20.             //get links returned from paypal in response to Create function call  
  21.             var links = createdPayment.links.GetEnumerator();  
  22.             string paypalRedirectUrl = null;  
  23.             while (links.MoveNext()) {  
  24.                 Links lnk = links.Current;  
  25.                 if (lnk.rel.ToLower().Trim().Equals("approval_url")) {  
  26.                     //saving the payapalredirect URL to which user will be redirected for payment  
  27.                     paypalRedirectUrl = lnk.href;  
  28.                 }  
  29.             }  
  30.             // saving the paymentID in the key guid  
  31.             Session.Add(guid, createdPayment.id);  
  32.             return Redirect(paypalRedirectUrl);  
  33.         } else {  
  34.             // This function exectues after receving all parameters for the payment  
  35.             var guid = Request.Params["guid"];  
  36.             var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);  
  37.             //If executed payment failed then we will show payment failure message to user  
  38.             if (executedPayment.state.ToLower() != "approved") {  
  39.                 return View("FailureView");  
  40.             }  
  41.         }  
  42.     } catch (Exception ex) {  
  43.         return View("FailureView");  
  44.     }  
  45.     //on successful payment, show success page to user.  
  46.     return View("SuccessView");  
  47. }  
  48. private PayPal.Api.Payment payment;  
  49. private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId) {  
  50.     var paymentExecution = new PaymentExecution() {  
  51.         payer_id = payerId  
  52.     };  
  53.     this.payment = new Payment() {  
  54.         id = paymentId  
  55.     };  
  56.     return this.payment.Execute(apiContext, paymentExecution);  
  57. }  
  58. private Payment CreatePayment(APIContext apiContext, string redirectUrl) {  
  59.     //create itemlist and add item objects to it  
  60.     var itemList = new ItemList() {  
  61.         items = new List < Item > ()  
  62.     };  
  63.     //Adding Item Details like name, currency, price etc  
  64.     itemList.items.Add(new Item() {  
  65.         name = "Item Name comes here",  
  66.             currency = "USD",  
  67.             price = "1",  
  68.             quantity = "1",  
  69.             sku = "sku"  
  70.     });  
  71.     var payer = new Payer() {  
  72.         payment_method = "paypal"  
  73.     };  
  74.     // Configure Redirect Urls here with RedirectUrls object  
  75.     var redirUrls = new RedirectUrls() {  
  76.         cancel_url = redirectUrl + "&Cancel=true",  
  77.             return_url = redirectUrl  
  78.     };  
  79.     // Adding Tax, shipping and Subtotal details  
  80.     var details = new Details() {  
  81.         tax = "1",  
  82.             shipping = "1",  
  83.             subtotal = "1"  
  84.     };  
  85.     //Final amount with details  
  86.     var amount = new Amount() {  
  87.         currency = "USD",  
  88.             total = "3"// Total must be equal to sum of tax, shipping and subtotal.  
  89.             details = details  
  90.     };  
  91.     var transactionList = new List < Transaction > ();  
  92.     // Adding description about the transaction  
  93.     transactionList.Add(new Transaction() {  
  94.         description = "Transaction description",  
  95.             invoice_number = "your generated invoice number"//Generate an Invoice No  
  96.             amount = amount,  
  97.             item_list = itemList  
  98.     });  
  99.     this.payment = new Payment() {  
  100.         intent = "sale",  
  101.             payer = payer,  
  102.             transactions = transactionList,  
  103.             redirect_urls = redirUrls  
  104.     };  
  105.     // Create a payment using a APIContext  
  106.     return this.payment.Create(apiContext);  
  107. }  
Now build and call the PaymentWithPaypal action of Home controller. You will be redirected to the sandbox payment page of PayPal. Login here with the Business account created on the 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 a successful payment message or payment failed in case of exception as the final result of the completion of the transaction.

 

You can also check notifications for the payment made under the sandbox account by expanding and clicking on the notification link. 



I hope this will help you.


Similar Articles