我们使用wordpress JSON对用户进行登录,并添加/更新/删除购物车项。我们正在用register_rest_route函数来完成这个任务。
我们使用此代码删除购物车项:
function remove_from_cart(WP_REST_Request $req)
{
$resp = null;
$cart_item = $req['cart_item'];
try {
WC()->cart->remove_cart_item($cart_item);
} catch (Exception $e) {
$resp = $e;
}
return rest_ensure_response(new CartResponse());
}这对客人来说是很好的。但是,一旦登录用户尝试了它,购物车就会在页面重新加载之后返回到它的正常状态。new CartResponse()创建的响应正确地显示了没有删除项的购物车。但是,在页面重新加载之后,项目仍然存在。因为这只发生在登录用户,而不是客人,我认为这是一个会话问题。另外,使用以下方法更新购物车对于登录用户也是有效的:
function update_cart_item(WP_REST_Request $req)
{
$resp = null;
$cart_item = $req['cart_item'];
try {
if ($cart_item && $cart_item['quantity']) {
WC()->cart->set_quantity($cart_item['key'], $cart_item['quantity']);
}
} catch (Exception $e) {
$resp = $e;
}
return rest_ensure_response(new CartResponse());
}不幸的是,将数量设置为0也不起作用。
这就是我们如何登录用户:
function login_customer(WP_REST_Request $req)
{
$body = $req->get_body();
$input = json_decode($body, TRUE);
$credentials = ['user_login' => $input['email'], 'user_password' => $input['password']];
$user = wp_signon($credentials, false);
if (is_a($user, 'WP_Error') || !$user) {
// if an error occurs, return null
return rest_ensure_response(null);
}
$resp = new CustomerResponse($user->ID);
return rest_ensure_response($resp);
}我们没有使用任何缓存插件。这里怎么了?
以下是所有会话cookie的列表:

编辑:
我刚刚检查了饼干,同时登录并删除了一个购物车项目。
因此,似乎购物车哈希存储在某个地方,并在重新加载时恢复,但在删除购物车项时没有正确更新。
发布于 2017-12-29 18:36:16
似乎您需要非need对删除请求进行身份验证。
现在,我在标题中为每个响应添加非Now:
function add_cors_http_header(){
header("X-WP-Nonce: ".wp_create_nonce('wp_rest'));
}
add_action('init','add_cors_http_header');在前面我把它设置为:
let nonce: string = null;
export const fetchNoAuth = (endpoint: string, method: string = 'GET', data: any = null): Promise<any> => {
let headers: any = {'Content-Type': 'application/json'};
if (nonce) {
headers['X-WP-Nonce'] = nonce;
}
return fetch('http://' + apiUrl + apiPath + endpoint + '?' + debugQuery, {
method,
credentials: 'include',
headers,
body: data ? JSON.stringify(data) : null
})
.then((data) => {
const nonceFromResponse = data.headers.get('X-WP-Nonce');
if (nonceFromResponse) {
nonce = nonceFromResponse;
} else {
nonce = null;
}
return data;
})
};确保请求中的标头名为X-WP-Nonce
https://stackoverflow.com/questions/48026219
复制相似问题