Paypal Code - Validate Credit Card & CreditCard Payment through Website Payments Pro method

Posted by Venkat | Labels: , , ,

How to Validate the CreditCard in asp.net ??

To validate the CreditCard first you have to check the Card Type then followed by
the no.of digits..etc.. on that Specific Card type. here i am using Luhn Algorithm to validate.

So you have place these algorithm on Separate Class file ie: Create

CardValidator.cs on the App_Code Folder and paste the below code.

using System;

public enum CardType
{
    MasterCard, BankCard, Visa, AmericanExpress, Discover, DinersClub, JCB
};

public sealed class CardValidator
{
    private CardValidator() { } // static only

    public static bool Validate(CardType cardType, string cardNumber)
   {
      byte[] number = new byte[16]; // number to validate

      // Remove non-digits
      int len = 0;
      for(int i = 0; i < cardNumber.Length; i++)
      {
         if(char.IsDigit(cardNumber, i))
         {
            if(len == 16) return false; // number has too many digits
            number[len++] = byte.Parse(cardNumber[i].ToString ());
         }
      }

      // Validate based on card type, first if tests length, second tests prefix
      switch(cardType)
      {
         case CardType.MasterCard:
            if(len != 16)
               return false;
            if(number[0] != 5 || number[1] == 0 || number[1] > 5)
               return false;
            break;

         case CardType.BankCard:
            if(len != 16)
               return false;
            if(number[0] != 5 || number[1] != 6 || number[2] > 1)
               return false;
            break;

         case CardType.Visa:
            if(len != 16 && len != 13)
               return false;
            if(number[0] != 4)
               return false;
            break;

         case CardType.AmericanExpress:
            if(len != 15)
               return false;
            if(number[0] != 3 || (number[1] != 4 && number[1] != 7))
               return false;
            break;

         case CardType.Discover:
            if(len != 16)
               return false;
            if(number[0] != 6 || number[1] != 0 || number[2] != 1 || number[3] != 

1)
               return false;
            break;

         case CardType.DinersClub:
            if(len != 14)
               return false;
            if(number[0] != 3 || (number[1] != 0 && number[1] != 6 && number[1] 

!= 8)
               || number[1] == 0 && number[2] > 5)
               return false;
            break;

         case CardType.JCB:
            if(len != 16 && len != 15)
               return false;
            if(number[0] != 3 || number[1] != 5)
               return false;
            break;
        
      }

      // Use Luhn Algorithm to validate
      int sum = 0;
      for(int i = len - 1; i >= 0; i--)
      {
         if(i % 2 == len % 2)
         {
            int n = number[i] * 2;
            sum += (n / 10) + (n % 10);
         }
         else
            sum += number[i];
      }
      return (sum % 10 == 0);
   }
}

I have the task of payment method through paypal pro using Credit Card.i was

googled a lot with paypal site , fourms and came with the sample code.

The PayPal Name-Value Pair API (NVP API) enables you to leverage thefunctionality of the PayPal API by simply sending an HTTP request to PayPal and specifying request parameters using name-value pairs. The NVP API is a lightweight alternative to the PayPal SOAP API and provides access to the same set of functionality as the SOAP API.

Ref: https://www.paypal.com/IntegrationCenter/ic_nvp.html

Here i am usin NVP API for payment through CreditCard using website Payment Pro

Method , we can also use SOAP API for this we need to do

1)setExpressionCheckout

2) DoExpressionCheckout

3) GetExpressionCheckout.

Either we can use API or through Code. I am Registering on Sandbox.paypal to check the code. we have to create the Buyer , seller Account to check the amount has been transferred or not , so it will automatically create the creditcard no, cardtype for the test account, we have to use this to check the Amount Transfer
or not. While testing , the amount was not deducted on the buyer account but it will credited on Seller account  as this is sanbox test, this is not an issue ,while you upload it on live , it will work smoothly.As i was tested with Sandbox - so you can check it on live.

One of the main advantage of this method is , it will not redirect the user to paypal site,instead the process has been doing on background from the same site after successfull transaction it will give the Transactionid ,
act etc.. so you can store this thing on DB.


While page Designing make sure you have these Fields

1) Card Type

2) Textbox for CreditCard Number

3) Expire Date  / Expire Month

4) Pay button / Cancel button

paybutton_Click
try
        {
              bool validateCard = false;
              if (ddlCCType.SelectedValue.ToString() == "Visa")
              {
                  validateCard = CardValidator.Validate( CardType.Visa , 

txtCCNumber.Text);
              }
              else if (ddlCCType.SelectedValue.ToString() == "MasterCard")
              {
                  validateCard = CardValidator.Validate(CardType.MasterCard , 

txtCCNumber.Text);
              }
              else if (ddlCCType.SelectedValue.ToString() == "AMEX")
              {
                  validateCard = CardValidator.Validate(CardType.AmericanExpress, 

txtCCNumber.Text);
              }

            if (validateCard != false)
            {
                  string ipaddress;

                ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (ipaddress == "" || ipaddress == null)
                {
                    ipaddress = Request.ServerVariables["REMOTE_ADDR"];

                }
        Session["ipAddress"] = ipaddress;

         //API Credentials (3-token)

            string strUsername = "troy2._1261822640_biz_api1.gmail.com";

            string strPassword = "1261822646";

            string strSignature = 

"An5ns1Kso7MWUdW4ErQKJJJ4qi4-A60C4mgCoX2-L9FhwhF2rfGtRPeI";

            string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword 

+ "&SIGNATURE=" + strSignature;
        
            // For Sandbox testing use this API 
            string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";

            // Fpr Live Server use this API
            string strNVPLiveServer = "https://api-3t.paypal.com/nvp";

            string strAPIVersion = "2.3";

// here i am assigning the credit card type cardno,expiry date/month to
 //the session variable and pass it here 

                       string strNVP = strCredentials + 

"&METHOD=DoDirectPayment&CREDITCARDTYPE=" + Session["cardType"].ToString() + 

"&ACCT=" + Session["cardNo"].ToString() + "&EXPDATE=" + 

Session["expiryDate"].ToString() + "&CVV2=808&AMT=" + Amount_Label.Text + 

"&FIRSTNAME=" + FirstName_Label.Text + "&LASTNAME=" + LastName_Label.Text + 

"&IPADDRESS=" + Session["ipAddress"].ToString() + "&STREET=" + address1 + "+" + 

address2 + "&CITY=" + city + "&STATE=" + state + "&COUNTRY=" + country + "&ZIP=" 

+ zip + "&COUNTRYCODE=US&PAYMENTACTION=Sale&VERSION=" + strAPIVersion;

  //Create web request and web response objects, make sure you using the correct 

server (sandbox/live)

            HttpWebRequest wrWebRequest = 

(HttpWebRequest)WebRequest.Create(strNVPSandboxServer);

            ////Set WebRequest Properties
            wrWebRequest.Method = "POST";

            //// write the form values into the request message
            StreamWriter requestWriter = new 

StreamWriter(wrWebRequest.GetRequestStream());

            requestWriter.Write(strNVP);
            requestWriter.Close();

            //// Get the response.
            HttpWebResponse hwrWebResponse = 

(HttpWebResponse)wrWebRequest.GetResponse();

            StreamReader responseReader = new 

StreamReader(wrWebRequest.GetResponse().GetResponseStream());

            //// and read the response
            string responseData = responseReader.ReadToEnd();

            responseReader.Close();
            Response.Write(Server.UrlDecode(responseData));
               
            }
            else
            {
                validateCard_Label.Text = "Please check your card number...";
            }
            
            
          
        }
        catch (Exception ex)
        {
            throw ex;
        } 

Finally , once your Transaction is success you will get the output ie:TransactionID with ack

EX: Output

ACK=Success&TIMESTAMP=date/timeOfResponse
&CORRELATIONID=debuggingToken&VERSION=2.300000&BUILD=buildNumber
&TOKEN=EC-3DJ78083ES565113B&EMAIL=abcdef@anyemail.com
&PAYERID=95HR9CM6D56Q2&PAYERSTATUS=verified
&FIRSTNAME=John&LASTNAME=Smith...&AMT=15&TRANSACTIONID=24527936A38716

Invalid postback or callback argument.

Posted by Venkat | Labels:

I came across the post on Forums ie:

Invalid postback or callback argument.  Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation

To Solve this issue Make sure that you are using IsPostback on the Page_Load() event of that page.


 page_Load() event
If (!IsPostBack)
{
// bind the data
}

Check whether Querystring is available or not.

Posted by Venkat | Labels: ,

Now , i am going to explain how to check Whether the Querystring is present or available or not.

For ex: I am passing id as a querystring to the page2.aspx from page1.aspx.

So on Page1.aspx


Button1_Clickevent() Response.Redirect("page2.aspx?id=1",false); Then on Page2.aspx Page2_Loadevent() If(!IsPostback) {        If(!String.ISNullOrEmpty(Request.QueryString["id"]))         {               // get the value of Querstring id , if id is not null or empty         }        else if(!String.ISNullOrEmpty(Request.QueryString["name"]))         {              // get the value of name querystring if name is not null or empty         } }   When you run the above code - ie: on Page2.aspx you can get the id Querystring value. this works fine.   
Suppose if you pass some other querystring name ex: name from the Page1.aspx the above code gives
ie: Button2_Clickevent()
         Response.Redirect("page2.aspx?name=Dotnet",false);
Error : Object Reference Exception. 

Because it first check the  if condition so in the first condition it contains id so the querystring id will not present so it leads to the Null reference exception.


to avoid this exception you have to check like this.

Page2_Loadevent()
If(!IsPostback) {   if(Request.QueryString["id"] != null)     {        If(!String.ISNullOrEmpty(Request.QueryString["id"]))         {               // get the value of Querstring id , if id is not null or empty         }   } if ((Request.QueryString["name"] != null)   {         if(!String.ISNullOrEmpty(Request.QueryString["name"]))         {              // get the value of name querystring if name is not null or empty         } }  }
          This if(Request.QueryString["id"] != null)  - checks if id is a QueryString variable.

  If(!String.ISNullOrEmpty(Request.QueryString["id"]))  - Check if the id is empty or not

     

Setting Autocomplete Off for the Textbox

Posted by Venkat | Labels:

Now i have to show how to set the Autocompletetype - off for the asp.net  - Texbox

If you want to set the autoComplete property  off use AutoComplete="off" for the textbox.

ie: Autocomplete in the sense if the user typed some text on the textbox, then once again he entered the some word starting with the same letter, it shows previos typed word shows like a combobox manner.

To avoid showing that previous typed word by setting the autoComplete ="Off" to the Textbox.

if you want to set it for the whole page set it on the Form tag


<form autocomplete="off" id="form1" runat="server">
</form>

PayOffers.in