Ajax fetch api работает только в первый раз с гостевым пользователем - PullRequest
1 голос
/ 08 марта 2020

У меня есть код с моей темой WordPress. Я пытаюсь добавить продукт в корзину на странице продукта с помощью API загрузки. Проблема, с которой я здесь столкнулся, состоит в том, что код запускается только в первый раз, со второго раза он вернет ошибку 403.

Мой JS код:

var request = new Request( ajax_url,
    {
        method: 'POST',
        body: 'action=ajax_add_to_cart&ajax_nonce=' + data.ajax_nonce,
        credentials: 'include',
        headers: new Headers(
            {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            }
        )
    }
);

fetch( request )
    .then(
        function( res ) {
            if ( 200 !== res.status ) {
                // Always print from the second time.
                console.log( 'Status Code: ' + res.status );
                return;
            }

            res.json().then(
                function( data ) {
                    // Only print on the first time.
                    console.log( data );
                }
            );
        }
    );

Мой php код:

add_action( 'wp_ajax_ajax_add_to_cart', 'ajax_single_add_to_cart' );
add_action( 'wp_ajax_nopriv_ajax_add_to_cart', 'ajax_single_add_to_cart' );
function ajax_add_to_cart() {
    check_ajax_referer( 'ajax_add_to_cart', 'ajax_nonce' );

    $response = array();

    if ( ! isset( $_POST['product_id'] ) || ! isset( $_POST['product_qty'] ) ) {
        wp_send_json_error();
    }

    $product_id        = absint( $_POST['product_id'] );
    $product_qty       = absint( $_POST['product_qty'] );
    $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $product_qty );

    if ( isset( $_POST['variation_id'] ) ) {
        $variation_id = absint( $_POST['variation_id'] );
    }

    if ( isset( $_POST['variations'] ) ) {
        $variations = (array) json_decode( sanitize_text_field( wp_unslash( $_POST['variations'] ) ), true );
    }

    if ( $variation_id && $passed_validation ) {
        WC()->cart->add_to_cart( $product_id, $product_qty, $variation_id, $variations );
    } else {
        WC()->cart->add_to_cart( $product_id, $product_qty );
    }

    ob_start();
    woocommerce_mini_cart();
    $response['content'] = ob_get_clean();

    wp_send_json( $response );
}

Могу ли я заменить эту одноразовую проверку на?

check_ajax_referer( 'ajax_add_to_cart', 'ajax_nonce' );

Проблема, описанная выше, решена в режиме инкогнито (или в гостевом режиме), в обычном режиме она отлично подходит для me.

Может быть, у меня чего-то не хватает для пользователя, который не вошел в систему (вышел из системы). Любые предложения будут оценены, спасибо.

...