protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // Used parts from https://www.paypaltech.com/PDTGen/ // Visit above URL to auto-generate PDT script authToken = WebConfigurationManager.AppSettings["PDTToken"]; //read in txn token from querystring txToken = Request.QueryString.Get("tx"); query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, authToken); // Create the request back string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"]; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); // Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = query.Length; // Write the request back IPN strings StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(query); stOut.Close(); // Do the request to PayPal and get the response StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream()); strResponse = stIn.ReadToEnd(); stIn.Close(); //string strResponse = "SUCCESS mc_gross=145.35 protection_eligibility=Ineligible address_status=confirmed payer_id=WJ3SRWX9PXP94 tax=0.00 address_street=1+Main+St payment_date=07%3A13%3A35+Sep+06%2C+2012+PDT payment_status=Pending terminal_id= charset=windows-1252 address_zip=95131 first_name=sdgsd receipt_reference_number= mc_fee=4.52 address_country_code=US address_name=sdgsd+sdgs custom=80%2C9b5dc3f5-54d2-413b-9803-1fbabe6770ac payer_status=verified business=sellpr_1346179874_biz%40yahoo.com address_country=United+States address_city=San+Jose quantity=1 payer_email=adver_1345188328_per%40yahoo.com txn_id=059835996R2655052 payment_type=instant last_name=sdgs address_state=CA receiver_email=sellpr_1346179874_biz%40yahoo.com store_id= payment_fee=4.52 receiver_id=EVBLGJGBR8RL8 pending_reason=paymentreview pos_transaction_type= txn_type=web_accept item_name=ewtwet num_offers=0 mc_currency=USD item_number=1 residence_country=US handling_amount=0.00 transaction_subject=80%2C9b5dc3f5-54d2-413b-9803-1fbabe6770ac payment_gross=145.35 shipping=0.00 "; // sanity check //Response.Write(strResponse); string CustomerID = GetCustomerID(); PDTHolder pdt = PDTHolder.Parse(strResponse); // If response was SUCCESS, parse response string and output details //The payment is succesful if (strResponse.StartsWith("SUCCESS")) { using (var context = new SidejobEntities()) { try { var Custom = pdt.Custom.Split(','); //var custom = GetProjectID() + "," + GetCustomerID() + "," + GetPaymentID(); int ProjectId = int.Parse(Custom[0]); int CustomerId = int.Parse(Custom[1]); int PaymentId = int.Parse(Custom[2]); var result = from c in context.ArchivedCustomerSuccessfulPDTs where c.CustomerID == CustomerId && c.ProjectID == ProjectId && c.TransactionId == pdt.TransactionId select c; var resultQuery = result.FirstOrDefault(); if (resultQuery == null) { HiddenLabel.Text = string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!", pdt.PayerFirstName, pdt.PayerLastName, pdt.PayerEmail, pdt.GrossTotal, pdt.Currency); //Insert into Successful PDT var CustomerSuccessfulPDT = new CustomerSuccessfulPDT { PDTID = GetNextSuccessfulPDTID(), GrossTotal = pdt.GrossTotal, Invoice = pdt.InvoiceNumber, PaymentStatus = pdt.PaymentStatus, FirstName = pdt.PayerFirstName, LastName = pdt.PayerLastName, PaymentFee = pdt.PaymentFee, BusinessEmail = pdt.BusinessEmail, TxToken = Request.QueryString.Get("tx"), ReceiverEmail = pdt.ReceiverEmail, ItemName = pdt.ItemName, CurrencyCode = pdt.Currency, TransactionId = pdt.TransactionId, Custom = pdt.Custom, //Testing this one subscriberId = pdt.SubscriberId, //subscriberId = "", CustomerID = CustomerId, ProjectID = ProjectId }; var PaymentID = int.Parse(Custom[2]); CustomerPaymentDue currentpaymentdue = (from c in context.CustomerPaymentDues where c.PaymentDueID == PaymentID select c).FirstOrDefault(); //Response.Write(pdt.PaymentStatus.ToString()); if (pdt.PaymentStatus == "Completed") { //Archived PDT var archivedcustomerSuccessfulPDT = new ArchivedCustomerSuccessfulPDT { PDTID = GetNextSuccessfulPDTID(), GrossTotal = pdt.GrossTotal, Invoice = pdt.InvoiceNumber, PaymentStatus = pdt.PaymentStatus, FirstName = pdt.PayerFirstName, LastName = pdt.PayerLastName, PaymentFee = pdt.PaymentFee, BusinessEmail = pdt.BusinessEmail, TxToken = Request.QueryString.Get("tx"), ReceiverEmail = pdt.ReceiverEmail, ItemName = pdt.ItemName, CurrencyCode = pdt.Currency, TransactionId = pdt.TransactionId, Custom = pdt.Custom, subscriberId = pdt.SubscriberId, CustomerID = CustomerId, ProjectID = ProjectId }; context.AddToArchivedCustomerSuccessfulPDTs(archivedcustomerSuccessfulPDT); //Archived Payment Due var archivedpaymentdue = new ArchivedCustomerPayment { CustomerID = currentpaymentdue.CustomerID, PaymentDueID = currentpaymentdue.PaymentDueID, ProjectID = currentpaymentdue.ProjectID, ProjectAmount = currentpaymentdue.ProjectAmount, Date = currentpaymentdue.Date, StatusID = currentpaymentdue.StatusID, CurrencyCode = currentpaymentdue.CurrencyCode, PaymentDue = currentpaymentdue.PaymentDue, PhaseStatus = currentpaymentdue.PhaseStatus }; context.AddToArchivedCustomerPayments(archivedpaymentdue); //Update PaymentDue context.CustomerPaymentDues.DeleteObject(currentpaymentdue); context.SaveChanges(); //invoke timeup for customerpayment //Approve Ad //ApproveAd(AdID); } else { currentpaymentdue.Status = pdt.PaymentStatus; currentpaymentdue.PaymentProcess = true; } context.AddToCustomerSuccessfulPDTs(CustomerSuccessfulPDT); context.SaveChanges(); } else { HiddenLabel.Text = Resources.Resource.AlreadyPaid; } } catch (Exception e1) { string failuremessage = pdt.PayerFirstName + " " + pdt.PayerLastName + "<br/>"; failuremessage += Resources.Resource.FailedTransaction + "<br/>"; failuremessage += Resources.Resource.FailurePDT; HiddenLabel.Text = failuremessage; } } } else { using (var context = new SidejobEntities()) { try { string[] Custom = pdt.Custom.Split(','); //var custom = GetProjectID() + "," + GetCustomerID() + "," + GetPaymentID(); int ProjectId = int.Parse(Custom[0]); int CustomerId = int.Parse(Custom[1]); int PaymentId = int.Parse(Custom[2]); //Insert into HackedPDT var CustomerHackedPDT = new CustomerHackedPDT { PDTID = GetNextSuccessfulPDTID(), GrossTotal = pdt.GrossTotal, Invoice = pdt.InvoiceNumber, PaymentStatus = pdt.PaymentStatus, FirstName = pdt.PayerFirstName, LastName = pdt.PayerLastName, PaymentFee = pdt.PaymentFee, BusinessEmail = pdt.BusinessEmail, TxToken = Request.QueryString.Get("tx"), ReceiverEmail = pdt.ReceiverEmail, ItemName = pdt.ItemName, CurrencyCode = pdt.Currency, TransactionId = pdt.TransactionId, Custom = pdt.Custom, SubscriberId = pdt.SubscriberId, CustomerID = CustomerId, ProjectID = ProjectId }; context.AddToCustomerHackedPDTs(CustomerHackedPDT); context.SaveChanges(); //Email Admin EmailAdmin("HackedPDT", GetNextSuccessfulPDTID()); string failuremessage = pdt.PayerFirstName + " " + pdt.PayerFirstName + "<br/>"; failuremessage += Resources.Resource.FailedTransaction + "<br/>"; failuremessage += Resources.Resource.FailurePDT; HiddenLabel.Text = failuremessage; } catch (Exception e1) { EmailAdmin("HackedPDT", GetNextSuccessfulPDTID()); string failuremessage = pdt.PayerFirstName + " " + pdt.PayerFirstName + "<br/>"; failuremessage += Resources.Resource.FailedTransaction + "<br/>"; failuremessage += Resources.Resource.FailurePDT; HiddenLabel.Text = failuremessage; } } } } }
//From ProcessIpn to GetNextSuccessfulIPNID private void ProcessIpn(IPNHolder ipn, string advertiserID) { // 1 //check that receiver_email is your Primary PayPal email // 2 //check the payment_status is Completed // 3 //check that payment_amount/payment_currency are correct // 4 //check that txn_id has not been previously processed // 5 //process payment // 4 //check that txn_id has not been previously processed IPN using (var context = new SidejobEntities()) { try { var result = from c in context.CustomerSuccesfulIPNs where c.TransactionId == ipn._txnID select c.TransactionId; var resultQuery = result.FirstOrDefault(); if (resultQuery == null) { //TransactionID doesn't Exist In IPN //Custom for the Ad //Passing multiple variables into custom. var Custom = ipn._custom.Split(','); //var custom = GetProjectID() + "," + GetCustomerID() + "," + GetPaymentID(); int ProjectId = int.Parse(Custom[0]); int CustomerId = int.Parse(Custom[1]); int PaymentId = int.Parse(Custom[2]); float paymentGross = float.Parse(ipn._paymentGross); float paymentFees = float.Parse(ipn._paymentFee); float paymentDue = paymentGross - paymentFees; //3//check that payment_amount are correct var result2 = from c in context.CustomerPaymentDues where c.CustomerID == CustomerId && c.ProjectID == ProjectId && Math.Abs(c.PaymentDue - paymentGross) < 0.00001 select c.ProjectID; var resultQuery2 = result2.FirstOrDefault(); if (resultQuery2 != 0) { // 4 b //check that txn_id has not been previously processed ipn var result3 = from c in context.CustomerSuccessfulPDTs where c.TransactionId == ipn._txnID && c.PaymentStatus == "Completed" select c.PDTID; var resultQuery3 = result3.FirstOrDefault(); if (resultQuery3 == 0) { double paymentGross1 = double.Parse(ipn._paymentGross); double paymentFees1 = double.Parse(ipn._paymentFee); //Insert into customeripn var customeripn = new CustomerSuccesfulIPN { IPNID = GetNextSuccessfulIPNID(), GrossTotal = paymentGross1, Invoice = ipn._invoice, PayerStatus = ipn._paymentStatus, FirstName = ipn._firstName, LastName = ipn._lastName, PaymentFee = paymentFees1, BusinessEmail = ipn._business, ReceiverEmail = ipn._receiverEmail, ItemName = ipn._itemName, CurrencyCode = ipn._countryCode, TransactionId = ipn._txnID, Custom = ipn._custom, CustomerID = CustomerId, ProjectID = ProjectId, TxType = ipn._txnType, PendingReason = ipn._pendingReason, SubscriberId = "", PaymentDate = DateTime.Now.Date, Address = ipn._address, City = ipn._city, State = ipn._state, Zip = ipn._zip, Country = ipn._country, CountryCode = ipn._countryCode, AddressStatus = ipn._addressStatus, PaymentStatus = ipn._payerStatus, PayerID = ipn._payerID, PaymentType = ipn._paymentType, NotifyVersion = ipn._notifyVersion, PayerPhone = ipn._payerPhone, Tax = ipn._tax, PayerBusinessName = ipn._payerBusinessName }; context.CustomerSuccesfulIPNs.AddObject(customeripn); context.SaveChanges(); CustomerPaymentDue currentpaymentdue = (from c in context.CustomerPaymentDues where c.PaymentDueID == PaymentId select c).FirstOrDefault(); //Archived Payment Due var archivedpaymentdue = new ArchivedCustomerPayment { CustomerID = currentpaymentdue.CustomerID, PaymentDueID = currentpaymentdue.PaymentDueID, ProjectID = currentpaymentdue.ProjectID, ProjectAmount = currentpaymentdue.ProjectAmount, Date = currentpaymentdue.Date, StatusID = currentpaymentdue.StatusID, CurrencyCode = currentpaymentdue.CurrencyCode, PaymentDue = currentpaymentdue.PaymentDue, PhaseStatus = currentpaymentdue.PhaseStatus, PaymentProcess = currentpaymentdue.PaymentProcess }; context.AddToArchivedCustomerPayments(archivedpaymentdue); //Update PaymentDue context.CustomerPaymentDues.DeleteObject(currentpaymentdue); context.SaveChanges(); //invoke timeup for customerpayment //Approve Ad //ApproveAd(AdID); //Insert into HistoryTransaction //Delete from PaymentDue //EmailBuyer EmailBuyer(Resources.Resource.PaypalSuccessfulHeader, "Success", ipn._payerEmail, ipn); //EmailAdmin EmailAdmin(("Successful Payment"), ipn); } } } } catch (Exception e) { } } }