Solved

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

Posted on 2008-10-20
18
1,767 Views
Last Modified: 2013-11-29
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

0
Comment
Question by:pradipkkoli
  • 11
  • 7
18 Comments
 
LVL 8

Expert Comment

by:the_crazed
ID: 22756516
do you know if the notify_url page is being called at all? try adding some lines to write a log file.
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22756584
there are several third parties who provide test harnesses for your IPN page, including these guys:

http://www.belahost.com/pp/
0
 

Author Comment

by:pradipkkoli
ID: 22756653
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.
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22756869
so what's Request.ContentLength? zero?
(how are you testing this? with 1p payments?)
0
 

Author Comment

by:pradipkkoli
ID: 22756996
Request.contentlength is zero also i am doing one payment at a time above 10 dollars.

Please help
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22758056
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

0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22758410
when you are switching form sandbox to live, are you changing anything else in your config file?
0
 

Author Comment

by:pradipkkoli
ID: 22764943
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
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22765470
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

0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 8

Expert Comment

by:the_crazed
ID: 22765475
I mean log.txt not C:\log.txt
0
 

Author Comment

by:pradipkkoli
ID: 22765968
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.
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22766058
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
0
 

Author Comment

by:pradipkkoli
ID: 22785019
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
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 22785155
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?
0
 

Author Comment

by:pradipkkoli
ID: 22785427
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.
0
 
LVL 8

Accepted Solution

by:
the_crazed earned 500 total points
ID: 22785553
why can't you send a screenshot? simply press alt+Print Screen, paste into "Paint", save, then attatch to your post.

your code has no problems, it should work fine.

your settings as you have described are all fine

your IPN should be working, the problem must be at PayPal's end

you will have to raise a ticket with them sorry
https://ppmts.custhelp.com/cgi-bin/ppdts.cfg/php/enduser/ask.php

really sorry to not be able to be more help
0
 

Author Closing Comment

by:pradipkkoli
ID: 31507751
I got my code working for paypal, it was the error from the session variable in my code and paypal was responding properly.
0
 
LVL 8

Expert Comment

by:the_crazed
ID: 23054816
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!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Read about how to choose the best possible content marketing agency to suit your needs. Content marketing has become an integral part of running a successful tech business, so it is wise to be informed.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now