I'm working on a web app that will manage WooCommerce orders, over WooCommerce REST API.
I'm trying to update the order status after the user clicks a button.
When I run the app, click the button, I get a 200 - OK status, but the order remains the same, no update is done.
This is the cURL example on the documentation:
curl -X PUT https://example.com/wp-json/wc/v3/orders/727 \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"status": "completed"
}'
On Postman, i execute the query and it works just fine, adding this code on the body (raw-JSON), over a PUT request:
{
"status": "cancelled"
}
Now, this is my C# code, on the onClick action of the button:
#region Request
string nuevoEstado = "trash";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlRequestInicial);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "PUT";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr + ":" + apiPwd));
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var serializaer = new JavaScriptSerializer();
var elJeison = serializaer.Serialize(new
{
status = nuevoEstado
});
streamWriter.Write(elJeison);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string returnString = httpResponse.StatusCode.ToString();
ltErr.Text = returnString;
#endregion
returnString shows "OK", but no update is done.
Any help is muchly appreciated
Solved it with another approach. I post it here in case anyone gets to the same issue I had:
I changed the method to a async void
using System.Net.Http;
using System.Net.Http.Headers;
protected async void btnCompletarPedidoApiAxnAsync (object sender, EventArgs e)
{
...
}
And I set a using block, changing the approach over a HttpClient();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("PUT"), laUrl))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(apiUsr + ":" + apiPwd));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\n \"status\": \"completed\"\n}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
string responseBody = await response.Content.ReadAsStringAsync();
}
}