'Nonce has not been verifed - Woocommerce problem

I have problem with nonce,

I have ajax calls that download cost and dates from API, recently I made change to posts, they are not wordpress posts that "pretend" to be a products, they are now products from woocommerce.

Old posts have no problems with veryfing nonce, new ones can't verify nonces. I really didn't change anything besides making Woocommerce.php that use my product.twig instead of making products using gutenberg.

Here's my jsData:

declare const jsData: { ajaxUrl: string; nonce: string; post_id: number; google_api_key: string; theme_uri: string }

Here's ajax call:

 async addToCart(dateStart: DateTime, dateEnd: DateTime) {
const formData = new FormData()

formData.append('nonce', jsData.nonce)
formData.append('action', 'addToCart')
formData.append('product_id', `${jsData.post_id}`)
formData.append('booked_date_start', dateStart.format('YYYY-MM-DD'))
formData.append('booked_date_end', dateEnd.format('YYYY-MM-DD'))

return callAjax({
  method: 'POST',
  body: formData,
}).then(res => res.json())

}

This is my assets.php where I create nonce and i transfer it to js bundle

$nonce = wp_create_nonce('ajax');
    // type in jsData.d.ts
    $transferDatas = [
        'ajaxUrl' => admin_url('admin-ajax.php?data-nonce="' . $nonce . '"'),
        'nonce' => $nonce,
        'post_id' => get_the_ID(),
        'theme_uri' => get_stylesheet_directory_uri(),
        'google_api_key' => get_field('google_api_key', 'options'),
    ];
    wp_localize_script('bundle-js', 'jsData', $transferDatas);

And this is how I try to verify nonce

if (wp_verify_nonce($_POST['nonce'], 'ajax')) ...

I tried to change post to REQUEST, and I added action which register session on init like below in my functions.php

function register_my_session()
{
    if( !session_id() )
    {
        session_start();
    }
}

Do you have any ideas what can I change to make those nonces verifed like on old posts (that are still up and work - new ones doesnt work)?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source