Woocommerce REST API POST in v2 not working - c#

I have upgraded to V2 and having trouble with posting updates to Woocommerce on my Windows server from C# (using RestSharp).
GET works in both V1 and V2.
Changing order status (for order 81) works in V1, using this code:
var client = new RestClient("https://mysite.com");
client.Authenticator = new HttpBasicAuthenticator("ck_6c5bbb4e467d1994d2428a476bxxxxxx",
"cs_008adefb1692a708e9795de9fxxxxxx");
var requestv1 = new RestRequest("wc-api/v1/orders/{id}", Method.POST);
requestv1.RequestFormat = DataFormat.Json;
requestv1.AddBody(new { status = "completed" });
requestv1.AddParameter("id", 81, ParameterType.UrlSegment);
var queryResultv1 = client.Execute<WC_Manager.OrderSingle>(requestv1);
Changing the resource to "wc-api/v2/orders/{id}" generates no error and the Execute still returns the order now with the extra fields from v2, however the status is NOT changed in the queryresult or in the database.
Same problem when trying to post an update for a product in V2.
Trying to PUT or DELETE gives me a "MethodNotAllowed".

You can add body content with this:
string bodyContent;
bodyContent = "{ \"status\": \"completed\" , ";
bodyContent += "\"customer_note\": \"" + customerNote + "\" }";
request.AddParameter("application/json", bodyContent, ParameterType.RequestBody);

Related

LInkedIn API: The remote server returned an error: (410)

I am facing issue while making call to https://api.linkedin.com/v1/people
using C#. The following code was working fine before. Suddenly today I notice that it's not working.
Here is my code:
string fields = "id,first-name,last- name,site-public-profile-request,email-address"; //connections
string url = "https://api.linkedin.com/v1/people/~:(" + fields + ")?format=json";
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", "Bearer " + accessToken);
headers.Add("x-li-format", "json");
WebRequests webReq = new WebRequests();
string response = webReq.GetRequest(url, headers);
profile = JsonConvert.DeserializeObject<LinkedInUserProfile>(response);
This is for my live site.
I found the problem
V1 is retired now so I need to move to v2
Refrence Link: https://learn.microsoft.com/en-us/linkedin/shared/integrations/people/profile-api?context=linkedin/consumer/context

Get Pdf Rest Sharp (GET)

I am testing a service to which you send a json and it returns a PDF with the data you sent it. I did tests with Insomnia as shown here:
It works correctly, but trying to recover the file through code always generates an error. My code is the following:
var client = new RestClient("Api");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\n\t\"QuotationId\": 0,\n\t\"QuotationName\": \"CasaLomas\",\n\t\"UserGUID\": \"75DB06AC-E349-4C47-A5AF-87EC63A9B8A9\",\n\t\"QuotedQuantity\": 5,\n\t\"TotalPrice\": 500,\n\t\"CopyEmail\": \"angelmg50#hotmail.com\",\n\t\"MaterialDetails\": [\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t},\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t},\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t}\n\t]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This connects correctly with the API but apparently the json has not been sent correctly. Any idea why this happens?
I created the json with dynamic and tried to send it.
dynamic cotizacion = new JObject();
cotizacion.QuotationId = 0;
cotizacion.QuotationName = "Casa lomas 3";
cotizacion.UserGUID = "75DB06AC-E349-4C47-A5AF-87EC63A9B8A9";
cotizacion.QuotedQuantity = 6;
cotizacion.TotalPrice = 456.12;
cotizacion.CopyEmail = "angelmg50#hotmail.com";
cotizacion.MaterialDetails = new JArray(new JObject(
new JProperty("SKU", "C05423082015140001"),
new JProperty("Name", "PORC KONE WHITE MATE 60x30x1"),
new JProperty("Quantity", 1),
new JProperty("Price", 638.09),
new JProperty("Amount", 6380.30)));
var client = new RestClient("Api");
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", cotizacion, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
But this does not work either.
When I print response.Content in console it shows me the following: "Message": "Internal error when trying to generate the PDF" Value can not be null. \ R \ nParameter name: source "," StatusCode ": 3," Result ": null, "ResultList": null}
https://github.com/restsharp/RestSharp/wiki/Recommended-Usage
It seems like you are trying to add a parameter with the name "application/json". You may need to specify the name of the parameter in the endpoint and use AddObject instead of AddParameter. We can help more if you can give us some more info on your endpoint.

Specified value has invalid HTTP Header characters

Im trying to access WOWZA Streaming Cloud through their REST API from an ASP.NET site, however have little experience in RESTSharp.
Here is an example curl I'm trying to create:
curl -H 'wsc-api-key: KEY' -H 'wsc-access-key: KEY' -H 'Content-Type:
application/json' -X POST -d '{"live_stream": {"name": "MyNewLiveStream",
"transcoder_type": "transcoded", "billing_mode": "pay_as_you_go",
"broadcast_location": "us_west_california", "encoder": "other_rtmp",
"delivery_method": "push", "aspect_ratio_width": 1920,
"aspect_ratio_height": 1080}}'https://api.cloud.wowza.com/api/v1/live_streams/
see: https://sandbox.cloud.wowza.com/apidocs/v1/
Here is the c# code im using:
var client = new RestClient("https://api.cloud.wowza.com/");
var newRequest = new RestRequest("api/v1/live_streams",Method.POST);
newRequest.AddHeader("wsc-api-key", ConfigurationManager.AppSettings["WowzaAPIKey"]);
newRequest.AddHeader("wsc-access-key", ConfigurationManager.AppSettings["WowzaAccessKey"]);
newRequest.AddHeader("Content-Type", "application/json");
var body = "{\"live_stream\": {" +
"\"aspect_ratio_height\": 720," +
"\"aspect_ratio_width\": 1280," +
"\"billing_mode\": \"pay_as_you_go\"," +
"\"broadcast_location\": \"us_west_california\"," +
"\"closed_caption_type\": \"none\"," +
"\"delivery_method\": \"push\"," +
"\"encoder\": \"wowza_gocoder\"," +
"\"hosted_page\": true," +
"\"hosted_page_sharing_icons\": true," +
"\"name\": \"MyLiveStream\"," +
"\"player_countdown\": false," +
"\"player_responsive\": true," +
"\"player_type\": \"original_html5\"," +
"\"player_width\": 0," +
"\"recording\": false," +
"\"target_delivery_protocol\": \"hls\"," +
"\"transcoder_type\": \"transcoded\"," +
"\"use_stream_source\": false}";
newRequest.AddJsonBody(body);
IRestResponse myResponse = client.Execute(newRequest);
Following modifications based on the responses, the response code is now
"{\"meta\":{\"status\":401,\"code\":\"ERR-401-InvalidApiKey\",\"title\":\"Invalid Api Key Error\",\"message\":\"Invalid API key.\",\"description\":\"\",\"links\":[]}}"
Your headers are wrong- you dont need to repeat content-type in value and remove : from the api-key name:
newRequest.AddParameter("content-type", "application/json");
newRequest.AddParameter("wsc-api-key", ConfigurationManager.AppSettings["WowzaAPIKey"]);
Update as OP updated the question
So now after the modification, the call is through and is working fine. The current error is regarding invalid api key you are passing - may be the access key/api key you are passing is invlaid/expired.
Thanks everyone for the help - i can now interact seamlessly with Wowza Cloud Streaming through the REST api wrapped by C# and using restsharp.
The solution in the end was to use the visual studio function to generate template JSON classes through Paste Special (see In C#, how do I model a JSON object with multiple nested arrays?) - generating the WowzaLivestream class.
Then using this code in the end:
_restClient = new RestClient("https://api-sandbox.cloud.wowza.com");
var newRequest = new RestRequest("api/v1/live_streams", Method.POST);
newRequest.RequestFormat = DataFormat.Json;
newRequest.AddHeader("wsc-api-key", ConfigurationManager.AppSettings["WowzaAPIKey"]);
newRequest.AddHeader("wsc-access-key", ConfigurationManager.AppSettings["WowzaAccessKey"]);
newRequest.AddHeader("Content-Type", "application/json");
newRequest.AddHeader("Accept", "application/json");
var requestBody = new WowzaLivestream
{
live_stream = new Live_Stream
{
aspect_ratio_height = 1024,
aspect_ratio_width = 1900,
billing_mode = "pay_as_you_go",
broadcast_location = "eu_ireland",
closed_caption_type = "none",
delivery_method = "push",
encoder = "other_rtmp",
name = "WowzaLStest2: " + DateTime.Now.ToShortTimeString(),
player_countdown = true,
player_responsive = true,
player_type = "original_html5",
player_width = 0,
recording = false,
target_delivery_protocol = "hls",
transcoder_type = "transcoded",
use_stream_source = false
}
};
var json = newRequest.JsonSerializer.Serialize(requestBody);
newRequest.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
IRestResponse myResponse = _restClient.Execute(newRequest);
It turns out that the URL used was wrong - it isnt specifically stated in the documentation but for sandbox use, the URL is https://api-sandbox.cloud.wowza.com.
Are you sure you want to add "content-type", "wsc-api-key" and "wsc-access-key" as request parameters?
They should be added in the request header as following.
newRequest.AddHeader("content-type", "Content-Type: application/json");
newRequest.AddHeader("wsc-api-key:", ConfigurationManager.AppSettings["WowzaAPIKey"]);
newRequest.AddHeader("wsc-access-key", ConfigurationManager.AppSettings["WowzaAccessKey"]);

Making POST API request via c# with hashed API Key

I'm trying to make a POST call (from a C# WPF app) to a web service on an internal intranet (so I can't give the exact URL sorry), which is basically a url shortening service.
The page gives the following instructions:
In order to use the API service, simply make HTTP POST requests to this URL:
https://...internalAddress.../api/<method>
For example, to create a snip, make an HTTP POST request to:
https://...internalAddress.../api/shorten
with these parameters:
api_key hash of a registered API key
url URL to be shortened
Now I have tried to implement this in a couple of different ways with what I've found via google / here, these are:
1:
string apiKey = "xxxx11112222333";
string urlForShortening = #"http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp";
string destination = #"https://internalurl/api/shorten";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(destination);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write("{'api_key': '" + apiKey + "', 'url': '" + urlForShortening + "'}");
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
MessageBox.Show(responseText);
}
2: (Using the rest library created in the article found in the shortening link)
string apiKey = "xxxx11112222333";
string urlForShortening = #"http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp";
string destination = #"https://internalurl/api/shorten";
RestClient client = new RestClient(destination, HttpVerb.POST,
"{'api_key': '" + apiKey + "', 'url': '" + urlForShortening + "'}");
var json = client.MakeRequest();
MessageBox.Show(json);
have also tried feeding in the jsonData in double quotes:
var jsonData = "{\"api_key\": \"" + apiKey + "\", \"url\": \"" + urlForShortening + "\"}";
The result from both methods I always get is:
{"status": 400, "message": "Missing API key"}
Can someone please shed some light on what I'm doing wrong?
From the brief, I think the key may need to be hashed in some form and not sure how to do this.
Turns out my whole implementation was wrong, I was trying to send the data as JSON / using the wrong classes instead of a vanilla HTTP POST.
I used Method 2 found in this article and it worked fine: HTTP request with post
ie.
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["api_key"] = "xxxx11112222333";
values["url"] = #"http://www.codeproject.com";
string destination = #"https://internalurl/api/shorten";
var response = client.UploadValues(destination, values);
var responseString = Encoding.Default.GetString(response);
MessageBox.Show(responseString);
}
Thanks for your help though!
I assume that you are attempting to send json data in the request body for the POST call to the API.
You dont seem to be providing a valid json here though. This is what you are sending now:
{'api_key':'someApiKey'}
{'url':'someUrlForShortening'}
Use a json validator to ensure you have a valid json document before you attempt to send it to the API.
A valid json would be
{
"api_key":"someApiKey",
"url":"someUrlForShortening"
}

GoToWebinar - Request not in expected format - RestSharp

Similar to this forum post:
https://developer.citrixonline.com/forum/request-not-expected-format
However he didn't really explain what he found was wrong with his code.
I'm using RestSharp to make API calls. I've been able to get it to work great to pull an list of upcoming webinars however when I try to register participant I keep getting a 400/Request not in expected format error.
Following this documentation https://developer.citrixonline.com/api/gotowebinar-rest-api/apimethod/create-registrant, here is my code:
var client = new RestClient(string.Format("https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants", "300000000000xxxxxx", btn.CommandArgument));
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddHeader("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
request.AddHeader("Authorization", "OAuth oauth_token=" + System.Configuration.ConfigurationManager.AppSettings["GoToWebinar"]);
request.AddParameter("firstName", LoggedInUser.FirstName);
request.AddParameter("lastName", LoggedInUser.LastName);
request.AddParameter("email", LoggedInUser.Email);
var response = client.Execute(request);
var statusCode = response.StatusCode;
Any insights on how I can figure out why I keep getting that error?
Thank you!
Instead of using AddParamter (which adds key/value parameters to the request body), you need to write JSON instead:
request.DataFormat = DataFormat.Json;
request.AddBody(new {
firstName = LoggedInUser.FirstName,
lastName = LoggedInUser.LastName,
email = LoggedInUser.Email
});
You'll also need to clear the handlers (which automatically set the Accept header) if you want to specify them directly:
client.ClearHandlers();

Categories