How to refund payment using Paypal in Asp.Net MVC
Paypal
Paypal is a payment gateway which provides secure payments across the world. It help you accept international payment at some price per transaction. There is no initial setup fee for implementing paypal.So for integrating paypal in Asp.Net mvc we have to follow these steps :
First of all take one Asp.net mvc application and we will install paypal nuget package which is showed in the image below
After you have done installing paypal nuget package we will have to take one new controller where we will add paypal integration code. You have to add these namespaces on the controller
using PayPal.Api;
So, now we have to add these methods in our controller, this method will help us initialize payment and redirect to payment page
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["payment"]= 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["payment"] as string); //If executed payment failed then we will show payment failure message to user if (executedPayment.state.ToLower() != "approved") { return View("FailureView"); } else { //Testing Refund Session["SaleId"] = executedPayment.transactions[0].related_resources[0].sale.id; } } } catch (Exception ex) { return View("FailureView"); } //on successful payment, show success page to user. return View("SuccessView"); } public ActionResult InitiateRefund() { APIContext apiContext = PaypalConfiguration.GetAPIContext(); CreateRefundRequest(apiContext); return View("SuccessView"); } private void CreateRefundRequest(APIContext apiContext) { Sale CheckTheSale = new Sale(); DetailedRefund refundforreal = new DetailedRefund(); var saleId = Convert.ToString(Session["SaleId"]); CheckTheSale = Sale.Get(apiContext, saleId); string MaxAmountToRefund = CheckTheSale != null ? CheckTheSale.amount.total : "0"; Amount refundAmount = new Amount(); decimal NumericTotal = Convert.ToDecimal(MaxAmountToRefund) * 1; refundAmount.total = NumericTotal.ToString(); string RefundCurrency = "USD"; refundAmount.currency = RefundCurrency; RefundRequest refund = new RefundRequest(); refund.description = "Returned items."; refund.reason = "Refund Demo"; refund.amount = refundAmount; try { // Refund sale refundforreal = Sale.Refund(apiContext, saleId, refund); } catch (Exception ex) { } } 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 = "1", // 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 = Guid.NewGuid().ToString(), //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); }
After this now you have to go to models folder and add new class file PaypalConfiguration.cs . And add following code there
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() { ClientId = ConfigurationManager.AppSettings["clientId"]; ClientSecret = ConfigurationManager.AppSettings["clientSecret"]; } // getting properties from the web.config public static Dictionary<string, string> GetConfig() { return new Dictionary<string, string>() { {"mode","sandbox"} //Change sendbox to live for production }; } private static string GetAccessToken() { // getting accesstocken from paypal string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, new Dictionary<string, string>() { {"mode","sandbox"} //Change sendbox to live for production }).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 go to your web config file and add two appsettings for clientid and client secret
<add key="clientId" value="AfIlrsSZiFGFGi0K2VIUrfLObfNvqtCT2mcBvNUxgLTxPUs_o21gVTjoggSpYFcF2hqkMhfVUSqCv1w"/> <add key="clientSecret" value="ECeFFQaGnAPzbtq1mNvyZPTUIrZxfsA-XJlZgrDwjJSI1hj1lqT5r1nISJLYeR2xwBarEg5Mq4n18Lm7"/>
Here , please replace the credentials with your original credentials.
Now add one view and add following code there for payment button
<a class="btn btn-primary" href="/Home/PaymentWithPaypal">Pay Now</a>
Add new view SuccessView.cshtml and Add following code on the view for refund
<div class="row"> <a class="btn btn-primary" href="/Home/InitiateRefund">Refund</a> </div>
Now, we have to run the application and you will see this
Click on the button and it will call Action PaymentWithPaypal on HomeController. Now , it will create one default item and redirect on the payment page as showed below
Now click on Pay with credit or debit card button and it will redirect on a screen where you will have to add card details.
You can fill the follow details in here for sandbox testing
Country - United States Card Type: Visa Card Number: 4032034155351326 Expiration Date: 09/24 CVV: 275 Street: 4790 Deer Haven Drive City: Greenville State/province/area: South Carolina Phone number 864-353-5437 Zip code 29601 Country calling code +1
Now click on continue as guest and it will hit back the same method Here , you can add a breakpoint and check if your payment is approved
Now click on refund on the following success screen to initiate refund transaction
Now you can check in the code that refund process has been completed
Now you can login to paypal dashboard and check the refund transaction
For, production environment you can use
// getting properties from the web.config public static Dictionary<string, string> GetConfig() { return new Dictionary<string, string>() { {"mode","live"} //Change sendbox to live for production
}; } private static string GetAccessToken() { // getting accesstocken from paypal string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, new Dictionary<string, string>() { {"mode","live"} //Change sendbox to live for production }).GetAccessToken(); return accessToken; }
So after changing the mode you just have to set live credentials in web.config and you will be able to use this on production .
This is how we can have paypal integration in Asp.net MVC and learn How to refund payment using Paypal in Asp.Net MVC or initiate refund using paypal.