Link to home
Start Free TrialLog in
Avatar of pradipkkoli
pradipkkoli

asked on

Paypal Instant payment notification not working with live account but works fine wirh sandbox testing.

Sir,

I am using paypal's instant payment verification to process the payment. The script works fine with sandbox testing tool and i get the response as verified or invalid. But when the same coding is used with live paypal account nothing is received though the payment get processed in paypal account.

Please help for this on urgent.
<!-- My Html code is to send the payment is -->
<form id="payForm" method="post" action="<%Response.Write (URL);%>">
        <input type="hidden" name="cmd" value="<%Response.Write (cmd);%>" />
        <input type="hidden" name="business" value="<%Response.Write (business);%>" />
        <input type="hidden" name="item_name" value="<%Response.Write (item_name);%>" />
        <input type="hidden" name="amount" value="<%Response.Write (amount);%>" />
        <input type="hidden" name="no_shipping" value="<%Response.Write (no_shipping);%>" />
        <input type="hidden" name="return" value="<%Response.Write (return_url);%>" />
        <input type="hidden" name="rm" value="<%Response.Write (rm);%>" />
        <input type="hidden" name="notify_url" value="<%Response.Write (notify_url);%>" />
        <input type="hidden" name="cancel_return" value="<%Response.Write (cancel_url);%>" />
        <input type="hidden" name="currency_code" value="<%Response.Write (currency_code);%>" />
        <input type="hidden" name="custom" value="<%Response.Write (request_id);%>" />
    </form>
    <script language="javascript" type="text/javascript">
        document.forms["payForm"].submit ();    
    </script>
 
<!-- code behind for this is in sp.net c# -->
 
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //Session["ClientEventId"] = "1";
            //Session["ParticipantTypeID"] = "1";
            if (Session["totalEventFees"].ToString().Trim() != "0")
            {
                string amt = string.Format("{0:c}", Convert.ToDouble(Session["totalEventFees"].ToString().Trim()));
                amt = amt.Replace('$', ' ');
                amount = amt.Trim();
            }
            else
                Response.Redirect("RegistrationPayment.aspx");
 
            participantRegistration myReg = new participantRegistration();
            myReg.setClientEventID = Session["ClientEventId"].ToString().Trim();
            DataTable dt = new DataTable();
            dt = myReg.getClientCredentials;
 
            string confrimationPage = dt.Rows[0]["afterPaymentReturnPage"].ToString().Trim();
            
            business = dt.Rows[0][1].ToString().Trim();
            //item_name = "Registration payment for " + dt.Rows[0][6].ToString().Trim() + ", " + dt.Rows[0][5].ToString().Trim() + " event.";            
            item_name = " " + dt.Rows[0][5].ToString().Trim() + ". ";            
            return_url = ConfigurationManager.AppSettings["return_url"].ToString().Trim();           
            notify_url = ConfigurationManager.AppSettings["notify_url"].ToString().Trim();
            cancel_url = ConfigurationManager.AppSettings["cancel_url"].ToString().Trim();
            currency_code = ConfigurationManager.AppSettings["currency_code"].ToString().Trim();
            no_shipping = "1";
            if (ConfigurationManager.AppSettings["UseSandbox"].ToString().Trim() == "true")
                URL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            else
                URL = "https://www.paypal.com/cgi-bin/webscr";
            request_id = generateTempRequestId();
            Session.Add("strTranNum", request_id.Trim());
 
            rm = "2";
            
        }
        catch
        {
            //Response.Redirect("RegistrationPayment.aspx?pay=0");
            Server.Transfer(Request.UrlReferrer.ToString());
        }
    }
 
    private string generateTempRequestId()
    {
        Random rnd = new Random();
        int length = 8;
        string charPool = "ABCdefghiDEF234GHIJKLnopqMNOPQR789STUVWXYZabcjklmrstuvwxyz1560";
        StringBuilder rs = new StringBuilder();
 
        while (length > 0)
        {
            rs.Append(charPool[(int)(rnd.NextDouble() * charPool.Length)]);
            length = length - 1;
        }
 
        DateTime dt = new DateTime();
        dt = DateTime.Now;
        string curHr = Convert.ToString(dt.Hour);
        string curMin = Convert.ToString(dt.Minute);
        string curSec = Convert.ToString(dt.Millisecond);
        string dateYear = Convert.ToString(dt.Year);
        string dateMonth = Convert.ToString(dt.Month);
        string dateDay = Convert.ToString(dt.Day);
        if (Convert.ToInt32(dateMonth) < 10)
            dateMonth = "0" + dateMonth;
 
        if (Convert.ToInt32(curHr) < 10)
            curHr = "0" + curHr;
        if (Convert.ToInt32(curMin) < 10)
            curMin = "0" + curMin;
        string TranId = curHr + curMin + curSec + rs.ToString() + "_" + Session["ClientEventId"].ToString() + ":" + Session["ParticipantTypeID"].ToString() ;
 
        return TranId.ToString().Trim();
    }
 
<!-- The code where request is received after proccesing is -->
 
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string strFormValues = Encoding.ASCII.GetString(Request.BinaryRead(Request.ContentLength));            
            string strNewValue = "";
            string URL = "";
            if (ConfigurationManager.AppSettings["UseSandbox"].ToString().Trim() == "true")
                URL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            else
                URL = "https://www.paypal.com/cgi-bin/webscr";
 
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            strNewValue = strFormValues + "&cmd=_notify-validate";
            req.ContentLength = strNewValue.Length;           
 
            StreamWriter stOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
            stOut.Write(strNewValue);
            stOut.Close();
            HttpWebResponse strResponse = (HttpWebResponse)req.GetResponse();
            Stream IPNResponseStream = strResponse.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader readStream = new StreamReader(IPNResponseStream, encode);           
 
            char[] read = new char[256];
            int count = readStream.Read(read, 0, 256);
            while (count > 0)
            {
                string IPNResponse = new string(read, 0, count);
                count = readStream.Read(read, 0, 256);
                string amount = string.Format("{0:c}", Convert.ToDouble(Session["totalEventFees"].ToString().Trim()));
                amount = amount.Replace('$', ' ');
                amount = amount.Trim();                
                string tranID = Session["strTranNum"].ToString().Trim();
                participantRegistration myReg1 = new participantRegistration();
                string[] strTranS1 = tranID.Split('_');
                string[] strClientEvntParticipant1 = strTranS1[1].Split(':');
                myReg1.setClientEventID = strClientEvntParticipant1[0].ToString().Trim();
                DataTable dt1 = new DataTable();
                dt1 = myReg1.getClientCredentials;
                business = dt1.Rows[0][1].ToString().Trim();// "pradip.koli@gmail.com";
                string confrimationPage = dt1.Rows[0]["afterPaymentReturnPage"].ToString().Trim();
                if (IPNResponse == "VERIFIED")
                {
                    rEmail = this.Request["receiver_email"].ToString().Trim();
                    tType = this.Request["txn_type"].ToString().Trim();
                    tID = this.Request["txn_id"].ToString().Trim();
                    mGrossAmtApproved = this.Request["mc_gross"].ToString().Trim();
                    userEmail = this.Request["payer_email"].ToString().Trim();
                    userFirstName = this.Request["first_name"].ToString().Trim();
                    userLastName = this.Request["last_name"].ToString().Trim();
                    customTranID = this.Request["custom"].ToString().Trim();
                    if (tType == "web_accept" && rEmail == business.Trim() && customTranID == tranID)
                    {
                        if (mGrossAmtApproved == amount)
                            lblPayPalLabel.Text = "Payment of $" + amount + " Made Successfully";
                        else
                        {
                            if (Convert.ToDouble(mGrossAmtApproved) > 0 && Convert.ToDouble(mGrossAmtApproved) < Convert.ToDouble(amount))
                                lblPayPalLabel.Text = "Payment of $" + mGrossAmtApproved + " made successfully. Partial Payment will not register you!";
                            else
                                lblPayPalLabel.Text = "Payment of $" + amount + " Made Successfully";
                        }
                        string[] strTranS = customTranID.Split('_');
                        string[] strClientEvntParticipant = strTranS[1].Split(':');
                        participantRegistration myReg = new participantRegistration();
                        DataTable dt = new DataTable();
                        dt = myReg.getPaymentDataTable().Clone();//.Copy();
                        DataRow myRow = dt.NewRow();
                        myRow["ClientEventId"] = strClientEvntParticipant[0].ToString().Trim();
                        myRow["ParticipantType"] = strClientEvntParticipant[1].ToString().Trim();
                        myRow["AmountPaid"] = amount;
                        myRow["PaymentType"] = "PayPal";
                        myRow["CardHolderName"] = "";
                        myRow["CardNumber"] = "";
                        myRow["CardType"] = "";
                        myRow["CCExpiryDate"] = "";
                        myRow["AuthorizationNo"] = tID;
                        myRow["Payer_Email"] = userEmail;
                        myRow["Payer_FirstName"] = userFirstName;
                        myRow["Payer_LastName"] = userLastName;
                        dt.Rows.Add(myRow);
                        DataSet myDst = new DataSet();
                        myDst = ((DataSet)Session["RegistrationDataSet"]).Clone();
                        myDst = ((DataSet)Session["RegistrationDataSet"]).Copy();
                        myDst.Tables.Add(dt);
                        Session["RegistrationDataSet"] = null;
                        Session["RegistrationDataSet"] = myDst;
                        myReg.setClientEventID = strClientEvntParticipant[0].ToString().Trim();
                        myReg.setparticipantTypeID = strClientEvntParticipant[1].ToString().Trim();
                        myReg.setRegisterationDataset = myDst.Copy();
                        string str = myReg.registerParticipant;
                        string confId = str;
                        myReg.setConfrimationID = str;
                        str = myReg.insertBillingAddress;
                        str = myReg.insertTransactionData(confId, mGrossAmtApproved, userEmail, userFirstName, userLastName, customTranID, "", "", "");
                        MailClient myMail = new MailClient();
                        try
                        {
                            DataTable myTab = new DataTable();
                            myTab = ((DataTable)(Session["schoolInfo"])).Clone();
                            myTab = ((DataTable)(Session["schoolInfo"])).Copy();
                            if (myTab.Rows.Count > 0)
                            {                               
                                //myMail.sendNewSchoolInfo(confId, myTab.Rows[0][0].ToString().Trim(), myTab.Rows[0][1].ToString().Trim(), myTab.Rows[0][2].ToString().Trim(),
                                //    myTab.Rows[0][3].ToString(), myTab.Rows[0][4].ToString(), myTab.Rows[0][5].ToString(), myTab.Rows[0][6].ToString(), myTab.Rows[0][7].ToString(),
                                //    myTab.Rows[0][8].ToString(), myTab.Rows[0][9].ToString());
                                string strSchoolConf = "0";
                                participantCommon myParticipant = new participantCommon();
                                strSchoolConf = myParticipant.insertParticipantSchool(confId, myTab.Rows[0]["SchoolName"].ToString().Trim(), myTab.Rows[0]["SchoolAddress"].ToString().Trim(), myTab.Rows[0]["SAptNo"].ToString().Trim(),
                                        myTab.Rows[0]["Scity"].ToString().Trim(), myTab.Rows[0]["Sstate"].ToString().Trim(), myTab.Rows[0]["Szip"].ToString().Trim(), myTab.Rows[0]["SPhone"].ToString().Trim(), myTab.Rows[0]["Sfax"].ToString().Trim(),
                                        myTab.Rows[0]["schoolWebsite"].ToString().Trim(), myTab.Rows[0]["Mastername"].ToString().Trim(), myTab.Rows[0]["Scountry"].ToString().Trim());
                                Session["schoolInfo"] = null;
                            }
                        }
                        catch
                        {
                        }
                        //myMail.sendConfirmationMailPayee(confId);
                        myMail.sendConfirmationMail(confId);
                        Response.Redirect(confrimationPage);
                    }
                    else
                    {
                        lblPayPalLabel.Text = "Payment has been declined";
                    }
                }
            }
        }
        catch
        {
 
        }
    }
 
 
 
<!-- where i am going wrong for live i am not abale to figure it out -->

Open in new window

Avatar of the_crazed
the_crazed
Flag of United Kingdom of Great Britain and Northern Ireland image

do you know if the notify_url page is being called at all? try adding some lines to write a log file.
there are several third parties who provide test harnesses for your IPN page, including these guys:

http://www.belahost.com/pp/
Avatar of pradipkkoli
pradipkkoli

ASKER

Yes notify url page is also called but there being no querystring that is passing back from paypal, hence either the request.forms nor the Encoding.ASCII.GetString(Request.BinaryRead(Request.ContentLength)) has value which again needs to pass back to paypal. The response values from paypal are coming from sandbox testing but not from the live paypal, i am totally surprised.
so what's Request.ContentLength? zero?
(how are you testing this? with 1p payments?)
Request.contentlength is zero also i am doing one payment at a time above 10 dollars.

Please help
did you try running a POST through
http://www.belahost.com/pp/
?

did you get the same results?

try replacing

//replace this
//string strFormValues = Encoding.ASCII.GetString(Request.BinaryRead(Request.ContentLength));  
 
//with this
System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream);
string strFormValues = reader.ReadToEnd(); 

Open in new window

when you are switching form sandbox to live, are you changing anything else in your config file?
Sir,

I can use the proposed statement
System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream);
string strFormValues = reader.ReadToEnd();

But the question is there is no query string returning from paypal site if i use live paypal account but the query string is return when i use sandbox testing.  

And also yes i am simply changing the flag from the web.config to either use sandbox or live paypal account.

Thanks
please alter the code at the top of your page to the following, call it once directly, once from sandbox and once from live, and send me the C:\log.txt that is produced

thanks
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
	System.IO.StreamReader r = new System.IO.StreamReader(Request.InputStream);
	string strFormValues = r.ReadToEnd(); 
 
	System.IO.StreamWriter f = new System.IO.StreamWriter(Server.MapPath("log.txt"),true);
	f.WriteLine("DateTime.Now " + DateTime.Now);
	f.WriteLine("Request.ContentLength " + Request.ContentLength);
	f.WriteLine("Request.QueryString " + Request.QueryString);
	f.WriteLine("HTTP_REFERER " + Request.ServerVariables["HTTP_REFERER"]);
	f.WriteLine("strFormValues " + strFormValues);
 
	f.WriteLine(" ");
 
	f.Close();
	f=null;
         string strNewValue = "";
 
//.....

Open in new window

I mean log.txt not C:\log.txt
Sir, i agree you required the log file and i can give you the log file (which will contain some data) after testing on Sandbox.  But it is very much clear that log file for live paypal account will be BLANK. Because live paypal account is not sending any querystring to my return page hence ( as per your code),
f.WriteLine("Request.ContentLength " + Request.ContentLength);
      f.WriteLine("Request.QueryString " + Request.QueryString);

Request.ContentLength and Request.QueryString is coming BLANK, and this is my question that WHY PAYPAL LIVE ACCOUNT IS NOT SENDING ANY RESPONSE BACK, while sandbox testing sends. Now if any special settings are required in paypal account for Instant payment notification please confirm, i can do that, because i guess i had done each settings on my paypal account,but some how something is missing. I had attached the code, the code which is taken from paypal site itself.  

So sending log will have the data for sandbox testing but not for live paypal account.
please follow the steps and post the log anyway. i would not expect it to be blank for live, i would expect it to shown something like:

DateTime.Now 21/10/2008 09:57:03
Request.ContentLength 0
Request.QueryString
HTTP_REFERER http://www.paypal.com/
strFormValues
 


I have no idea yet why paypal live is not sending any response back, that is why I need your help to debug the problem.

i was going to suggest that you veryify that you have "Instant Payment Notification (IPN)" set to "On" under Profile/Instant Payment Notification Preferences

but you have assured me that the notification url is definitely being called, so that renders that solution useless
Sir,

Yes the IPN settings is set on. And i had not sent the log file because notify_url is never getting triggerred from paypal lice account even i waited on my local machine for about 5 mins. The response is immediatly given on the return url page, there also there being no data return from paypal. So the log file execpt above data is blank.

I am not understanding why notify_url is not triggered but return url is triggerred. Am i missing some setting in my paypal live account. I am not aware, there being no straight forward method to conform whether the user has paid the amount on paypal? while in my case payment is processing on paypal account but not triggerred on notify_url! How do i make user aware that there transaction is completed succesfully or not.

Thanks
oh, right, I thought you said the page we being called. this is a different problem.

is there a default URL in your paypal IPN settings? would you mind posting a screenshot of your Profile/Instant Payment Notification Preferences page?
Sir,

I cannot send the screenshot. But the IPN return is set true (that is enabled is true) with default url which will be used for live site. But as per the paypal documentation this url gets overridden if we send the notify_url to the paypal, so that should not matter, I guess. Also if i am not sure getting respond from the paypal on my local machine who should i get this code running on live.

So i want the code so that my notify_url gets triggered as soon as payment is made (if my above said code is not as per standards) also if my code is correct what i am missing on paypal site to set. I had already enabled IPN then why there is no trigger on my notify_url page.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of the_crazed
the_crazed
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I got my code working for paypal, it was the error from the session variable in my code and paypal was responding properly.
thanks for the points!

however, I'm afraid I've got to say a little "I told you so" - if you'd added the logging I suggested I'm sure it would have helped us on our way to figuring this out.

glad you got it sorted anyway!