When I ran the following code through the IPN simulator the simulator said it worked however my page received a INVALID response.
I did some reading and paypal said it uses charset UTF-8 but when I changed to that the simulator failed and I received no response.
The code runs on pageload
string postUrl = ConfigurationManager.AppSettings["PayPalSubmitUrlSandBox"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postUrl);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
string ipnPost = strRequest;
strRequest = "cmd=_notify-validate&" + strRequest;
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//removed this because I don't think it is what is causing the trouble }
}
else if (strResponse == "INVALID")
{
//removed this because I don't think it is what is causing the trouble
}
else
{
//removed this because I don't think it is what is causing the trouble
}
Try changing your code to the following:
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest = "cmd=_notify-validate&";
req.ContentLength = strRequest.Length;
Also, make sure you're logged into the sandbox BEFORE you do the test...
Figured it out... not really sure what changed from the previous code. I just found code on a tutorial and did some minor modifications.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing;
public partial class paypal_IPNHandler : System.Web.UI.Page
{
string payerEmail;
string paymentStatus;
string receiverEmail;
string amount;
/// <summary>
/// Process an incoming Instant Payment Notification (IPN)
/// from PayPal, at conclusion of a received payment from a
/// customer
/// </summary>
///
protected void Page_Load(object sender, EventArgs e)
{
// receive PayPal ipn data
// extract ipn data into a string
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
// append PayPal verification code to end of string
strRequest = "cmd=_notify-validate&" + strRequest;
// create an HttpRequest channel to perform handshake with PayPal
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"https://www.paypal.com/cgi-bin/webscr");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = strRequest.Length;
// send data back to PayPal to request verification
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
// receive response from PayPal
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// if PayPal response is successful / verified
if (strResponse.Equals("VERIFIED"))
{
// paypal has verified the data, it is safe for us to perform processing now
// extract the form fields expected: buyer and seller email, payment status, amount
payerEmail = Request.Form["payer_email"];
paymentStatus = Request.Form["payment_status"];
receiverEmail = Request.Form["receiver_email"];
amount = Request.Form["mc_gross"];
}
// else
else
{
// payment not complete yet, may be undergoing additional verification or processing
// do nothing - wait for paypal to send another IPN when payment is complete
}
String insertConnString = System.Configuration.ConfigurationManager.ConnectionStrings["BeachConnectionString"].ConnectionString;
using (SqlConnection insertcon = new SqlConnection(insertConnString))
using (SqlCommand cmdinsert = insertcon.CreateCommand())
{
string insertprofile = "INSERT INTO Test (Status, Text) VALUES (#Status, #Text)";
cmdinsert.CommandText = insertprofile;
cmdinsert.Parameters.Add("#Status", SqlDbType.VarChar).Value = strResponse.ToString();
cmdinsert.Parameters.Add("#Text", SqlDbType.VarChar).Value = strRequest.ToString();
cmdinsert.Connection.Open();
cmdinsert.ExecuteNonQuery();
}
}
}
Related
the APi call (Patch) through Visual Studio Console app is failing with the following error
The remote server returned an error: (403) Forbidden.
The same call works fine when I use Postman. I get the response back from Postman(Basic authentication with username and password). What could be the issue with the c# program.
.NET framework 4.7
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var result = string.Empty;
string json = #"{
""schemas"": [
""urn:scim:schemas:core:2.0:User"",
""urn:scim:schemas:extension:fa:2.0:faUser""
],
""userName"": ""ZMatt.Dandon #cmpy.com"",
""name"": {
""familyName"": ""Dandon"",
""givenName"": ""ZMatt""
},
""displayName"": ""ZMatt Dandon"",
""preferredLanguage"": ""en"",
""active"": false
}";
string url = #"https://url/hcmRestApi/scim/Users/C8FF94E381891376E050480A69294891";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
Req.Credentials = new NetworkCredential("UserName", "Password");
//Content_type
Req.ContentType = "application/vnd.oracle.adf.action+json";
//HTTP method
Req.Method = "PATCH";
using (var streamWriter = new StreamWriter(Req.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)Req.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
}
}
Basic authentication is base64 encoded and added to the HTTP Authorization header.
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
//Req.Credentials = new NetworkCredential("00OracleERPuser", "PMT12345");
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8")
.GetBytes("UserName" + ":" + "Password"));
Req.Headers.Add("Authorization", "Basic " + encoded);
I'm trying to post a JSON string on a PHP page using HTTP response methods as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Web;
namespace http_requests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/abc/products.php");
//httpWebRequest.ContentType = "application/json";
//httpWebRequest.Method = "POST";
//using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
//{
// string json = new JavaScriptSerializer().Serialize(new
// {
// user = "Foo",
// password = "Baz"
// });
// streamWriter.Write(json);
// streamWriter.Flush();
// streamWriter.Close();
// var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
// {
// var result = streamReader.ReadToEnd();
// }
//}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/ABC/products.php");
request.Method = WebRequestMethods.Http.Post;
string DataToPost = new JavaScriptSerializer().Serialize(new
{
user = "Foo",
password = "Baz"
});
byte[] bytes = Encoding.UTF8.GetBytes(DataToPost);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
//string postData = "firstName=" + HttpUtility.UrlEncode(p.firstName) +
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
//StreamWriter writer = new StreamWriter(request.GetRequestStream());
//writer.Write(DataToPost);
//writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//StreamReader reader = new StreamReader(response.GetResponseStream());
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
richTextBox1.AppendText("R : " + result);
Console.WriteLine(streamReader.ReadToEnd().Trim());
}
//richTextBox1.Text = response.ToString();
}
}
}
I tried it in many different ways (converting to bytes too) but still posts a NULL array.
PHP Code:
<?php
$json = $_POST;
if (isset($json)) {
echo "This var is set so I will print.";
//var_dump($json);
var_dump(json_decode(file_get_contents('php://input')));
}
?>
When I try to get tha response from server and print onto a text box, it prints right:
R : This var is set so I will print.object(stdClass)#1 (2) {
["user"]=>
string(3) "Foo"
["password"]=>
string(3) "Baz"
}
but i'm unable to check it on my PHP page, it says:
This var is set so I will print.NULL
Not sure if its posting a JSON onto PHP or not, but it sure does posts a NULL.
I want to see the JSON on PHP page, Any help would be appreciated.
Thank you,
Revathy
There is nothing wrong with your c# client side code, the problem is that visiting a site in your browser is a seperate request from the c# post, so you wont see anything.
As per my comment, if you want to see the data in a browser after a post i c#, you will need to save and retrieve it.
Here is a simple example using a text file to save post data and display it:
//if post request
if($_SERVER['REQUEST_METHOD']=='POST'){
//get data from POST
$data = file_get_contents('php://input');
//save to file
file_put_contents('data.txt', $data);
die('Saved');
}
//else if its a get request (eg view in browser)
var_dump(json_decode(file_get_contents('data.txt')));
I have a big trouble. I've done an e-commerce site many month ago, now i wanna do that after an user has bought, paypal redirect the user in a website that confirm the bought with an e-mail.
Obviously, the return page has a control of refererpage, because it can't send a confirmation mail to all that write the page address, but the command:
Request.ServerVariables["HTTP_REFERER"]
Doesn't work, because paypal is an https webpage. So, how i can solve it?
Thank you before!
hi you can try below code for this:
First set the "notify_url" in your website
<input type="hidden" name="notify_url" value="http://www.your-website-url.com/notifypaypal.aspx" />
after that create notifypaypal.aspx Page.
notifypaypal.aspx : here not required any code ..
notifypaypal.aspx.cs :
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using BLL;
public partial class notifypaypal : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Post back to either sandbox or live
// string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";//For localhost
string strLive = "https://www.paypal.com/cgi-bin/webscr";//For live server
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
string ipnPost = strRequest;
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
//req.Proxy = proxy;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// logging ipn messages... be sure that you give write permission to process executing this code
string logPathDir = ResolveUrl("Messages");
string logPath = string.Format("{0}\\{1}.txt",Server.MapPath(logPathDir), DateTime.Now.Ticks);
File.WriteAllText(logPath, ipnPost);
if (strResponse == "VERIFIED")
{
#region [Update Order Status]
string txn_id = HttpContext.Current.Request["txn_id"]; //txn_id= Unique transaction number.
string payment_status = HttpContext.Current.Request["payment_status"]; //payment_status=Payment state(Completed,Pending,Failed,Denied,Refunded)
string pending_reason = HttpContext.Current.Request["pending_reason"]; //pending_reason=Reason of payment delay(echeck,multi_currency,intl,verify,...)
string item_number = HttpContext.Current.Request["item_number"]; //item_number=order number
if (HttpContext.Current.Request["payment_status"].ToString() == "Completed")
{
try
{
//update in database that particular "item_number"(Order number) is successfully Completed
}
catch
{
}
}
else
{
if (HttpContext.Current.Request["payment_status"].ToString() == "Pending")
{
try
{
//update in database that particular "item_number"(Order number) is Pending
}
catch
{
}
}
else
{
}
}
#endregion
}
else if (strResponse == "INVALID")
{
}
else
{
}
}
}
i am using the following code to send notification but it is for only one device but i want to send notification to multiple devices in same request.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class AndroidPush : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string deviceId = "DEVICE_REGISTRATION_ID";
string message = "Lead Generated Please check Lead section";
string tickerText = "Lead Generated Please check Lead section";
string contentTitle = "Lead Generated Please check Lead section";
string postData =
"{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string response = SendGCMNotification("my api key", postData, "application/json");
}
/// <summary>
/// Send a Google Cloud Message. Uses the GCM service and your provided api key.
/// </summary>
/// <param name="apiKey"></param>
/// <param name="postData"></param>
/// <param name="postDataContentType"></param>
/// <returns>The response string from the google servers</returns>
private string SendGCMNotification(string apiKey, string postData, string postDataContentType)
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
so i want to know how can i use this code so that it can send notification to multiple devices.
If anyone knows about this then please provide answer or suggestion for the same.
Thanks in advance
I need have some site manipulation from C# programming language (Microsoft Visual Studio 2010). It is site "http://m.vk.com" . I authorized on this site. It was everything normal. First web-page after authorization it was my profile page. But when I passed to another page this site I loosed my authorization. Another site page was displayed but in non authorization mode. I saved and wrote cookies files to another query. I write next my C# programming code:
I used these directives:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;
It is main function code which started after main button pushing:
private void button1_Click(object sender, EventArgs e)
{
string login = textBox1.Text;
string pass = textBox2.Text;
bool avt = http_auth_vk(login, pass);
if (avt == true)
{
toolStripStatusLabel1.Text = "Succes authorization !";
}
else
{
toolStripStatusLabel1.Text = "Authorization data incorrect !";
}
}
This is the function "http_auth_vk" :
public bool http_auth_vk(string login, string pass)
{
//*****************************
//Получаем action_url
//*****************************
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
System.Net.WebRequest reqGET = System.Net.WebRequest.Create("http://m.vk.com/");
System.Net.WebResponse resp = reqGET.GetResponse();
System.IO.Stream stream = resp.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
string s = sr.ReadToEnd();
//*****************************
//Парсим
//*****************************
// Создаём экземпляр класса
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
// Загружаем в класс (парсер) наш html
doc.LoadHtml(s);
// Извлекаем значения
HtmlNode bodyNode = doc.DocumentNode.SelectSingleNode("//div[#class='cont']/form");
// Выводим на экран значиение атрибута src
// у изображения, которое находилось
// в теге <div> в слассом bla
string result1 = bodyNode.Attributes["action"].Value;
//*****************************
//POST запрос
//*****************************
var cookies = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create(result1);
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write("email=" + login + "&pass=" + pass);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
//*****************************
//Парсим, поиск ID
//*****************************
HtmlAgilityPack.HtmlDocument doc2 = new HtmlAgilityPack.HtmlDocument();
doc2.LoadHtml(result);
string result2;
try
{
//textBox3.Text = result;
HtmlNode bodyNode2 = doc2.DocumentNode.SelectSingleNode("//div[#class='user_wrap']/a");
result2 = bodyNode2.Attributes["href"].Value.Substring(3);
//Если ID найден, то авторизация удалась
//ПЕРЕХОД НА СТРАНИЦУ ГРУППЫ
//string sLocation = myHttpWebResponse.Headers["Location"];
// получам cookie
string sCookies = "";
if (!String.IsNullOrEmpty(resp.Headers["Set-Cookie"]))
{
sCookies = resp.Headers["Set-Cookie"];
}
MessageBox.Show(sCookies);
// формируем запрос
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://m.vk.com/id100669061");
//myHttpWebRequest.Proxy = new WebProxy("127.0.0.1", 8888);
myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
myHttpWebRequest.Headers.Add("Accept-Language", "ru");
myHttpWebRequest.ContentType = "text/plain";
if (!String.IsNullOrEmpty(sCookies))
{
myHttpWebRequest.Headers.Add(HttpRequestHeader.Cookie, sCookies);
}
// выполняем запрос
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
StreamReader myStreamReader = new StreamReader(myHttpWebResponse.GetResponseStream(), Encoding.GetEncoding(1251));
textBox3.Text = myStreamReader.ReadToEnd();
MessageBox.Show(myStreamReader.ReadToEnd());
//Console.WriteLine(myStreamReader.ReadToEnd());
//Console.ReadKey();
return true;
}
catch
{
//textBox3.Text = result;
//Если ID не науден, то авторизация не удалась
MessageBox.Show("Authorization error !");
return false;
}
}
}
How I can save authorization, after next page pass?
After a little investigation I believe I found your problem. The .NET framework will take care the cookies for you, you don't need to worry about setting the cookie or save the cookie for later use, but you do need to use the same CookieContainer for all requests.
So first set the cookie container you would like to use:
var cookies = new CookieContainer();
You can remove this, as well, all piece of code that uses sCookies.
string sCookies = "";
if (!String.IsNullOrEmpty(resp.Headers["Set-Cookie"]))
{
sCookies = resp.Headers["Set-Cookie"];
}
MessageBox.Show(sCookies);
And in the second/third request instead of having this:
if (!String.IsNullOrEmpty(sCookies))
{
myHttpWebRequest.Headers.Add(HttpRequestHeader.Cookie, sCookies);
}
You need to have this (CookieContainer)
myHttpWebRequest.CookieContainer = cookies;