This article discusses integration of PayPal payment gateway in MVC  web application. PayPal is an online payment service that allows you to pay for purchases, receive payments, or to send and receive money. To receive these services, a person must submit various financial details to PayPal, such as credit card number, transmission can be done by mail. Thereafter, transactions are conducted without having to disclose financial details, an email address and a password is sufficient.

We will look at a simple scenario of taking a user to a PayPal payment page to checkout.

1. Setting up the development tools

  • Creating a PayPal Account

You will need a sandbox account to test your transactions. The sandbox account is separate from a regular account and is all you need to sign up to before you develop and test your code.

  • PayPal Account Settings

It's good practice to put things like account settings in the web.config. The code in this article will access these settings. You must change the sandbox setting to False when using regular account details:

   <add key="PayPal:Sandbox" value="True" />
   <add key="PayPal:Username" value="*" />
   <add key="PayPal:Password" value="*" />
   <add key="PayPal:Signature" value="*" />
   <add key="PayPal:ReturnUrl" value="" />
   <add key="PayPal:CancelUrl" value="" />

2. Creating the button
Now, you will have to create two Views in a Controller, one where you have the button and one where you have the validation mechanism. Let’s start with the button! Put the code below into any View. My View name is IPN in the User controller.
<!-- When you are done with all testing and want to change to the real PayPal, use following instead-->
<form action="" method="post">
<!-- end of Real PayPal example-->
<form action="" method="post">
        <input class="full-width" type="hidden" name="business" value="<!--enter the Business account email here-->">
        <input type="hidden" name="cmd" value="_xclick">
        <input type="hidden" name="item_name" value="The unlimited music download subscription">
        <input type="hidden" name="amount" value="9">
        <input type="hidden" name="no_shipping" value="1">
        <input type=hidden name=RETURNURL
        <input type="hidden" name="return" value="">
        <input type="hidden" name="notify_url" value="">
        <button type="submit">Order now!</button>

3. Processing the information returned by PayPal

The example code is based on this code. Please take a look at it to see how it is done with several variables.

Now you need to create a new View in the controller, called IPN. Insert the following code:
public ActionResult IPN()
    var order = new Order(); // this is something I have defined in order to save the order in the database
    // Receive IPN request from PayPal and parse all the variables returned
    var formVals = new Dictionary<string, string>();
    formVals.Add("cmd", "_notify-synch"); //notify-synch_notify-validate
    formVals.Add("at", "this is a long token found in Buyers account"); // this has to be adjusted
    formVals.Add("tx", Request["tx"]);
    // if you want to use the PayPal sandbox change this from false to true
    string response = GetPayPalResponse(formVals, false);
    if (response.Contains("SUCCESS"))
        string transactionID = GetPDTValue(response, "txn_id"); // txn_id //d
        string sAmountPaid = GetPDTValue(response,"mc_gross"); // d
        string deviceID = GetPDTValue(response, "custom"); // d
        string payerEmail = GetPDTValue(response,"payer_email"); // d
        string Item = GetPDTValue(response,"item_name");
        //validate the order
        Decimal amountPaid = 0;
        Decimal.TryParse(sAmountPaid, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out amountPaid);
        if (amountPaid == 9 )  // you might want to have a bigger than or equal to sign here!
            if (orders.Count(d => d.PayPalOrderRef == transactionID) < 1)
                //if the transactionID is not found in the database, add it
                //then, add the additional features to the user account
                //if we are here, the user must have already used the transaction ID for an account
                //you might want to show the details of the order, but do not upgrade it!
            // take the information returned and store this into a subscription table
            // this is where you would update your database with the details of the tran
            //return View();
            // let fail - this is the IPN so there is no viewer
            // you may want to log something here
            order.Comments = "User did not pay the right ammount.";
            // since the user did not pay the right amount, we still want to log that for future reference.
            _db.Orders.Add(order); // order is your new Order
    return View();
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
    string paypalUrl = useSandbox ? ""
        : "";
    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();
    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 (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
        using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
            response = streamIn.ReadToEnd();
    return response;
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))
    return thisVal;

Please note down the Activation token found in the Buyers account in Profile>My Selling Tools>Website preferences> Update. Then, enable auto return and payment data transfer. There, you will also find the Activation token which you should add to:
formVals.Add("at", "this is a long token found in Buyers account");


Why you should choose for your Cheap ASP.NET MVC 5.1.1 Hosting?

  1. Daily Backup Service

    We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it.

  2. Experts in ASP.NET MVC 5.1.1 Hosting

    Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up

  3. Excellent Uptime Rate

    Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP.

  4. 24/7-based Support

    We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers.

  5. Advanced Technology provides various editions of the important ASP.NET MVC frameworks, including basic ASP.NET MVC, ASP.NET MVC 2, ASP.NET MVC 3, ASP.NET MVC 4, ASP.NET MVC 5, ASP.NET MVC 5.1 and the latest ASP.NET MVC 5.1.1 . All of these frameworks enable customers to have a high level of flexibility and avoid compatible issue.