如何 post 数据到 wordpress woocommerce api?

How to post data to wordpress woocommerce api?

我将 RestSharp 与 WordPress woo-commerce RestApi 一起使用。资源请求有效。但是创建产品失败。这不是 Wordpress 的问题,因为使用 Insomnia 添加数据有效。

这是问题的代码:

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);

这是响应的原始消息:

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

这是什么问题,我该如何解决?

解决方案是在 post url 中包含身份验证凭据:

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