WooCommerce rest api access failing with httpWebRequest - woocommerce

I am trying to get WooCommerce data using WooCommerce v3 API from c#.
When I use below url in browser I get the products data as json;
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890
When I use url
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products
and
consumer_key = ck_12345678901234567890 and consumer_secret = cs_12345678901234567890
as Params in Postman then I get the products data as well. So the credentials and url are valid.
However when I try to do this using HttpWebRequest it fails with "The remote server returned an error: (401) Unauthorized" exception. My code is below and the exception appears on the last line of code.
The vales in HttpWebRequest before the GetResponseAsync call can be seen here.
What am I doing wrong?
Thanks
Regards
string wc_url = "https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";
HttpWebRequest httpWebRequest = null;
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url);
httpWebRequest.AllowReadStreamBuffering = false;
WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);

Related

QuickBooks OAuth API (401) Unauthorized

Here is the OAuth library I'm using: https://github.com/danielcrenna/oauth
I'm getting the token, secret and realmId (company id) just fine and storing them, but when I go to do a simple request, I get (401) Unauthorized.
Here's the code I'm using:
var rq = new OAuthRequest
{
Method = "GET",
Type = OAuthRequestType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Token = requestToken,
TokenSecret = requestTokenSecret,
RequestUrl = "https://quickbooks.api.intuit.com/v3/company/" + realmId + "/query?query=select%20%2A%20from%20CompanyInfo&minorversion=4",
Version = "1.0",
};
And the Auth header:
OAuth oauth_consumer_key="****",oauth_nonce="6su4ljd2is5bxns4",oauth_signature="0taFXiouzOkpK258tz%2Fc%2F2fVQ0c%3D",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1461339515",oauth_token="****",oauth_version="1.0"
I can't find any other details in the error, I'm just getting "401 Unauthorized." How do I get this request to go through?
Oauth is pretty strict in how the header is written. Why not use one of the Libraries already provided by Intuit? or use the API Explorer to view the header and compare to your request header?
The order of the oauth header parameters matter, and version is not the last one. See this guide.
https://developer.intuit.com/docs/0050_quickbooks_api/0010_your_first_request/rest_essentials_for_the_quickbooks_api

Do I need to investigate HTTP 401 cached by Fiddler during the HttpWebRequest post to ASP.NET WebApi server

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;

Get HTTP Response from a url by using C#

Environment: ASP.Net MVC 4 using C#
I need to get image by using GET request to a URL /inbound/faxes/{id}/image
I used the code below
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("/inbound/faxes/238991717/image");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader stream = new StreamReader(response.GetResponseStream());
but it flags "URL not valid"
I used the complete URL www.interfax.net/inbound/faxes/{id}/image
but the result is same
I want to follow this article to receive faxes
Accepting incoming fax notifications by callback
Can anyone help me to get fax...?
Try like this:
using (var client = new WebClient())
{
byte[] imageData = client.DownloadData("http://www.interfax.net/inbound/faxes/{id}/image");
}
Notice how the url is prefixed with the protocol (HTTP in this case). Also make sure you have replaced the {id} part of the url with the actual id of the image you are trying to retrieve.

PayPal Express Checkout returns - Security header is not valid

This has probably been asked a thousand times... But i'm sure i have all the endpoints and credentials right. It was working yesterday.
Security error:
Error no: 10002
Error message: Security header is not valid
Right now i'm testing against the sandbox server.
Whenever i try the testURL in my browser i get ACK=Success with a token, but i get "Security header is not valid" error when it runs through the code.
It was working a few hours ago but for some reason i keep getting the same error now.
using user/pwd and signature from a sandbox account
https://api-3t.sandbox.paypal.com/nvp
USER=xxxxxxxxxxxxxxxxxxxx
PWD=XXXXXXXXXXXXX
SIGNATURE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I have the following test code:
String testURL = "https://api-3t.sandbox.paypal.com/nvp?USER=xxxxxxxxxxxxxxxxxxxx&PWD=XXXXXXXXXXXXX&SIGNATURE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&VERSION=84.0-2276209&PAYMENTREQUEST_0_PAYMENTACTION=Sale&PAYMENTREQUEST_0_AMT=15&RETURNURL=https%3a%2f%2fdomain.com%2fCheckout.aspx&CANCELURL=https%3a%2f%2fdomain.com%2fCheckout.aspx&METHOD=SetExpressCheckout";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(testURL);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(testURL);
streamOut.Close();
// get resposne
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = HttpUtility.UrlDecode(streamIn.ReadToEnd());
streamIn.Close();
HTTPREsponse when code sends it
TIMESTAMP=2011-11-22T23:25:34Z&CORRELATIONID=392047cb78388&ACK=Failure&VERSION=84.000000&BUILD=2271164&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Security error&L_LONGMESSAGE0=Security header is not valid&L_SEVERITYCODE0=Error
HttpResponse if i just copy paste the testURL in the browser
TOKEN=EC%2d4JW15968AV8121546&TIMESTAMP=2011%2d11%2d22T22%3a59%3a27Z&CORRELATIONID=c790299fd9ac7&ACK=Success&VERSION=84%2e000000&BUILD=2271164
I've tried not to UrlEncode the variables in the test url... same problem
thanks in advance
OK this might be a bug on Paypal's side.
if i change the testUrl from
String testURL = "https://api-3t.sandbox.paypal.com/nvp?USER=XXX&PWD=YYY&SIGNATURE=ZZZ&VERSION=.......&METHOD=SetExpressCheckout";
to
String testURL = "https://api-3t.sandbox.paypal.com/nvp?&x=y&USER=XXX&PWD=YYY&SIGNATURE=ZZZ&VERSION=.......&METHOD=SetExpressCheckout";
it works
See the bolded part with random first querystring variable.
PayPal seems to ignore the first querystring parameter when it's sent from codebehind (which would be user=xxx if there wasn’t x=y before it).

HTML scraping: Forms authentication failed for the request. The ticket supplied has expired

The ActiveForums module we're using as part of our DotNetNuke system has a bug in the XML for it's RSS feed. It doesn't correctly encode ampersands, it leaves them as & rather than encoding them as &
I've reported the bug to the company, but in the mean time I need a fix. So what I've done is create an intermediary page that makes a request to the RSS feed via a System.Net.HttpWebRequest.Create(url) and them performs a Regex.Replace to replaces any unencoded ampersands.
The problem is that when I run the code on our production server I get an exception: The remote server returned an error: (500) Internal Server Error.
The only reason I could think of was around authentication (As the server requires NTLM), however as far as I can tell I'm doing this part of it correctly. My code is shown below:
string html = string.Empty;
string url = "http://intranet.nt.avs/dnn/Default.aspx?tabid=130";
WebResponse response;
WebRequest request = System.Net.HttpWebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
html = sr.ReadToEnd();
}
// Clean invalid XML
html = Regex.Replace( html, "&(?!amp;|gt;|lt;|quot;|apos;)", "&", RegexOptions.Multiline | RegexOptions.IgnoreCase );
Response.ContentType = "text/xml";
Response.Write( html );
Updated: Here's what the event log says
Error code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired

Resources