hal
hal

Reputation: 841

How to post data to wordpress woocommerce api?

I am using RestSharp with WordPress woo-commerce RestApi. The requesting of resources works. However creating of a product fails. It is not the problem with the Wordpress because adding data with Insomnia worked.

This is the code for the problem:

var client = new RestClient($"localhost/index.php/wp-json/wc/v3/");

client.UseNewtonsoftJson();
        
string ck = "ck_48a3709aa7403f33e60188cb2eb90cd30bb5d2a1";
string cs = "cs_fb122249ab19f8e25d516654dc1e92ca74bc3081";
client.Authenticator = new SimpleAuthenticator("consumer_key", ck, "consumer_secret", cs);

var request = new RestRequest("products/{product}", DataFormat.Json).AddUrlSegment("product", "12");
var product = client.Get<Product>(request).Data;

Console.WriteLine(product.name);

Product newp = new Product();
newp.name = "new product";
request = new RestRequest("products", Method.POST, DataFormat.Json);
request.AddJsonBody(newp);
var response = client.Post<Product>(request);

This is the raw message of the response:

{"code":"woocommerce_rest_cannot_create","message":"Sorry, you are not allowed to create resources.","data":{"status":401}}

What is the problem and how do I fix it?

Upvotes: 2

Views: 1957

Answers (1)

hal
hal

Reputation: 841

The solution is to include authentication credentials in post url:

request = new RestRequest("products/?consumer_key=ck_48a3709aa7403f33e60188cb2eb90cd30bb5d2a1&consumer_secret=cs_fb122249ab19f8e25d516654dc1e92ca74bc3081", Method.POST, DataFormat.Json);

Upvotes: 1

Related Questions