I blog at http://rajeshpillai.net and have a community startup http://ownabook.org/
(Don't forget to click "Mark as Answer" on the post(s) that helped you.)
Those are great for posting data to PayPal. My issue is how to handle data from PayPal. Website -> PayPal , PayPal -> website. My issues are in the second part . Thanks
Please go trough Getting Started with PayPal and ASP.net. Note that he mentions examples. Yep! They are available to download and you can learn from them too.
Happy coding and don't give up!
Please "Mark As Answer" if the post helped you.
mitja.gti | www.mitjagti.com
ironman99
Member
76 Points
80 Posts
MVC and paypal
Aug 17, 2012 08:58 PM|LINK
Hi, I've been trying to get paypal implemented in my site for about two weeks now. It's been a pain!!! I like this tutorial http://www.asp.net/mvc/videos/mvc-1/aspnet-mvc-storefront/aspnet-mvc-storefront-part-22-restructuring-rerouting-and-paypal , but I'm frustrated because he starts out using IPN and then goes into using PDT but never explains how he implemented it.
I'm able to post values to paypal, but actually recieving anything back from paypal has been my hang up.
here is what I've tried:
public ActionResult IPN() { var formVals = new Dictionary<string, string>(); formVals.Add("cmd", "_notify-validate"); string response = GetPayPalResponse(formVals, true); if (response == "VERIFIED") { string transactionID = Request["txn_id"]; string sAmountPaid = Request["mc_gross"]; string orderID = Request["custom"]; //_logger.Info("IPN Verified for order " + orderID); //validate the order Decimal amountPaid = 0; Decimal.TryParse(sAmountPaid, out amountPaid); //Order order = _orderService.GetOrder(new Guid(orderID)); //Order order = null; //check the amount paid ProcessedItems order = null; if (AmountPaidIsValid(order, amountPaid)) { int itmNum; order.OrderID = GetPDTValue(response, "custom"); order.Name = GetPDTValue(response, "first_name") + GetPDTValue(response, "last_name"); bool result = Int32.TryParse(GetPDTValue(response, "item_number"), out itmNum); if (true == result) order.ProductID = itmNum; order.Line1 = GetPDTValue(response, "address_street"); order.City = GetPDTValue(response, "address_city"); order.State = GetPDTValue(response, "address_state"); order.Country = GetPDTValue(response, "address_country"); order.Zip = GetPDTValue(response, "address_zip"); order.Status = "Paid"; //process it try { //_pipeline.AcceptPalPayment(order, transactionID, amountPaid); //_logger.Info("IPN Order successfully transacted: " + orderID); return RedirectToAction("RedirectFromPayPal"); } catch { //HandleProcessingError(order, x); return View(); } } else { //let fail - this is the IPN so there is no viewer } } return View(); } /// <summary> /// Handles the PDT Response from PayPal /// </summary> /// <returns></returns> public ActionResult PDT() { //_logger.Info("PDT Invoked"); string transactionID = Request.QueryString["tx"]; string sAmountPaid = Request.QueryString["amt"]; string orderID = Request.QueryString["cm"]; var formVals = new Dictionary<string, string>(); formVals.Add("cmd", "_notify-synch"); formVals.Add("at", "id goes here"); formVals.Add("tx", transactionID); string response = GetPayPalResponse(formVals, true); //_logger.Info("PDT Response received: " + response); if (response.StartsWith("SUCCESS")) { //_logger.Info("PDT Response received for order " + orderID); //validate the order Decimal amountPaid = 0; Decimal.TryParse(sAmountPaid, out amountPaid); ProcessedItems order = null; //Order order = null; if (AmountPaidIsValid(order, amountPaid)) { int itmNum; order.OrderID = GetPDTValue(response, "custom"); order.Name = GetPDTValue(response, "first_name") + GetPDTValue(response, "last_name"); bool result= Int32.TryParse(GetPDTValue(response, "item_number"), out itmNum); if(true == result) order.ProductID = itmNum; order.Line1 = GetPDTValue(response, "address_street"); order.City = GetPDTValue(response, "address_city"); order.State = GetPDTValue(response, "address_state"); order.Country = GetPDTValue(response, "address_country"); order.Zip = GetPDTValue(response, "address_zip"); order.Status = "Paid"; processedItems.SaveItem(order); //var add = new Address(); //add.FirstName = GetPDTValue(response, "first_name"); //add.LastName = GetPDTValue(response, "last_name"); //add.Email = GetPDTValue(response, "payer_email"); //add.Street1 = GetPDTValue(response, "address_street"); //add.City = GetPDTValue(response, "address_city"); //add.StateOrProvince = GetPDTValue(response, "address_state"); //add.Country = GetPDTValue(response, "address_country"); //add.Zip = GetPDTValue(response, "address_zip"); //add.UserName = order.UserName; //process it try { // _pipeline.AcceptPalPayment(order, transactionID, amountPaid); // _logger.Info("PDT Order successfully transacted: " + orderID); return RedirectToAction("RedirectFromPayPal"); } catch { //HandleProcessingError(order, x); return View(); } } else { //Payment amount is off //this can happen if you have a Gift cert at PayPal //be careful of this! //HandleProcessingError(order, new InvalidOperationException("Amount paid (" + amountPaid.ToString("C") + ") was below the order total")); return View(); } } else { ViewData["message"] = "Your payment was not successful with PayPal"; return View(); } } /// <summary> /// Utility method for handling PayPal Responses /// </summary> private string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox) { string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr"; var req = (HttpWebRequest) WebRequest.Create(paypalUrl); // Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); var sb = new StringBuilder(); sb.Append(strRequest); foreach (string key in formVals.Keys) { sb.AppendFormat("&{0}={1}", key, formVals[key]); } strRequest += sb.ToString(); req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://urlort#"); //req.Proxy = proxy; //Send the request to PayPal and get the response string response = ""; using (var streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII)) { streamOut.Write(strRequest); streamOut.Close(); using (var streamIn = new StreamReader(req.GetResponse().GetResponseStream())) { response = streamIn.ReadToEnd(); } } return response; } private bool AmountPaidIsValid(ProcessedItems order, decimal amountPaid) { //pull the order bool result = true; if (order != null) { if (order.Price > amountPaid) { //_logger.Warn("Invalid order amount to PDT/IPN: " + order.ID + "; Actual: " + amountPaid.ToString("C") + "; Should be: " + order.Total.ToString("C") + "user IP is " + Request.UserHostAddress); result = false; } } else { //_logger.Warn("Invalid order ID passed to PDT/IPN; user IP is " + Request.UserHostAddress); } return result; } private string GetPDTValue(string pdt, string key) { string[] keys = pdt.Split('\n'); string thisVal = ""; string thisKey = ""; foreach (string s in keys) { string[] bits = s.Split('='); if (bits.Length > 1) { thisVal = bits[1]; thisKey = bits[0]; if (thisKey.Equals(key, StringComparison.InvariantCultureIgnoreCase)) break; } } return thisVal; }@using System.Configuration @using SportsStore.Domain.Entities @model SportsStore.WebUI.Models.CartIndexViewModel @{ ViewBag.Title = "PostToPayPal"; int itemCount = 0; //var processedItem = new SportsStore.Domain.Entities.ProcessedItems(); //var customID = processedItem.GenerateId(); } <h2>Order Details</h2> <div style="width: 900px"> <div style="float: left; width: 500px"> <h3>Cart</h3> <table width="90%" align="center"> <thead> <tr> <th align="center">Quantity</th> <th align="left">Item</th> <th align="right">Price</th> <th align="right">Subtotal</th> </tr> </thead> <tbody> @foreach (CartLine line in Model.Cart.Lines) { <tr> <td align="center">@line.Quantity</td> <td align="left">@line.Product.Name</td> <td align="right">@line.Product.Price.ToString("c")</td> <td align="right">@((line.Quantity*line.Product.Price).ToString("c"))</td> </tr> } </tbody> <tfoot> <tr> <td colspan="3" align="right">Total:</td> <td align="right"> @Model.Cart.ComputeTotalValue().ToString("c") </td> </tr> </tfoot> </table> </div> <div style="float: right; width: 400px"> <h3>Shipping Information</h3> <table width="90%" align="center"> <thead> <tr> <th align="center">Name</th> <th align="left">Address</th> <th align="right">City</th> <th align="right">State</th> <th align="right">Zip</th> </tr> </thead> <tbody> <tr> <td align="center">@Model.ShippingDetails.Name</td> <td align="left">@Model.ShippingDetails.Line1</td> <td align="right">@Model.ShippingDetails.City</td> <td align="right">@Model.ShippingDetails.State</td> <td align="right">@Model.ShippingDetails.Zip</td> </tr> </tbody> <tfoot> <tr> </tr> </tfoot> </table> </div> </div> <form id="Paypal" name="Paypal" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="POST"> @Html.Hidden("cmd", "_cart") @Html.Hidden("upload", "1") @Html.Hidden("business", ConfigurationManager.AppSettings["BusinessAccountKey"]) @Html.Hidden("custom", Model.OrderID) @* @Html.Hidden("tax_cart",)*@ @Html.Hidden("currency_code", ConfigurationManager.AppSettings["CurrencyCode"]) @Html.Hidden("return", ConfigurationManager.AppSettings["ReturnURL"]) @Html.Hidden("cancel_return", ConfigurationManager.AppSettings["CancelURL"]) @Html.Hidden("first_name", Model.ShippingDetails.Name) @Html.Hidden("last_name", Model.ShippingDetails.Name) @Html.Hidden("address1", Model.ShippingDetails.Line1) @Html.Hidden("address2", Model.ShippingDetails.Line1) @Html.Hidden("city", Model.ShippingDetails.City) @Html.Hidden("state", Model.ShippingDetails.State) @Html.Hidden("country", Model.ShippingDetails.Country) @Html.Hidden("zip", Model.ShippingDetails.Zip) @foreach (CartLine item in Model.Cart.Lines) { itemCount++; @Html.Hidden("item_name_" + itemCount.ToString(), item.Product.Name) @Html.Hidden("item_number_" + itemCount.ToString(), item.Product.ProductID) @Html.Hidden("amount_" + itemCount.ToString(), item.Product.Price.ToString()) @Html.Hidden("quantity_" + itemCount.ToString(), item.Quantity.ToString()) @Html.Hidden("shipping_" + itemCount.ToString(), item.Product.Price.ToString()) @Html.Hidden("handling_" + itemCount.ToString(), 0) } <div style="margin-top: 50px; float: right;"> <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"/> </div> </form>thinkrajesh
Participant
1356 Points
232 Posts
Re: MVC and paypal
Aug 18, 2012 09:07 AM|LINK
Until anyone response with accurate answer, the following posts may be helpful.
http://www.superstarcoders.com/blogs/posts/paypal-with-asp-net-mvc.aspx
Paypal Express checkout...
http://www.arunrana.net/2012/01/paypal-integration-in-mvc3-and-razor.html
(Don't forget to click "Mark as Answer" on the post(s) that helped you.)
ironman99
Member
76 Points
80 Posts
Re: MVC and paypal
Aug 18, 2012 11:12 PM|LINK
paypal integration mvc
mitja.GTI
Star
11157 Points
2094 Posts
Re: MVC and paypal
Aug 18, 2012 11:43 PM|LINK
Please go trough Getting Started with PayPal and ASP.net. Note that he mentions examples. Yep! They are available to download and you can learn from them too.
Happy coding and don't give up!
mitja.gti | www.mitjagti.com