简体   繁体   中英

How to Add new product to Woocommerce using c# RestSharp

I try to add new product to Woocommerce using c# RestSharp, but answer from server is:

{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_consumer_key parameter mangler"}]}

For adding product i use next code:

  public string AddProduct()
    {
        Method method = Method.POST;
        string result = "";
        string endpoint = "products";
        var client = new RestClient(ApiUrl);
        var parameters = new Dictionary<string, string>();
        var request = createRequestWithParams(parameters, endpoint, method); 
        request.RequestFormat = DataFormat.Json;

        request.AddJsonBody(new DTO.WCProduct { title = "eeee2", type = "simple", regular_price = "777", description = "Descr" });
        AddOAuthparams(ref parameters, method.ToString(), endpoint);
        result = client.Execute(request).Content;
        return result;
    }

Where Method createRequestWithParams is :

private RestRequest createRequestWithParams(Dictionary<string, string> parameters, string res, Method methos)
    {
        var req = new RestRequest(res, methos);
        foreach (var item in parameters)
        {
            req.AddParameter(item.Key, item.Value);
        }
        return req;
    }`

Where Method AddOAuthparams is :

   void AddOAuthparams(ref Dictionary<string, string> parameters, string method, string endpoint)
    {
        parameters["oauth_consumer_key"] = this.ConsumerKey;
        parameters["oauth_timestamp"] =
            DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds.ToString();
        parameters["oauth_timestamp"] = parameters["oauth_timestamp"].Substring(0, parameters["oauth_timestamp"].IndexOf(",")); //todo fix for . or ,
        parameters["oauth_nonce"] = Hash(parameters["oauth_timestamp"]);
        parameters["oauth_signature_method"] = "HMAC-SHA256";
        parameters["oauth_signature"] = GenerateSignature(parameters, method, endpoint);

    }

 public string GenerateSignature(Dictionary<string, string> parameters, string method, string endpoint)
    {
        var baserequesturi = Regex.Replace(HttpUtility.UrlEncode(this.ApiUrl + endpoint), "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
        var normalized = NormalizeParameters(parameters);

        var signingstring = string.Format("{0}&{1}&{2}", method, baserequesturi,
            string.Join("%26", normalized.OrderBy(x => x.Key).ToList().ConvertAll(x => x.Key + "%3D" + x.Value)));
        var signature =
            Convert.ToBase64String(HashHMAC(Encoding.UTF8.GetBytes(this.ConsumerSecret),
                Encoding.UTF8.GetBytes(signingstring)));
        Console.WriteLine(signature);
        return signature;
    }

    private Dictionary<string, string> NormalizeParameters(Dictionary<string, string> parameters)
    {
        var result = new Dictionary<string, string>();
        foreach (var pair in parameters)
        {
            var key = HttpUtility.UrlEncode(HttpUtility.UrlDecode(pair.Key));
            key = Regex.Replace(key, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()).Replace("%", "%25");
            var value = HttpUtility.UrlEncode(HttpUtility.UrlDecode(pair.Value));
            value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()).Replace("%", "%25");
            result.Add(key, value);
        }
        return result;
    }

** But if i try to Get info about products or Delete some product this functions worked fine, **

This code i find on Github https://github.com/kloon/WooCommerce-REST-API-Client-Library

I think, that my function for signature is worked bad, but i don't understand what should be fixed.

Maybe this is an old question. But it will be worth for someone came from google searching any hint.

edit: From the error message, i think you forgot to include the oauth_consumer_key as the message. Make sure your request include the oauth_consumer_key, by check the RestRequest query parameter.

Btw instead using the implementation from kloon, you can use the Woocommerce C# Library from my repository

Try the below solution its very easy to integrate and require very less line of codes.It Works for me

static void Main(string[] args)
        {
            string requestURL = @"http://www.example.co.uk/test/wp-json/wc/v1/products";

            UriBuilder tokenRequestBuilder = new UriBuilder(requestURL);
            var query = HttpUtility.ParseQueryString(tokenRequestBuilder.Query);
            query["oauth_consumer_key"] = "consumer_key";
            query["oauth_nonce"] = Guid.NewGuid().ToString("N");
            query["oauth_signature_method"] = "HMAC-SHA1";
            query["oauth_timestamp"] = (Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds)).ToString();
            string signature = string.Format("{0}&{1}&{2}", "POST", Uri.EscapeDataString(requestURL), Uri.EscapeDataString(query.ToString()));
            string oauth_Signature = "";
            using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("consumer_Secret&")))
            {
                byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(signature));
                oauth_Signature = Convert.ToBase64String(hashPayLoad);
            }
            query["oauth_signature"] = oauth_Signature;
            tokenRequestBuilder.Query = query.ToString();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenRequestBuilder.ToString());
            request.ContentType = "application/json; charset=utf-8";
            // request.Method = "GET";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = File.ReadAllText(@"D:\JsonFile.txt");//File Path for Json String

                streamWriter.Write(json);
                streamWriter.Flush();
            }

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM