Shopify api更新变量返回错误

本文关键字:返回 错误 变量 更新 api Shopify | 更新日期: 2023-09-27 18:02:30

我想更新商店产品的inventory_quantity,结果出错了

远程服务器返回一个错误:(400)Bad Request.

这就是我如何实现它的。

ProductVariant product = new ProductVariant();
product.id = 1962693211;
product.inventory_quantity = 20;
product.inventory_management = "shopify";
string ordersApi = ConfigurationManager.AppSettings["Shopify_Api_Inventory"];
string url = ordersApi.Replace("{StoreName}", _cred.StoreName);
url = url.Replace("{id}", product.id.ToString());
string xmlStringResult = string.Empty;

try
{
    var req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "PUT";
    req.ContentType = "application/json";
    req.Credentials = GetCredential(url);
    req.PreAuthenticate = true;
    var json = JsonConvert.SerializeObject(product);
    json = "{ variant: " + json + "}";

    if (!String.IsNullOrEmpty(json))
    {
        using (var ms = new MemoryStream())
        {
            using (var writer = new StreamWriter(req.GetRequestStream()))
            {
                writer.Write(json);
                writer.Close();
            }
        }
    }
    using (var resp = (HttpWebResponse)req.GetResponse())
    {
        if (resp.StatusCode != HttpStatusCode.OK)
        {
            string message = String.Format("Call failed. Received HTTP {0}", resp.StatusCode);
            AppendLog(string.Format("Error: {0}", message));
            return xmlStringResult;
        }
        var sr = new StreamReader(resp.GetResponseStream());
        xmlStringResult = sr.ReadToEnd();
    }
}
catch (Exception ex)
{
    AppendLog(string.Format("Error: {0}", ex.Message));
}

提前感谢您的帮助

Shopify api更新变量返回错误

这行代码

json = "{ variant: " + json + "}";

生成如下json

{ variant: {"id":1962693211,"inventory_quantity":20,"inventory_management":"shopify"}}

无效。有效的json应该是

{ "variant": {"id":1962693211,"inventory_quantity":20,"inventory_management":"shopify"}}

所以你需要把上面这行代码改成

json = "{ '"variant'": " + json + "}";