The variation added by the admin api cannot be added to the cart

The variation added by the admin api cannot be added to the cart

ostap-brechko
Shopify Partner
1 0 0

Hello. I am developing a size configurator. I would like to be able to add a custom price variation to the shopping cart. For this purpose, I create a variation via the admin api. I am doing this according to the documentation:
https://shopify.dev/api/admin/rest/reference/products/product-variant
Then I get the variant_id returned by the admin api. After that, in the js code on the front-end of the Shopify site, I add the variation I just created to the cart. But the problem is that the basket does not display the price and name of the variation created in this way.
After that, if you wait a few seconds and then refresh the page, then after that the basket is displayed normally, and the new variation is present in it.

I'm pretty sure the problem is not with my theme. I tried doing this also on the Debut theme and the error recurred.

These variations are not displayed in the cart popup that is implemented in my theme, and they are also not displayed on the / cart page. From this I conclude that the data is not available as a result of a request to the address /cart.js, as well as in the .liquid template on the cart page. However, if you wait a few seconds, the data appears both in the pop-up window and on the / cart page. It looks like there is some kind of cache, or a delay in data transfer between the admin api and the Shopify frontend.

I have been trying to solve this problem for 2 days. I did an additional check for the existence of the variation via the admin api after it had already been added. I used a separate query for this. And only after a successful check, I added the variation to the cart. But the problem remains.

I've tried adding variations with and without an image. I've tried adding variations to the cart both by submitting a request to /cart/add.js and by submitting a standard form on the product page. I used the success function to make sure that the request was sent accurately. I even added a time delay and page reload after the add to cart request. But none of these methods give a 100% guarantee that the option will be displayed correctly in the shopping cart.

Please tell me if there is a solution for this problem?

P. S. I am attaching screenshots of the error and examples of my code.

Alert-Cart-Error.png

 

Pop-Up-Cart-Error.png

 

Pop-Up-Cart-Error2.png

 

Pop-Up-Cart-Error3.png

 doc_2021-09-04_21-13-49.png

 

doc_2021-09-04_21-14-26.png

 

doc_2021-09-04_21-14-58.png

 

admin-api-server-php-code-excample.png

 

Server admin API code excample:

 

 

<?php
header('content-type: application/json');

//Отключить вывод всех ошибок
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

//продолжить выполнение после закрытия браузера
ignore_user_abort(true);

require_once __DIR__ . '/inc/functions.php';

$product_id = $_GET['product_id'];
$token = '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';
$shop = 'rueckwand24';
$method = 'POST';
$query = $_POST;
$post_option1 = trim($_POST['variant']['option1']);
$post_option2 = trim($_POST['variant']['option2']);
$api_endpoint = "/admin/api/2021-07/products/" . $product_id . "/variants.json";

$result = shopify_call($token, $shop, $api_endpoint, $query, $method);
$status = $result['headers']['status'];
$request_result = stristr($status, '201 Created');

if($request_result !== false){
  $response = json_decode($result['response']);
  $variant_id = $response->variant->id;

  //Make sure that the option is present in the product
  $result_variants = shopify_call($token, $shop, $api_endpoint, array(), 'GET');
        file_put_contents(__DIR__ . '/logs/log_admin_api_after_add_variants_data.txt', var_export($result_variants, true));
        $response_variants_obj = json_decode($result_variants['response']);
        foreach($response_variants_obj->variants as $variant){
          $option1 = trim($variant->option1);
          $option2 = trim($variant->option2);

          if($post_option1 == $option1 and $post_option2 == $option2){
            echo '{"variant_id":"'.$variant->id.'"}';
          }
        }

  //echo '{"variant_id":"'.$variant_id.'"}';

}else{
  $response = json_decode($result['response']);
  if(isset($response->errors->base)){
      $error_base_str = $response->errors->base[0];
      $variant_exists = stristr($error_base_str, 'already exists');
      if($variant_exists !== false){
        //Variant exists lets get it from api
        $result_variants = shopify_call($token, $shop, $api_endpoint, array(), 'GET');
        file_put_contents(__DIR__ . '/logs/log_admin_api_result_variants_data.txt', var_export($result_variants, true));
        $response_variants_obj = json_decode($result_variants['response']);
        foreach($response_variants_obj->variants as $variant){
          $option1 = trim($variant->option1);
          $option2 = trim($variant->option2);

          if($post_option1 == $option1 and $post_option2 == $option2){
            echo '{"variant_id":"'.$variant->id.'"}';
          }
        }

      }
  }
}


file_put_contents(__DIR__ . '/logs/log_GET_data.txt', var_export($_GET, true));
file_put_contents(__DIR__ . '/logs/log_POST_data.txt', var_export($_POST, true));
file_put_contents(__DIR__ . '/logs/log_admin_api_result_data.txt', var_export($result, true));
?>

 

 


Frontend code excample:

 

 

    $(document).on('click', '#AddToCart-product-template-1', function(){
      event.preventDefault();
      var result_tab = getActiveTab();
      // console.log(result_tab);

      if(result_tab){
        //send config form
          // console.log('send config form!');

          let material = getMaterial();

          let config_width = $('#config_width').val();
          let config_height = $('#config_height').val();
          var units = $('#select_width').val();

          var option1 = config_width+' × '+config_height+' '+units;
          
          let square = getSquareCm();
           // console.log('square');
           // console.log(square);

          var new_price = getConfigPrice(square, material);
           // console.log('new_price');
           // console.log(new_price);

           var data_price = getDataPrice(new_price);
           console.log('data_price');
           console.log(data_price);

          updateVisualPrice(new_price);

          //add config variant
                
                $.ajax({
                    url: "https://daobot.sctest.ru/shopify_apps/rueckwand24/?product_id={{ product.id }}",
                    method: 'POST',
                    dataType: 'json',
                    data: {"variant":{"image_id": "{{ product.featured_image.id }}","option1": option1,
                    "option2":material,
                    "inventory_management":null,
                    "price":new_price
                  }},
                    crossDomain: true,
                      success: function (response) {
                        console.log(response);
                        console.log(response['variant_id']);
                        var variant_id = response['variant_id'];

                        $('#ProductSelect-product-template-1').append('<option data-sku="" data-option1="'+option1+'" data-option2="'+option1+'" data-content-price="'+new_price+'" data-price="'+data_price+'" value="'+variant_id+'">'+' '+option1+' / '+material+' - '+data_price+' </option>');

                        var sortBySelect = document.querySelector("#ProductSelect-product-template-1"); 
                        sortBySelect.value = variant_id; 
                        var event_result = sortBySelect.dispatchEvent(new Event("change"));
                        console.log('event_result:');
                        console.log(event_result);
                        if(event_result){

                          $('form#AddToCartForm-product-template-1').submit();
                          
                          // $.ajax({
                          //     type: 'POST',
                          //     url: '/cart/add.js',
                          //     dataType: 'json',
                          //     data: {
                          //       items: [
                          //         {
                          //           quantity: 1,
                          //           id: variant_id
                          //         }
                          //       ]
                          //     },
                          //     success: function(data){
                          //       //document.cookie = "configurator_show_cart=true";
                          //       //location.href=location.href;
                          //       document.location.href = '/cart'
                          //     }
                          // });

                        }
                      },
                    error: function (jqXHR, exception) {
                        console.log('error function');
                      }
                });

          //add config variant END

        //send config form END
      }
      else{
        //send default form
          console.log('send default form!');
          $('form#AddToCartForm-product-template-1').submit();
        //send default form END
      }
    });

 

 

 

Reply 1 (1)

Jason
Shopify Partner
11206 226 2311

If your code is attempting to add a variant to the cart, and it doesn't reflect until you refresh the page that does suggest this issue is in your theme code. 
Looking at the console logs should help determine success or failure as well.

Being able to see this live would help. I also noticed in one of your screenshots that you're pulling data from the shopifypreview url. Worth checking that you're using the same domain for the preview and ideally the store one (vs preview)

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★