Wednesday, September 14, 2011

PayPal and MVC

Recently i had an opportunity to implement paypal. At first it was way too overwhelming to read about it and implement it in a day or two. However, this video link  by Rob Conery cleared up lot of my confusion. I recommend seeing this video if you have any plans to implement paypal. So, PayPal SandBox  is the development site where you can test your code. All the code i have implemented is either in documentation or from the video.

//Controller

public class PayPalController : Controller
{
private const string Server_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";


public PayPalController()
{

}

public ActionResult Index()
{
MovieModel movieModel = new MovieModel();
movieModel.MovieDate = new List() {
new DateTime(2011,9,15).ToLongDateString()
};
movieModel.MovieTime = new List()
{
"12:00 PM","3:00 PM","7:00 PM","10:00 PM"
};
movieModel.NoOfTickets = new List() {1,2,3,4,5,6};
movieModel.Price = 15;
return View(movieModel);
}

public RedirectResult PostToPayPal(MovieModel movieModel)
{
string custom = GetTransactionFromDB(movieModel);
string cmd = "_xclick";
string business = "SELLEREMAIL";
string notify_url = "Localhost/PayPal/IPN";
int amount = movieModel.Price;
string item_name = "Ticket";
string redirect = string.Format("{0}&cmd={1}¬ify_url={2}&amount={3}&item_name={4}&custom={5}&business={6}",Server_URL,cmd,notify_url,amount,item_name,custom,business);
return Redirect(redirect);  
}

private string GetTransactionFromDB(MovieModel movieModel)
{
//store from model in DB and return transactionID
//store amount also,need to verify later.
return "123-234-5678";
}


public void IPN()
{
var formVals = new Dictionary();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
if (response == "VERIFIED")
{
string sAmountPaid = Request["mc_gross"];
string paymentStatus = Request["payment_status"];
string customField = Request["custom"];
if (sAmountPaid == GetPriceFromDatabase(id) && paymentStatus == "Completed")
{
string buyerEmail = Request["payer_email"];
string transactionID = Request["txn_id"];//PayPal Transaction ID(Store It)
string firstName = Request["first_name"];
string lastName = Request["last_name"];
//Call to SP saying Payment Processed
}
else
{
//Call to SP Saying Payment Corrupt or Invalid
}
}
else if (response == "INVALID")
{
//Call to SP Saying Payment Failed;
}
else
{
//Send Email to Admin with response details
}
}

private string GetPriceFromDatabase(string id)
{
return "15";
}



public string GetPayPalResponse(Dictionary formVals, bool useSandbox)
{

string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";


HttpWebRequest 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);

StringBuilder 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;

string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{

streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}

return response;
}


}
}


//View
<% using (Html.BeginForm("PostToPayPal", "PayPal", new { id= "Form" }))
   { %>
(Theatre Name)
Date: <%= Html.DropDownListFor(model => model.MovieDate,new SelectList(Model.MovieDate,Model.MovieDate.First())) %>
<%= Html.HiddenFor(model => model.Price, new { id = "Price" })%> <%= Html.HiddenFor(model => model.TheatreName, new { id = "TheatreName"}) %>
Time Tickets Price Buy With PayPal
<%= Html.DropDownListFor(model => model.MovieTime, new SelectList(Model.MovieTime, "3:00 PM"))%>
<%= Html.DropDownListFor(model => model.NoOfTickets, new SelectList(Model.NoOfTickets, 1), new { id = "Tickets" })%>

15$



<%} %>

Email me if you have questions. But like i said, the video has most of the explanation.

2 comments:

  1. Hi Friend i implemented this code in my project the transaction was successfully completed in pay pal page but get the response is invalid when redirect to website.

    ReplyDelete
  2. The compositions of this blog are sensational.
    Kucoin

    ReplyDelete