我瞭解使用隨機數的過程,當我創建自己的模板時。 但我正在開發一個ReactJS應用程序,它只使用Wordpress REST API來提取數據,所以用戶永遠不會到達index.php,但會對Ajes的WP Api進行調用。Wordpress Auth + Nonces + Ajax + No模板 - Cookie現時值無效
現在我無法得到nonce東西的工作。 這是我迄今所做的:
我增加了以下端點:
register_rest_route('frontend', '/customer/', array(
'methods' => 'GET',
'callback' => 'get_customer'
));
register_rest_route('frontend', '/customer/', array(
'methods' => 'POST',
'callback' => 'create_user_and_login'
));
這些都是我的功能:
function get_customer()
{
return get_current_user_id();
}
function create_user_and_login(){
// dummy data for testing
$credentials = ['user_login' => '[email protected]mail.de', 'user_password' => 'XXXX', 'remember' => true];
// create a new user/customer via woocommerce
$customerId = wc_create_new_customer($credentials['user_login'], $credentials['user_login'], $credentials['user_password']);
if(is_a($customerId,'WP_Error')) {
return $customerId;
}
// get the user & log in
$user = get_user_by('id', $customerId);
if($user) {
wp_set_current_user($customerId);
wp_set_auth_cookie($customerId);
}
// create new nonce and return it
$my_nonce = wp_create_nonce('wp_rest');
return $my_nonce;
}
如果我現在運行的支撐柱,/customer
觸發create_user_and_login()
,新創建的隨機數在ajax響應中返回。然後我用回現時運行我的下一個請求,一個GET到/customer?_wpnonce=MY-NONCE
,但我得到的錯誤:
{
"code": "rest_cookie_invalid_nonce",
"message": "Cookie nonce is invalid",
"data": {
"status": 403
}
}
我檢查the nonce documentation,但我無法找到我的問題的解決方案。會話可能會不同步嗎?因此,在錯誤的會話上創建了隨機數或wp_set_auth_cookie
和wp_set_current_user
未被正確調用?或者我必須使用wp_localize_script
功能嗎?這會產生問題,因爲我希望將ReactJS和Wordpress後端分開。
我在POST後得到了兩個cookie,一個wordpress
cookie和一個wordpress_logged_in
cookie。
我缺少什麼?
非常感謝!這樣可行。 – Dario