PayPal Payment Gateway Integration In Asp.Net

Using PayPal Payment Gateway in Your e-Commerce Site


If you are developing an ASP.NET web application and you require some payment gateway integration, then here is a simplified option to integrate PayPal with your application.

** A PayPal account can be used only for international transactions. You can not use it for domestic transactions. If you want the solution for domestic purpose then integrate CCAvenue or some other gateway, those provide domestic transactions.

Here I am going to explain this with a piece of code, which will be easier to understand and implement. So lets start

Interface For sending the buyer details to PayPal


   Download Source Code Here

How to Integrate PayPal in ASP.NET

<div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="form-group">
                <label for="exampleInputEmail1">Your Name:</label><asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtPurpose"
                    ErrorMessage="Please enter your Name" runat="server"
                    ValidationGroup="save" ForeColor="red"></asp:RequiredFieldValidator>
                <asp:TextBox runat="server" class="form-control" ValidationGroup="save" ID="txtName"></asp:TextBox>

            </div>
            <div class="form-group">
                <label for="f">Your EmailID:</label>
                <asp:RegularExpressionValidator ID="regexEmailValid" runat="server"
                    ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    ControlToValidate="txtEmailId" ValidationGroup="save"
                    ErrorMessage="Invalid Email Format"
                    ForeColor="red"></asp:RegularExpressionValidator>
                <asp:TextBox runat="server" class="form-control"
                    ValidationGroup="save"
                    ID="txtEmailId"></asp:TextBox>

            </div>
            <div class="form-group">
                <label>Your Phone No:</label>
                <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server"
                    ControlToValidate="txtPhone"
                    ForeColor="red" ErrorMessage="Invalid Phone No"
                    ValidationGroup="save" ValidationExpression="^([0-9\(\)\/\+ \-]*)$">
                </asp:RegularExpressionValidator>
                <asp:TextBox runat="server" ID="txtPhone" ValidationGroup="save" class="form-control"></asp:TextBox>

            </div>
            <div class="form-group">
                <label>Enter Amount:</label><asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtAmount"
                    runat="server" ForeColor="red" ErrorMessage="Please enter the amount.">
                </asp:RequiredFieldValidator>
                <asp:TextBox runat="server" ID="txtAmount" class="form-control"
                    ValidationGroup="save"></asp:TextBox>

            </div>
            <div class="form-group">
                <label>Currency:</label>
                <asp:DropDownList runat="server" ID="ddlCurrency" CssClass="form-control">
                    <asp:ListItem>- Select -</asp:ListItem>
                    <asp:ListItem>INR</asp:ListItem>
                    <asp:ListItem>USD</asp:ListItem>
                    <asp:ListItem>EURO</asp:ListItem>
                    <asp:ListItem>Pound</asp:ListItem>
                </asp:DropDownList>
            </div>
            <div class="form-group">
                <label>Your Purpose:</label>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtPurpose"
                    ErrorMessage="Can not be left blank" ValidationGroup="save"
                    runat="server" ForeColor="red"></asp:RequiredFieldValidator>
                <asp:TextBox TextMode="MultiLine"
                    Rows="10" runat="server" ID="txtPurpose" class="form-control"
                    Height="50px"></asp:TextBox>

            </div>
            <asp:Button ID="btnPay" runat="server" Text="Pay Now" CssClass="btn btn-info"
                OnClick="btnPay_Click" ValidationGroup="save"></asp:Button>
        </div>
    </div>
Now go to the code behind page of the webform and add the below method in it.

An important thing to notice is I am using the live URL of PayPal as this functionality is implemented in my live server. You can use the Sandbox URL of PayPal for testing purposes.
protected void btnPay_Click(object sender, EventArgs e)
    {
        PayWithPayPal(txtAmount.Text.Trim(), txtPurpose.Text.Trim(), txtName.Text.Trim(), txtPhone.Text.Trim(), txtEmailId.Text.Trim(), Convert.ToString(ddlCurrency.SelectedValue));
    }

    protected void PayWithPayPal(string amount, string itemInfo, string name,
      string phone, string email, string currency)
    {
        string redirecturl = "";

        //Mention URL to redirect content to paypal site
        redirecturl += "https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" +
                       ConfigurationManager.AppSettings["paypalemail"].ToString();

        //First name i assign static based on login details assign this value
        redirecturl += "&first_name=" + name;

        //City i assign static based on login user detail you change this value
        redirecturl += "&city=bhubaneswar";

        //State i assign static based on login user detail you change this value
        redirecturl += "&state=Odisha";

        //Product Name
        redirecturl += "&item_name=" + itemInfo;

        //Product Name
        redirecturl += "&amount=" + amount;

        //Phone No
        redirecturl += "&night_phone_a=" + phone;

        //Product Name
        redirecturl += "&item_name=" + itemInfo;

        //Address 
        redirecturl += "&address1=" + email;

        //Business contact id
        // redirecturl += "&[email protected]";

        //Shipping charges if any
        redirecturl += "&shipping=0";

        //Handling charges if any
        redirecturl += "&handling=0";

        //Tax amount if any
        redirecturl += "&tax=0";

        //Add quatity i added one only statically 
        redirecturl += "&quantity=1";

        //Currency code 
        redirecturl += "&currency=" + currency;

        //Success return page url
        redirecturl += "&return=" +
          ConfigurationManager.AppSettings["SuccessURL"].ToString();

        //Failed return page url
        redirecturl += "&cancel_return=" +
          ConfigurationManager.AppSettings["FailedURL"].ToString();

        Response.Redirect(redirecturl);
    }
OK, that is fine. Now before running your application you need to add something in your web.config file. Just add the below shown appsetting code snippet to your web config file under the system.web tag. Here you have to give information regarding your PayPal account, your PayPal email ID , PayPal submit URL, your website success URL, failure URL, etc.
<appSettings>
      <add key="token" value="PW1BDVNqVPVanwduF_Tb2Ey91aT1Uhx1kL7HPc-7e8S-6AnUwSSHyasolSe"/>
      <add key="paypalemail" value="[email protected]"/>
      <!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
      <add key="PayPalSubmitUrl" value="https://www.paypal.com/cgi-bin/webscr"/>
    
      <add key="FailedURL" value="http://www.icodefor.net"/>
    
      <add key="SuccessURL" value="http://www.icodefor.net"/>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
Now you can run your application to see if its working or not.

here is the screenshot after you are being redirected to the merchant site.
PayPal Merchant Site


Happy Coding...

1 comment:

  1. Black Hat hacking differs from White Hat hacking only with how we are choosing the final results of the hacking.
    You can\'t be Black Hat hacker when hacking into the own website.. If your site is situated on a standalone server, you could utilize port scanner to define open ports on that server. Then, using port scanner you could attempt guessing exact services that are running on those ports. After you get that information, you could begin using any exploits that are designed for those services. I would recommend using NMap as a port scanner. Try reading some articles or get information on forums concerning how to use exploits.. If your site won't run using standalone server, don't attempt scanning ports on that server or using any exploits made to take control that server. You may have serious problems in case you start performing it.. You could also try out your site for possible SQL injections or XSS vulnerabilities. In the event that site is associated with you, that is completely legal to test it for these vulnerabilities. Try getting good specifics of that on forums and communities, of course this details are created for Black Hat hacking.. If some of the tests will give you good results, you should think about modifying the code of this section to make it better.. . If the site doesn't completely are part of you, don\'t try running any tests onto it, as it might be described as a hacking attempt. For instance, livejournal, myspace or blogspot are well-defended against attacks.

    Feel free to surf to my weblog ... Scrapebox lists

    ReplyDelete