ASP.NET C# Get referer from Paypal - c#

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
{
}
}
}

Related

how to post on directly at facebook page using C# not at visitor post?

i refereed this post
how to post to facebook page wall from .NET but it will work on facebook page to post as visitor post.
and i want to post of page timeline not at visitor post and i am admin of this page and app.
please give solution for it .
here in my code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using System.Dynamic;
public partial class facebook : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
authontication();
}
private void authontication()
{
string app_id = "**********************";
string app_secret = "###################################";
string scope = "publish_actions,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
//dynamic parameters = new ExpandoObject();
string name = "sudhanshu";
name += " new data";
client.Post("/1168908853153698/feed", new { message = "My first appProduct "+name+" ." });
}
}
}
You need to use a Page Token, not a User Token. Make sure it really is a Page Token by debugging it: https://developers.facebook.com/tools/debug/accesstoken/
Also, publish_actions is the wrong permission to post as Page, you need to use publish_pages.
Additional information:
http://www.devils-heaven.com/facebook-access-tokens/
https://developers.facebook.com/docs/facebook-login/access-tokens
https://developers.facebook.com/docs/graph-api/reference/v2.6/page/feed#publish

PayPal IPN Error

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();
}
}
}

Facebook Web API exception

I keep on getting the exception The remote server returned an error: (400) Bad Request. Whenever it comes at the HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;. Can someone please help me? Here's my code. By the way, it's just a single aspx with not html content. It's just a pure C# file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace Facebook_API
{
public partial class Facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "1234567891234567"; //Just placed this digits to keep this hidden
string app_secret = "12345678912345678912345678912345"; //Just placed this digits to keep this hidden
string scope ="publish_stream,manage_pages"; //Scope are the permissions
if( Request["code"] == null)
{
Response.Redirect(String.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret{4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach(string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1 ));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "Testing Facebook WebAPI " });
}
}
}
You can also try this code by simple creating a new project and create a webform the just insert this in the cs file.
Why are you using
request.Method = "Put";
instead of a normal GET request?

Cannot set CookieContainer due to the state of the HttpWebRequest object error?

I am currently trying to login and get cookies to a remote server using windows phone 7 silverlight in visual studio. I managed to login and get a successful result for login, but when I try to put in the codes to get cookies, it just failed.
It produced error "Cannot set CookieContainer due to the state of the HttpWebRequest object." on my code "request.CookieContainer = new CookieContainer();"
Can anyone helps me? I can't seem to find the error and I try to look at the documentation and examples but with no luck. Below is my full codes on windows phone 7.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
namespace Testing_Login_
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, RoutedEventArgs e)
{
//HttpWebRequest req = WebRequest.Create();
string POST_ADDRESS = "http://mywebsite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute));
request.Method = "POST";
// don't miss out this
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
}
// Sumbit the Post Data
void RequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
Stream stream = request.EndGetRequestStream(asyncResult);
// Hack for solving multi-threading problem
// I think this is a bug
this.Dispatcher.BeginInvoke(delegate()
{
// Send the post variables
StreamWriter writer = new StreamWriter(stream);
writer.Write("username=" + textBoxUsername.Text + "&password=" + passwordBoxSTAMP.Password);
writer.Flush();
writer.Close();
request.CookieContainer = new CookieContainer();
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
});
}
// Get the Result
void ResponseReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
this.Dispatcher.BeginInvoke(delegate()
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// get the result text
string result = reader.ReadToEnd();
if (result == "TRUE")
{
MessageBox.Show("Login Successful!");
//CookieCollection cookieValue = response.Cookies;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
foreach (Cookie cookieValue in response.Cookies)
{
sw.WriteLine("Cookie: " + cookieValue.ToString());
}
sw.Close();
}
}
}
//MessageBox.Show(cookieValue.ToString());
}
else if (result == "ICRED")
{
MessageBox.Show("Username or Password incorrect!");
}
else
{
MessageBox.Show("Unknown Error!"+result);
}
});
}
private void ReadFromIsolatedStorage()
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs =
isf.OpenFile("CookieExCookies", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isfs))
{
textBoxCookies.Text = sr.ReadToEnd();
sr.Close();
}
}
}
}
}
}
Move the line:-
request.CookieContainer = new CookieContainer();
out of RequestReady and put it in buttonLogin_Click just after you have constructed it.
OR since you aren't re-using it anywhere ditch line altogether.
OR if in fact for things to really work you need to re-use it then construct and hold it somewhere else (such as a field in the class) and assign it to each Request object created before you invoke any BeginGetRequestStream or BeginGetResponse.

Error 400 bing text to speech

I’m using bing’s api TTS, I get the information from: http://msdn.microsoft.com/en-us/library/ff512420.aspx
This is the code (from the webside):
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.Media;
namespace Apigoogleprova
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Speak();
}
private static void ProcessWebException(WebException e, string message)
{
Console.WriteLine("{0}: {1}", message, e.ToString());
// Obtain detailed error information
string strResponse = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)e.Response)
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
{
strResponse = sr.ReadToEnd();
}
}
}
Console.WriteLine("Http status code={0}, error message={1}", e.Status, strResponse);
}
public static void Speak()
{
string appId = "myappID"; //go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "speak to me";
string language = "en";
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId +"&text;=" + text + "&language;=" + language;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
//httpWebRequest.Proxy = new WebProxy(""); set your proxy name here if needed
WebResponse response = null;
try
{
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}
}
catch (WebException e)
{
//ProcessWebException(e, "Failed to speak");
MessageBox.Show("Error"+e);
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
}
}
}
(I changed “myappID” with the ID that has provided me Microsoft)
When I run the app I get the following error:
Remote Server Error (400) Bad Request
I tried to go to the web with my browsers (firefox, chrome and IE):
http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=myappID&text;=speak to me&language;=en
And the result is:
**Argument Exception**
Method: Speak()
Parameter: text Message: Value cannot be null.
Parameter name: text message
id=3835.V2_Rest.Speak.25BD061A
Anyone know how to solve this problem?
Thank you very much!
Remove the ; from the parameter names in the query string.

Categories