paypal ipn integration in asp.net application - asp.net

Iam trying to integrate paypal ipn in my application,but Iam getting error like "An exception of type 'System.Net.WebException' occurred in System.dll" but was not handled in user code in streamwriter.I have tried the below code.Please suggest.
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
public partial class ipn : 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";
string strLive = "https://www.paypal.com/cgi-bin/webscr";
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);
strRequest += "&cmd=_notify-validate";
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")
{
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
}

string Identity_Token = "zkiMk_t - XXXXXagbIDrzPAChXuWIYVS66TXXXXXXXXXXXXXXXXXXXXXXXXXX";//From you paypal account
string txToken = Request.QueryString["tx"];
string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, Identity_Token);
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
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 += query;
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 response was SUCCESS, parse response string and output details
if (strResponse.StartsWith("SUCCESS"))
{
Label1.Text = "OK";
}
else
{
Label1.Text = "NO";
}
}
}

Related

Pushwoosh Remote API DOT NET Example

My Phonegap application can receive notifications from pushwoosh panel. I want to integrate it in my DOT NET Application with help of remote api.
You can find example at http://docs.pushwoosh.com/docs/createmessage
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string pwAuth = "YOUR_AUTH_TOKEN";
string pwApplication = "PW_APPLICATION_CODE";
JObject json = new JObject(
new JProperty("application", pwApplication),
new JProperty("auth", pwAuth),
new JProperty("notifications",
new JArray(
new JObject(
new JProperty("send_date", "now"),
new JProperty("content", "test"),
new JProperty("wp_type", "Toast"),
new JProperty("wp_count", 3),
new JProperty("data",
new JObject(
new JProperty("custom", "json data"))),
new JProperty("link", "http://pushwoosh.com/"),
new JProperty("conditions",
new JArray(
(object)new JArray("Color", "EQ", "black")))))));
PWCall("createMessage", json);
}
private void PWCall(string action, JObject data)
{
Uri url = new Uri("https://cp.pushwoosh.com/json/1.3/" + action);
JObject json = new JObject(new JProperty("request", data));
DoPostRequest(url, json);
}
private void DoPostRequest(Uri url, JObject data)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.ContentType = "text/json";
req.Method = "POST";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(data.ToString());
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
throw new Exception(string.Format("Problem with {0}, {1}", url, exc.Message));
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Page.Response.Write(responseText);
}
}
}
}

How to get data from API on POST method

I have to accesss an get some data from one of API.This API has only mentoned this method.No documentation showing how to acess and all.Data will be returned as Json.
This is the product API
1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}
I have generated the Token and I tried to access it like this.But nothing is recieving.I found an example and tried to do like this.May be this is wrong.Can any one show me how to access and get the data.Please see my code below and thanks in advanced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
request.Method = "POST";
string postData = "Data to post here";
byte[] post = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
}
}
I think you should change these things:
content type
request.ContentType = "application/json";
the post data
string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";
the URI
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");

How can I use auth cookie in cookie Aware Client to access secured web page?

Initially I'm login in to a secured webpage,then m getting the cookie manually and then i have to set the cookie while making another call to fetch data from authorized web url.
how can I make one cookie aware client which do not require to set the auth cookie again and again. it should automatically set the auth cookie and get the required data.
My code is
CPSession retVal = null;
if (guid != "")
retVal = TokenManager.getSessionInfo(guid);
ServicePointManager.ServerCertificateValidationCallback = delegate
{ return true; };
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(address);
httpWReq.CookieContainer = new CookieContainer();
Encoding encoding = new UTF8Encoding();
byte[] bdata = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "PUT";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.CookieContainer.SetCookies(new Uri(address), retVal.getAttributeValue(CookieType)); // here I'm setting cookie manually.
httpWReq.ContentLength = bdata.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(bdata, 0, bdata.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
You can create one cookie aware client like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace SunPowerService.Service
{
public class CookieAwareWebClient : WebClient
{
public CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}
}
and you can call it like this
using (var client = new CookieAwareWebClient())
{
Uri uri = new Uri("YourUrlToGetAuthCookie");
client.m_container.SetCookies(uri, strCookieVal);
jsonresponse = client.DownloadString(uri);
}

push notification using asp.Net

i am using asp.net for gcm push notification to android but message is can't send to each other but if i off the wi-fi of both the tablet and again on, then all message will received by both tablet.
Bellow is the GCM code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
public class AndroidGCMPushNotification
{
public string SendNotification(string deviceId, string message)
{
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
// --- text
//tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
//string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
// + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
string postData = "delay_while_idle=0&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleApiKey));
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
public string GoogleApiKey
{
get { return m_strGoogleAppID; }
set { m_strGoogleAppID = value; }
}
public string SenderId
{
get { return m_strSenderId; }
set { m_strSenderId = value; }
}
string m_strSenderId;
string m_strGoogleAppID;
}

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word .
I use this code .
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
System.Net.WebRequest request =
System.Net.HttpWebRequest.Create("http://spsdev2:1009");
System.Net.WebResponse response = request.GetResponse();
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(fileName);
WebResponse myResp = myReq.GetResponse();
//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();
I get error in myReq.GetResponse();
Error :The remote server returned an error: (401) Unauthorized.
Edit
This code work for me :)
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
I add credentials for HttpWebRequest.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}

Resources