ASP.NET MVC PayPal Integration




ASP.NET MVC PayPal Integration

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.

for more information about business please visit official Paypal Website for business or https://developer.paypal.com/webapps/developer/docs/integration/direct/log-in-with-paypal/detailed/

In this tutorial we propose to integrate the PAYPAL  e-commerce payment solution.

So, we are using Visual studio C# and ASP.NET MVC4 (for more information about ASP.NET MVC please take a look at  http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

Ready ? Lets start our tutorial :

1. Open Visual studio 2012 or later and Create your Project

2.  Choose ASP.NET MVC4 Template Projet, Internet Application and Razor ViewEngine

1

3. Expand Model folder and Create a new Model named PayPalModel to hold PayPal payment parameters

1

Try it 

public class PayPalModel
{
public string cmd { get; set; }
public string business { get; set; }
public string no_shipping { get; set; }
public string @return { get; set; }
public string cancel_return { get; set; }
public string notify_url { get; set; }
public string currency_code { get; set; }
public string item_name { get; set; }
public string amount { get; set; }
public string actionURL { get; set; }

public PayPalModel(bool useSandbox)
{
this.cmd = “_xclick”;
this.business = ConfigurationManager.AppSettings[“business”];
this.cancel_return = ConfigurationManager.AppSettings[“cancel_return”];
this.@return = ConfigurationManager.AppSettings[“return”];
if (useSandbox)
{
this.actionURL = ConfigurationManager.AppSettings[“test_url”];
}
else
{
this.actionURL = ConfigurationManager.AppSettings[“Prod_url”];
}
// We can add parameters here, for example OrderId, CustomerId, etc….
this.notify_url = ConfigurationManager.AppSettings[“notify_url”];
// We can add parameters here, for example OrderId, CustomerId, etc….
this.currency_code = ConfigurationManager.AppSettings[“currency_code”];
}
}

4. Create a Paypal Controller

2

Try it :

public class PayPalController : Controller
{
public ActionResult RedirectFromPaypal()
{
return View();
}

public ActionResult CancelFromPaypal()
{
return View();
}

public ActionResult NotifyFromPaypal()
{
return View();
}

public ActionResult ValidateCommand(string product, string totalPrice)
{
return View();
}
}

5. Now Create a Partial View (ValidateCommand.csHtml)  to use our Model.  Do not forget that all fields must be of type hidden

3

try it :

@model PaypalMVC.Models.PayPalModel

<body>
<form id=”hiddenform” action=@Model.actionURL>
@Html.HiddenFor(model => model.cmd)
@Html.HiddenFor(model => model.business)
@Html.HiddenFor(model => model.no_shipping)
@Html.HiddenFor(model => model.@return)
@Html.HiddenFor(model => model.cancel_return)
@Html.HiddenFor(model => model.notify_url)
@Html.HiddenFor(model => model.currency_code)
@Html.HiddenFor(model => model.item_name)
@Html.HiddenFor(model => model.amount)
</form>

<p style=”text-align: center”>
<h3>
Connecting to Paypal , please wait …

</h3>
</p>
</body>
@Scripts.Render(“~/bundles/jquery”)

<script type=”text/javascript” language=”javascript”>
$(this.document).ready(function () {
var form = $(“form”);
form.submit();
});
</script>

6. Now finish our ValidateCommand action of PayPalController

4

try it :

public ActionResult ValidateCommand(string product, string totalPrice)
{
bool useSandbox = Convert.ToBoolean(ConfigurationManager.AppSettings[“IsSandbox”]);
var paypal = new PayPalModel(useSandbox);

paypal.item_name = product;
paypal.amount = totalPrice;
return View(paypal);
}

7. Note its important to secure our action post. So only user who have credentials are allowed to pay articles ( For more information about securing your asp.NET MVC internet application please have a look at our tutorial How to configure Custom Membership and Role Provider using ASP.NET MVC4

5

8. Next finish our partialView by adding a jquery code to auto submit our form. The necessary scripts are  Jquery-{version}.js and    Jquery-{version}.min.js. Here we are used  @Scripts.Render(“~/bundles/jquery”)  to include all Jquery scripts.  A more better practice will be to export all javascript functions to external file but the submit function must be called just after displaying hidden field of our  form

 6

9. The next step is to create our checkOut form that dispays product name , Quantity, price and Total :

So expand View folder , expand Home folder and open index.csHtml file. Replace its contents by the following

7

try it :

@{
ViewBag.Title = “Home Page”;
}
@using (Html.BeginForm(“ValidateCommand”, “PayPal”))
{
<div>
<table >
<tr>
<td>
product Name:
</td>
<td>
<input type=”text” name=”product” value=”Visual Studio 2013″ readonly />
</td>
</tr>
<tr>
<td>
Total Price:
</td>
<td>
$<input type=”text” name=”totalPrice” value=”14800″ readonly />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type=”submit” name=”btnConfirm” value=”Check Out with Paypal” />
</td>
</tr>
</table>
</div>
}

10. we are at the end. Our final step is to update the web.config file with the appropriate settngs

8

11. Now , lets go testing our solution :

12. Run the  application (or Press F5 )

9

13. Confirm payment by clicking on button Check Out With PayPal, then you will be redirected to the payment  page

10

We have this page error because, we have not yet an valid account.

Now it time to create a test account by following this link https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/ug_sandbox/#accounts

14. Open Web.config file and update business value with your test account

11

15. So run again your application. Confirm or Cancel , etc…

12

Hope this post are helped you.

Download Sample

Note : for PayBox Integration please visit our tutorial for Paybox













Gora LEYE

I’m a .NET Architect and Technical Expert skills located in Paris (FRANCE). The purpose of this blog is mainly to post general .NET tips and tricks,

56 thoughts on “ASP.NET MVC PayPal Integration

  • 7 October 2013 at 18 h 01 min
    Permalink

    Hello
    I following your code but i got the error
    “You have requested an outdated version of PayPal. This error often results from the use of bookmarks”
    Can you help me take a look on this?
    Thank in advance

    Reply
    • 8 October 2013 at 14 h 56 min
      Permalink

      The response i have got from PayPal :
      The cause and solution of this issue is dependent upon how you are integrated with PayPal this could be caused by one of the following.

      1.) If using the Outlook payment wizard this is caused by the wizard adding a space in between the “cmd” variable name and the associated “=”. For example:

      https://www.paypal.com/cgi-bin/webscr?cmd =_xclick

      To resolve this you would need to generate the button and insert it into your email. Than select the button image and click insert > hyperlink in the Outlook programs top menu. In here you can see and remove the space referenced prior to sending the email.

      2.) Or If using the PayPal standard buttons it can be caused by the enctype being passes. You will want to check your PayPal button code and see if it using an enctype=”multipart/form-data” in the opening FORM tag.

      Here is an example:
      Should be

      These are the known issues that cause this error. There are other generic coding issues that can cause this error so please let me know if the above does not resolve the issue for you. Also please reply to this ticket with the integration type that you are using so that I may attach this ticket to the escalation in order that you may receive notification when the issue is resolved.

      It is possible to send you my sample by email.
      Regards

      Reply
  • 10 October 2013 at 11 h 44 min
    Permalink

    Hi Master,
    i am getting an error like
    “You have requested an outdated version of PayPal. This error often results from the use of bookmarks.” this paypal site

    Reply
    • 13 October 2013 at 17 h 15 min
      Permalink

      Yi you can read my previous post or download sample at the end of totorial

      Reply
  • 18 October 2013 at 5 h 32 min
    Permalink

    Thanks , Just same wht i am looking for.
    Here facilitator means the one who receives payment right?
    tell me about IPN.

    Reply
  • 25 October 2013 at 6 h 46 min
    Permalink

    Hi as u written i have completed this but in “RedirectFromPaypal” i want Payment transactionid of user…please help me to solve this

    Reply
    • 9 November 2013 at 6 h 41 min
      Permalink

      Hi as u written i have completed this but in “RedirectFromPaypal” i want Payment transactionid of user…please help me to solve this

      Reply
      • 10 November 2013 at 21 h 34 min
        Permalink

        Hi, parameter tx contains the transactionId, so Request.Querystring[tx] must contains the transaction id if payment is succees
        Regards

        Reply
  • 25 October 2013 at 12 h 16 min
    Permalink

    Thanks for the article; just wondering you to integrate paypal in a ASP.NET MVC project I’m working in; seems easy with your help. Thanks

    Reply
  • 30 October 2013 at 11 h 36 min
    Permalink

    what is the meaning of cmd properties in model

    Reply
  • 1 November 2013 at 16 h 16 min
    Permalink

    Je vous remercie enormement pour cette veritable source d information.

    Reply
  • 26 December 2013 at 4 h 06 min
    Permalink

    I want to make a recurring payment
    can you please let me know what change I need to make in it.

    Reply
    • 28 December 2013 at 21 h 56 min
      Permalink

      Hi,
      you must call recursively the ValidateCommand action with parameters product and total price :
      I have called it by the code :

      @using (Html.BeginForm(“ValidateCommand”, “PayPal”))
      {

      Reply
      • 31 December 2013 at 17 h 50 min
        Permalink

        No I want to create the recurring profile of the user
        and make the payment again with profileid

        Reply
      • 31 December 2013 at 18 h 59 min
        Permalink

        want you the user to pay and logout , and login again to pay by keeping the same profileid ?

        1 °) If yes you can user the user id and pass it in parameters.
        look for class PayPalModel and locate the commented line below

        // We can add parameters here, for example OrderId, CustomerId,

        here you can add parameters you want.

        2°) if not you can 1°) or use look for custum membership profile .

        hope my are helped you.
        regards

        Reply
      • 1 January 2014 at 5 h 07 min
        Permalink

        can you plese have a example for recurring profile
        It’s will really really helpful

        Reply
      • 1 January 2014 at 12 h 44 min
        Permalink

        Explain exactly what you want to do ?
        case 1°) or case 2°) ?

        Reply
  • 1 January 2014 at 14 h 36 min
    Permalink

    I want the payment to occur every month for that user that after he made in the first month.

    Reply
  • 2 January 2014 at 4 h 56 min
    Permalink

    Hello Today I did the transaction with test account
    I got the payment_status as pending and transaction Id diffrent from paypal account.
    Still I see the transaction as compledted and success in my test paypal account
    can you let me know why this happening?

    Reply
  • 3 January 2014 at 7 h 39 min
    Permalink

    Hello Today I did the transaction with test account
    I got the payment_status as pending and transaction Id diffrent from paypal account.
    Still I see the transaction as compledted and success in my test paypal account
    can you let me know why this happening?

    Reply
    • 7 March 2014 at 9 h 32 min
      Permalink

      i also face same problem and i also not receive any payment_status when using mobile or ipad why?

      Reply
  • 7 March 2014 at 9 h 08 min
    Permalink

    Hi, i have used your code to integrate Paypal in MVC but it received all time paymenet_status pending and i received pending_reason in multiple currency when using Sendbox. After put code into live and check from Mobile or ipad it doesn’t return payment_Status value, it receive NULL why? please help me.

    Reply
  • 8 April 2014 at 9 h 20 min
    Permalink

    Hi ,,Payment working fine…After the payment,The Paypal redirecting to “http://localhost/PayPal/RedirectFromPaypal”.. But that page was not showing.. It showing 404 error??? Why???
    ..

    Reply
      • 8 April 2014 at 10 h 04 min
        Permalink

        Oh..Thank You..Now its working…
        And i tried
        var st = Request.QueryString[tx];

        But it showing “The name ‘tx’ does not exist in current context ”

        How to fix it???

        Reply
  • 9 April 2014 at 13 h 05 min
    Permalink

    How to make refund request ????

    Reply
  • 23 April 2014 at 7 h 35 min
    Permalink

    I needed to thank you for this good read!! I certainly enjoyed every little bit of it. I’ve got you bookmarked to check out new stuff you post gfbdfeeckadeagge

    Reply
  • 25 April 2014 at 13 h 53 min
    Permalink

    this works perfect, only amount is not deducted from “Personal” account.
    even “Business” account has credited.
    any idea?

    Reply
  • 3 July 2014 at 3 h 45 min
    Permalink

    Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis. It’s always helpful to read through articles from other writers and practice a little something from other sites.

    Reply
  • 22 August 2014 at 22 h 57 min
    Permalink

    This tutorial is great – but shouldn’t you use IPN verifications just in case the user closes the broswer or the tab and doesn’t get to the target URL on your website after completing the payment?

    Reply
  • 23 October 2014 at 23 h 41 min
    Permalink

    The only think I can say is: Thank you, Thank you, I check other tutorials about but one working fine is yours.

    Reply
  • 19 November 2014 at 18 h 20 min
    Permalink

    how to receive message from notify url?

    Reply
  • 5 January 2015 at 20 h 59 min
    Permalink

    Thanks for this article, it’s clear and simple.
    But, couldn’t it be more secure to check the transaction when the user got back to our website ?
    Do Paypal API offer that kind of check ?

    In that way, we can automatically process the user request when he come back to the return url, but he couldn’t try to force this return url.

    If you already done that check by code, do you have a sample ?

    Many thanks

    Reply
  • 15 January 2015 at 17 h 20 min
    Permalink

    hi your code working charm .but i have a doubt After test buying using sandbox account my transaction details shows ” Unclaimed ” ,And No money credited to Business sandbox account from my Persional sandbox account,What is the reason please replay must

    Reply
  • 10 March 2015 at 10 h 07 min
    Permalink

    hi,
    I followed your article. Its very nice and it is working fine in my asp.net mvc 4 version website local host also.But for capturing the response from paypal after successful transaction , I placed Request.QueryString[« tx »] in RedirectFromPaypal action but it showing « null » . How to get the transaction id ?.. Please respond

    Reply
  • 10 March 2015 at 10 h 08 min
    Permalink

    Hi,
    I followed your article. It’s very nice and it is working fine in my asp.net mvc 4 version website local host also.But for capturing the response from PayPal after successful transaction , I placed Request.QueryString[« tx »] in RedirectFromPaypal action but it showing « null » value for all transactions . How to get the transaction ID?.. Please respond

    Reply
  • 18 April 2015 at 15 h 03 min
    Permalink

    any help on how to pass multiple products to paypal checkout please?

    Reply
  • 26 October 2016 at 0 h 20 min
    Permalink

    Hello everyone, it’s my first pay a visit at
    this web page, and article is truly fruitful in favor of me, keep up posting such
    articles or reviews.

    Reply
  • 26 October 2016 at 11 h 35 min
    Permalink

    Good web site you’ve got here.. It’s difficult to find quality writing like yours
    nowadays. I truly appreciate individuals like you! Take care!!

    Reply
  • 3 November 2016 at 9 h 48 min
    Permalink

    cartierlovejesduas Im grateful for the blog article.Really thank you! Really Cool.

    Reply
  • 8 November 2016 at 19 h 58 min
    Permalink

    Take a look at my blog

    Reply
  • 29 November 2016 at 0 h 47 min
    Permalink

    A person essentially help to make critically posts I might state. This is the first time I frequented your website page and thus far? I surprised with the research you made to create this particular submit extraordinary. Fantastic job!

    Reply
  • 29 November 2016 at 17 h 57 min
    Permalink

    Wonderful, what a webpage it is! This blog gives helpful data to us, keep it up.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *