Unable to reset Shopify API compare at price using ShopifySharp

914 views Asked by At

I used to be able to set compare_at_price to null after a product was on sale but now I get an error. This is making use of the ShopifySharp C# library from NozzleGear.

Example:

Price was: 1000, Compare at 1200

I want to reset it the Price to 1200, with compare at 0.

(422 Unprocessable Entity) compare_at_price: Compare at price needs to be higher than Price

I can neither set it to 0, so how will I disable the compare_at_price to 0 or null or remove it?

var variant = await productVariantService.UpdateAsync(product.VariantId.Value, new ProductVariant()
{
      Price = updatePrice,
      CompareAtPrice = updateCompareAtPrice
});
1

There are 1 answers

0
Anton Swanevelder On

There seems to be a bug, here is the workaround...

https://github.com/nozzlegear/ShopifySharp/issues/373

Create and use the below Service

using System;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ShopifySharp;
using ShopifySharp.Infrastructure;

public class ProductVariantServiceEx : ProductVariantService
{
    public ProductVariantServiceEx(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }

    public virtual async Task<ProductVariant> UpdateAsync(long productVariantId, ProductVariant variant)
    {
        try
        {
            // BUGFIX: If variant.CompareAtPrice is set to 0, then force it to empty
            string json = new JsonContent(new { variant }).ReadAsStringAsync().Result;

            if (json.Contains("\"compare_at_price\":0.00}")
                || json.Contains("\"compare_at_price\":0.00,"))
            {
                json = json.Replace("\"compare_at_price\":0.00", "\"compare_at_price\":\"\"");

                var req = PrepareRequest($"variants/{productVariantId}.json");
                using var content = new StringContent(json, Encoding.UTF8, "application/json");
                await Task.Run(() => Thread.Sleep(500));
                return (await ExecuteRequestAsync<ProductVariant>(req, HttpMethod.Put, default, content, "variant")
                    .ConfigureAwait(false)).Result;
            }

            return await base.UpdateAsync(productVariantId, variant);
        }
        catch (Exception)
        {
            return null;
        }
    }
}