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.
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.
- <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 and name it PaypalConfiguration and add the below code.
- public static class PaypalConfiguration {
-
- public readonly static string ClientId;
- public readonly static string ClientSecret;
-
- static PaypalConfiguration() {
- var config = GetConfig();
- ClientId = config["clientId"];
- ClientSecret = config["clientSecret"];
- }
-
- public static Dictionary < string, string > GetConfig() {
- return PayPal.Api.ConfigManager.Instance.GetProperties();
- }
- private static string GetAccessToken() {
-
- string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();
- return accessToken;
- }
- public static APIContext GetAPIContext() {
-
- APIContext apiContext = new APIContext(GetAccessToken());
- apiContext.Config = GetConfig();
- return apiContext;
- }
- }
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.
- public ActionResult PaymentWithPaypal(string Cancel = null) {
-
- APIContext apiContext = PaypalConfiguration.GetAPIContext();
- try {
-
-
- string payerId = Request.Params["PayerID"];
- if (string.IsNullOrEmpty(payerId)) {
-
-
-
-
- string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Home/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) {
- return View("FailureView");
- }
-
- 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 = "1",
- quantity = "1",
- sku = "sku"
- });
- var payer = new Payer() {
- payment_method = "paypal"
- };
-
- var redirUrls = new RedirectUrls() {
- cancel_url = redirectUrl + "&Cancel=true",
- return_url = redirectUrl
- };
-
- var details = new Details() {
- tax = "1",
- shipping = "1",
- subtotal = "1"
- };
-
- var amount = new Amount() {
- currency = "USD",
- total = "3",
- details = details
- };
- var transactionList = new List < Transaction > ();
-
- transactionList.Add(new Transaction() {
- description = "Transaction description",
- invoice_number = "your generated invoice number",
- amount = amount,
- item_list = itemList
- });
- this.payment = new Payment() {
- intent = "sale",
- payer = payer,
- transactions = transactionList,
- redirect_urls = redirUrls
- };
-
- return this.payment.Create(apiContext);
- }
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.