hubert17

Paypal Rest API Integration ASP.NET C#

Jan 20th, 2018
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 24.71 KB | None | 0 0
  1. using OrderFramework.Paypal;
  2. using OrderFramework.ViewModels;
  3. using PayPal.Api;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.Linq;
  8. using System.Web;
  9. using System.Web.Mvc;
  10.  
  11. namespace OrderFramework.Controllers
  12. {
  13.     public class PaypalController : Controller
  14.     {
  15.         public ActionResult GetPaypalVault(string CreditCardId)
  16.         {
  17.             var vault = PaypalVault.GetCreditCardDetailsFromVault(CreditCardId);
  18.             return Json(vault, JsonRequestBehavior.AllowGet);
  19.  
  20.         }
  21.  
  22.         public ActionResult PaymentWithCreditCard(string CreditCardId = "")
  23.         {
  24.             var pvm = PaypalViewModel.GetSamplePayment("yuberto.gabon@outlook.com");
  25.  
  26.             var apiContext = PayPalConfig.GetAPIContext();
  27.  
  28.             // A transaction defines the contract of a payment.
  29.             var transaction = new Transaction()
  30.             {
  31.                 amount = new Amount()
  32.                 {
  33.                     currency = pvm.Transaction.Amount.Currency,
  34.                     total = pvm.Transaction.Amount.Total,
  35.                     details = new Details()
  36.                     {
  37.                         shipping = pvm.Transaction.Amount.Detail.Shipping,
  38.                         subtotal = pvm.Transaction.Amount.Detail.Subtotal,
  39.                         tax = pvm.Transaction.Amount.Detail.Tax
  40.                     }
  41.                 },
  42.                 description = pvm.Transaction.Description,
  43.                 item_list = new ItemList()
  44.                 {
  45.                     items = pvm.Transaction.ItemList.Select(s => new Item
  46.                     {
  47.                         name = s.Name,
  48.                         currency = s.Currency,
  49.                         price = s.Price,
  50.                         quantity = s.Quantity,
  51.                         sku = s.Sku
  52.                     }).ToList(),
  53.                     shipping_address = new ShippingAddress
  54.                     {
  55.                         city = pvm.Transaction.ShippingAddress.City,
  56.                         country_code = pvm.Transaction.ShippingAddress.CountryCodeDomain,
  57.                         line1 = pvm.Transaction.ShippingAddress.AddressLine,
  58.                         postal_code = pvm.Transaction.ShippingAddress.PostalCode,
  59.                         state = pvm.Transaction.ShippingAddress.State,
  60.                         recipient_name = pvm.Transaction.ShippingAddress.RecipientName
  61.                     }
  62.                 },
  63.                 invoice_number = String.IsNullOrEmpty(pvm.Transaction.InvoiceNumber) ? GetRandomInvoiceNumber() : pvm.Transaction.InvoiceNumber
  64.             };
  65.  
  66.             // A resource representing a Payer that funds a payment.
  67.             var payer = new Payer()
  68.             {
  69.                 payment_method = "credit_card",
  70.                 payer_info = new PayerInfo
  71.                 {
  72.                     email = pvm.Payer.PayerInfo.Email
  73.                 }
  74.             };
  75.  
  76.             if(String.IsNullOrEmpty(CreditCardId))
  77.             {
  78.                 payer.funding_instruments = new List<FundingInstrument>()
  79.                 {
  80.                     new FundingInstrument()
  81.                     {
  82.                         credit_card = new CreditCard()
  83.                         {
  84.                             billing_address = new Address()
  85.                             {
  86.                                 city = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.City,
  87.                                 country_code = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.CountryCodeDomain,
  88.                                 line1 = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.AddressLine,
  89.                                 postal_code = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.PostalCode,
  90.                                 state = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.State
  91.                             },
  92.                             cvv2 = pvm.Payer.FundingInstrument.CreditCard.Cvv2,
  93.                             expire_month = pvm.Payer.FundingInstrument.CreditCard.ExpireMonth,
  94.                             expire_year = pvm.Payer.FundingInstrument.CreditCard.ExpireYear,
  95.                             first_name = pvm.Payer.FundingInstrument.CreditCard.FirstName,
  96.                             last_name = pvm.Payer.FundingInstrument.CreditCard.LastName,
  97.                             number = pvm.Payer.FundingInstrument.CreditCard.CcNumber,
  98.                             type = pvm.Payer.FundingInstrument.CreditCard.CcType
  99.                         }
  100.                     }
  101.                 };
  102.  
  103.                 CreditCardId = PaypalVault.StoreCreditCardInPaypal(pvm.Payer.FundingInstrument.CreditCard);
  104.             }
  105.             else
  106.             {
  107.                 //Here, we are assigning the User's Credit Card ID which we saved in Database
  108.                 payer.funding_instruments = new List<FundingInstrument>()
  109.                 {
  110.                     new FundingInstrument()
  111.                     {
  112.                         credit_card_token = new CreditCardToken
  113.                         {
  114.                             credit_card_id = CreditCardId
  115.                         }
  116.                     }
  117.                 };
  118.  
  119.             }
  120.  
  121.  
  122.             // A Payment resource; create one using the above types and intent as `sale` or `authorize`
  123.             var payment = new PayPal.Api.Payment()
  124.             {
  125.                 intent = "sale",
  126.                 payer = payer,
  127.                 transactions = new List<Transaction>() { transaction }
  128.             };
  129.  
  130.             // ^ Ignore workflow code segment
  131.             #region Track Workflow
  132.             //this.flow.AddNewRequest("Create credit card payment", payment);
  133.             #endregion
  134.  
  135.             // Create a payment using a valid APIContext
  136.             var createdPayment = payment.Create(apiContext);
  137.  
  138.             // ^ Ignore workflow code segment
  139.             #region Track Workflow
  140.             //this.flow.RecordResponse(createdPayment);
  141.             #endregion
  142.  
  143.             if (createdPayment.state.ToLower() != "approved")
  144.             {
  145.                 //return View("FailureView");
  146.                 return Content("Failed");
  147.             }
  148.  
  149.             return Content("Success Id: " + CreditCardId);
  150.  
  151.             // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
  152.         }
  153.  
  154.         public ActionResult PaymentWithPaypal(PaypalViewModel pvm)
  155.         {
  156.             pvm = PaypalViewModel.GetSamplePayment();
  157.  
  158.             //getting the apiContext as earlier
  159.             APIContext apiContext = PayPalConfig.GetAPIContext();
  160.  
  161.             try
  162.             {
  163.                 string payerId = Request.Params["PayerID"];
  164.  
  165.                 if (string.IsNullOrEmpty(payerId))
  166.                 {
  167.                     //this section will be executed first because PayerID doesn't exist
  168.                     //it is returned by the create function call of the payment class
  169.  
  170.                     // Creating a payment
  171.                     // baseURL is the url on which paypal sendsback the data.
  172.                     // So we have provided URL of this controller only
  173.                     //
  174.                     string baseURI = Request.Url.GetLeftPart(UriPartial.Authority)  // Request.Url.Scheme + "://" + Request.Url.Authority
  175.                         + "/" + Url.Action("PaymentWithPayPal","Paypal", new { area = "OrderFramework" }) + "?";
  176.  
  177.                     //guid we are generating for storing the paymentID received in session
  178.                     //after calling the create function and it is used in the payment execution
  179.  
  180.                     var guid = Convert.ToString((new Random()).Next(100000));
  181.  
  182.                     //CreatePayment function gives us the payment approval url
  183.                     //on which payer is redirected for paypal account payment
  184.  
  185.                     var createdPayment = this.CreatePayment(pvm, apiContext, baseURI + "guid=" + guid);
  186.  
  187.                     //get links returned from paypal in response to Create function call
  188.  
  189.                     var links = createdPayment.links.GetEnumerator();
  190.  
  191.                     string paypalRedirectUrl = null;
  192.  
  193.                     while (links.MoveNext())
  194.                     {
  195.                         Links lnk = links.Current;
  196.  
  197.                         if (lnk.rel.ToLower().Trim().Equals("approval_url"))
  198.                         {
  199.                             //saving the payapalredirect URL to which user will be redirected for payment
  200.                             paypalRedirectUrl = lnk.href;
  201.                         }
  202.                     }
  203.  
  204.                     // saving the paymentID in the key guid
  205.                     Session.Add(guid, createdPayment.id);
  206.  
  207.                     return Redirect(paypalRedirectUrl);
  208.                 }
  209.                 else
  210.                 {
  211.                     // This section is executed when we have received all the payments parameters
  212.  
  213.                     // from the previous call to the function Create
  214.  
  215.                     // Executing a payment
  216.  
  217.                     var guid = Request.Params["guid"];
  218.  
  219.                     var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
  220.  
  221.                     if (executedPayment.state.ToLower() != "approved")
  222.                     {
  223.                         return Content("Failed");
  224.                     }
  225.                 }
  226.             }
  227.             catch (Exception ex)
  228.             {
  229.                 //Logger.log("Error" + ex.Message);
  230.                 //return View("FailureView");
  231.                 return Content("Failed");
  232.             }
  233.  
  234.             //return View("SuccessView");
  235.             return Content("Success");
  236.         }
  237.  
  238.         #region PaypalMethods
  239.         private Payment payment;
  240.         private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
  241.         {
  242.             var paymentExecution = new PaymentExecution() { payer_id = payerId };
  243.             this.payment = new Payment() { id = paymentId };
  244.             return this.payment.Execute(apiContext, paymentExecution);
  245.         }
  246.  
  247.         private Payment CreatePayment(PaypalViewModel pvm, APIContext apiContext, string redirectUrl)
  248.         {
  249.             var payer = new Payer() { payment_method = "paypal" };
  250.  
  251.             // Configure Redirect Urls here with RedirectUrls object
  252.             var redirUrls = new RedirectUrls()
  253.             {
  254.                 cancel_url = redirectUrl,
  255.                 return_url = redirectUrl
  256.             };
  257.  
  258.  
  259.             //similar to credit card create itemlist and add item objects to it
  260.             var itemList = new ItemList()
  261.             {
  262.                 items = pvm.Transaction.ItemList.Select(s => new Item
  263.                 {
  264.                     name = s.Name,
  265.                     currency = s.Currency,
  266.                     price = s.Price,
  267.                     quantity = s.Quantity,
  268.                     sku = s.Sku
  269.                 }).ToList()
  270.             };
  271.  
  272.             // similar as we did for credit card, do here and create details object
  273.             var details = new Details()
  274.             {
  275.                 tax = pvm.Transaction.Amount.Detail.Tax,
  276.                 shipping = pvm.Transaction.Amount.Detail.Shipping,
  277.                 subtotal = pvm.Transaction.Amount.Detail.Subtotal
  278.             };
  279.  
  280.             // similar as we did for credit card, do here and create amount object
  281.             var amount = new Amount()
  282.             {
  283.                 currency = pvm.Transaction.Amount.Currency,
  284.                 total = pvm.Transaction.Amount.Total, // Total must be equal to sum of shipping, tax and subtotal.
  285.                 details = details
  286.             };
  287.  
  288.             var transactionList = new List<Transaction>();
  289.  
  290.             transactionList.Add(new Transaction()
  291.             {
  292.                 description = pvm.Transaction.Description,
  293.                 invoice_number = String.IsNullOrEmpty(pvm.Transaction.InvoiceNumber) ? GetRandomInvoiceNumber() : pvm.Transaction.InvoiceNumber,
  294.                 amount = amount,
  295.                 item_list = itemList
  296.             });
  297.  
  298.             this.payment = new Payment()
  299.             {
  300.                 intent = "sale",
  301.                 payer = payer,
  302.                 transactions = transactionList,
  303.                 redirect_urls = redirUrls
  304.             };
  305.  
  306.             // Create a payment using a APIContext
  307.             return this.payment.Create(apiContext);
  308.  
  309.         }
  310.  
  311.         /// <summary>
  312.         /// Gets a random invoice number to be used with a sample request that requires an invoice number.
  313.         /// </summary>
  314.         /// <returns>A random invoice number in the range of 0 to 999999</returns>
  315.         private string GetRandomInvoiceNumber()
  316.         {
  317.             return new Random().Next(999999).ToString();
  318.         }
  319.         #endregion
  320.     }
  321.  
  322. }
  323.  
  324. namespace OrderFramework.Paypal
  325. {
  326.     public static class PayPalConfig
  327.     {
  328.         public readonly static string ClientId;
  329.         public readonly static string ClientSecret;
  330.  
  331.         // Static constructor for setting the readonly static members.
  332.         static PayPalConfig()
  333.         {
  334.             ClientId = ConfigurationManager.AppSettings["PaypalClientId"];
  335.             ClientSecret = ConfigurationManager.AppSettings["PaypalClientSecret"];
  336.         }
  337.  
  338.         // Create the configuration map that contains mode and other optional configuration details.
  339.         public static Dictionary<string, string> GetConfig()
  340.         {
  341.             return ConfigManager.Instance.GetProperties();
  342.         }
  343.  
  344.         // Create accessToken
  345.         private static string GetAccessToken()
  346.         {
  347.             // ###AccessToken
  348.             // Retrieve the access token from
  349.             // OAuthTokenCredential by passing in
  350.             // ClientID and ClientSecret
  351.             // It is not mandatory to generate Access Token on a per call basis.
  352.             // Typically the access token can be generated once and
  353.             // reused within the expiry window                
  354.             string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();
  355.             return accessToken;
  356.         }
  357.  
  358.         // Returns APIContext object
  359.         public static APIContext GetAPIContext(string accessToken = "")
  360.         {
  361.             // ### Api Context
  362.             // Pass in a `APIContext` object to authenticate
  363.             // the call and to send a unique request id
  364.             // (that ensures idempotency). The SDK generates
  365.             // a request id if you do not pass one explicitly.
  366.             var apiContext = new APIContext(string.IsNullOrEmpty(accessToken) ? GetAccessToken() : accessToken);
  367.             apiContext.Config = GetConfig();
  368.  
  369.             // Use this variant if you want to pass in a request id  
  370.             // that is meaningful in your application, ideally
  371.             // a order id.
  372.             // String requestId = Long.toString(System.nanoTime();
  373.             // APIContext apiContext = new APIContext(GetAccessToken(), requestId ));
  374.  
  375.             return apiContext;
  376.         }
  377.  
  378.     }
  379.  
  380.     public static class PaypalVault
  381.     {
  382.         // https://www.codeproject.com/Tips/886187/PayPal-REST-API-Recurring-Payment-via-Stored-Credi
  383.         // https://code.tutsplus.com/articles/paypal-integration-part-2-paypal-rest-api--cms-22917
  384.  
  385.         public static string StoreCreditCardInPaypal(PaypalViewModel._Payer._FundingInstrument._CreditCard cc)
  386.         {
  387.             //Creating the CreditCard Object and assigning values
  388.             var creditCard = new CreditCard
  389.             {
  390.                 expire_month = cc.ExpireMonth,
  391.                 expire_year = cc.ExpireYear,
  392.                 number = cc.CcNumber,
  393.                 type = cc.CcType,
  394.                 cvv2 = cc.Cvv2
  395.             };
  396.  
  397.             try
  398.             {
  399.                 //Getting the API Context to authenticate the call to Paypal Server
  400.                 APIContext apiContext = PayPalConfig.GetAPIContext();
  401.                 // Storing the Credit Card Info in the PayPal Vault Server
  402.                 CreditCard createdCreditCard = creditCard.Create(apiContext);
  403.  
  404.                 //Saving the User's Credit Card ID returned by the PayPal
  405.                 //You can use this ID for future payments via User's Credit Card
  406.                 //SaveCardID(User.Identity.Name, createdCreditCard.id);
  407.  
  408.                 return createdCreditCard.id;
  409.  
  410.             }
  411.             catch (PayPal.PayPalException ex)
  412.             {
  413.                 //Logger.LogError("Error: " + ex.Message);
  414.                 return ex.Message;
  415.             }
  416.             catch (Exception ex)
  417.             {
  418.                 //Logger.LogError("Error: " + ex.Message);
  419.                 return ex.Message;
  420.             }
  421.  
  422.         }
  423.  
  424.         public static CreditCard GetCreditCardDetailsFromVault(string creditCardId)
  425.         {
  426.             try
  427.             {
  428.                 //Getting the API Context to authenticate the call
  429.                 APIContext apiContext = PayPalConfig.GetAPIContext();
  430.  
  431.                 //Getting the Credit Card Details from paypal
  432.                 //By sending the Card ID saved at our end
  433.                 CreditCard card = CreditCard.Get(apiContext, creditCardId); // "CARD-00N04036H5458422MKRIAWHY"
  434.                 return card;
  435.             }
  436.             catch (PayPal.PayPalException ex)
  437.             {
  438.                 //Logger.LogError("Error: " + ex.Message);
  439.             }
  440.  
  441.             return null;
  442.         }
  443.  
  444.         public static bool DeleteCreditCardFromVault(string creditCardId)
  445.         {
  446.             try
  447.             {
  448.                 // Getting the API Context for authentication the call to paypal server
  449.                 APIContext apiContext = PayPalConfig.GetAPIContext();
  450.  
  451.                 //get the credit card from the vault to delete
  452.                 CreditCard card = CreditCard.Get(apiContext, creditCardId); // "CARD-00N04036H5458422MKRIAWHY"
  453.  
  454.                 // Delete the credit card
  455.                 card.Delete(apiContext);
  456.  
  457.                 return true;
  458.             }
  459.             catch (PayPal.PayPalException ex)
  460.             {
  461.                 //Logger.LogError("Error: " + ex.Message);
  462.                 return false;
  463.             }
  464.         }
  465.     }
  466.  
  467. }
  468.  
  469. namespace OrderFramework.ViewModels
  470. {
  471.     public class PaypalViewModel
  472.     {
  473.         public _Payer Payer { get; set; }
  474.         public _Transaction Transaction { get; set; }
  475.  
  476.         public class _Payer
  477.         {
  478.             public _PayerInfo PayerInfo { get; set; }
  479.             public _FundingInstrument FundingInstrument { get; set; }
  480.  
  481.             public class _PayerInfo
  482.             {
  483.                 public string Email { get; set; }
  484.             }
  485.  
  486.             public class _FundingInstrument
  487.             {
  488.                 public _CreditCard CreditCard { get; set; }
  489.                 public _CreditCardToken CreditCardToken { get; set; }
  490.                 public class _CreditCard
  491.                 {
  492.                     public string FirstName { get; set; }
  493.                     public string LastName { get; set; }
  494.                     public string CcType { get; set; }
  495.                     public string CcNumber { get; set; }
  496.                     public string Cvv2 { get; set; }
  497.                     public int ExpireMonth { get; set; }
  498.                     public int ExpireYear { get; set; }
  499.                     public _BillingAddress BillingAddress { get; set; }
  500.  
  501.                     public class _BillingAddress
  502.                     {
  503.                         public string City { get; set; }
  504.                         public string CountryCodeDomain { get; set; }
  505.                         public string AddressLine { get; set; }
  506.                         public string PostalCode { get; set; }
  507.                         public string State { get; set; }
  508.                     }
  509.                 }
  510.                 public class _CreditCardToken
  511.                 {
  512.                     public string CreditCardId { get; set; }
  513.                 }
  514.             }
  515.  
  516.         }
  517.  
  518.         public class _Transaction
  519.         {
  520.             public string Description { get; set; }
  521.             public string InvoiceNumber { get; set; }
  522.             public _Amount Amount { get; set; }
  523.             public List<_Item> ItemList { get; set; }
  524.             public _ShippingAddress ShippingAddress { get; set; }
  525.  
  526.             public class _Amount
  527.             {
  528.                 public string Currency { get; set; }
  529.                 public string Total { get; set; }
  530.                 public _Detail Detail { get; set; }
  531.                 public class _Detail
  532.                 {
  533.                     public string Shipping { get; set; }
  534.                     public string Subtotal { get; set; }
  535.                     public string Tax { get; set; }
  536.                 }
  537.             }
  538.             public class _Item
  539.             {
  540.                 public string Name { get; set; }
  541.                 public string Currency { get; set; }
  542.                 public string Price { get; set; }
  543.                 public string Quantity { get; set; }
  544.                 public string Sku { get; set; }
  545.             }
  546.             public class _ShippingAddress
  547.             {
  548.                 public string City { get; set; }
  549.                 public string CountryCodeDomain { get; set; }
  550.                 public string AddressLine { get; set; }
  551.                 public string PostalCode { get; set; }
  552.                 public string State { get; set; }
  553.                 public string RecipientName { get; set; }
  554.             }
  555.  
  556.         }
  557.  
  558.         public static PaypalViewModel GetSamplePayment(string buyerEmail = "")
  559.         {
  560.             var pvm = new PaypalViewModel
  561.             {
  562.                 Payer = new _Payer
  563.                 {
  564.                     PayerInfo = new _Payer._PayerInfo
  565.                     {
  566.                         Email = buyerEmail
  567.                     },
  568.                     FundingInstrument = new _Payer._FundingInstrument
  569.                     {
  570.                         CreditCard = new _Payer._FundingInstrument._CreditCard
  571.                         {
  572.                             FirstName = "Yuberto",
  573.                             LastName = "Gabs",
  574.                             CcType = "visa",
  575.                             CcNumber = "4032031018735885",
  576.                             ExpireMonth = 02,
  577.                             ExpireYear = 2022,
  578.                             Cvv2 = "000",
  579.                             BillingAddress = new _Payer._FundingInstrument._CreditCard._BillingAddress
  580.                             {
  581.                                 AddressLine = "Marigold st., Carmen",
  582.                                 City = "Cagayan De Oro",
  583.                                 State = "Misamis Oriental",
  584.                                 CountryCodeDomain = "PH",
  585.                                 PostalCode = "9000"
  586.                             }
  587.                         }
  588.                     }
  589.                 },
  590.                 Transaction = new _Transaction
  591.                 {
  592.                     Amount = new _Transaction._Amount
  593.                     {
  594.                         Currency = "USD",
  595.                         Total = "28",
  596.                         Detail = new _Transaction._Amount._Detail
  597.                         {
  598.                             Shipping = "1",
  599.                             Subtotal = "26",
  600.                             Tax = "1"
  601.                         }
  602.                     },
  603.                     Description = "Gabs Sari-sari Sample Transaction",
  604.                     ItemList = new List<_Transaction._Item>
  605.                     {
  606.                         new _Transaction._Item
  607.                         {
  608.                              Currency = "USD",
  609.                              Name = "Banana Cue",
  610.                              Price = "8",
  611.                              Quantity = "2",
  612.                              Sku = "44443333"
  613.                         },
  614.                         new _Transaction._Item
  615.                         {
  616.                              Currency = "USD",
  617.                              Name = "Binignit",
  618.                              Price = "10",
  619.                              Quantity = "1",
  620.                              Sku = "44445555"
  621.                         }
  622.                     },
  623.                     ShippingAddress = new _Transaction._ShippingAddress
  624.                     {
  625.                         RecipientName = "Julieta Dela Saluta",
  626.                         AddressLine = "RCPA Road, Purok 6-A, North Poblacion",
  627.                         City = "Maramag",
  628.                         State = "Bukidnon",
  629.                         CountryCodeDomain = "PH",
  630.                         PostalCode = "8714",
  631.                     }
  632.                 }
  633.             };
  634.  
  635.             return pvm;
  636.         }
  637.  
  638.     }
  639. }
Add Comment
Please, Sign In to add comment