You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCart 4.x AJAX请求传递有效user_token仍返回“Invalid token session”(401 Unauthorized)问题求助

OpenCart 4.x AJAX请求传递有效user_token仍返回“Invalid token session”(401 Unauthorized)问题求助

大家好,我正在开发一个OpenCart 4.1.0.3的自定义模块,需求是在订单详情页加一个按钮,通过AJAX请求记录订单数据。现在按钮点击后会发起GET请求到我的自定义控制器,但明明已经传了有效的user_token,却一直收到“Invalid token session”的401 Unauthorized错误,实在卡壳了,想请教各位大佬!

我的实现代码

订单详情页模板(order_info.twig)中的按钮JS逻辑

$('#log-order-button').on('click', function() {
    const orderId = '{{ order_id }}';
    $.ajax({
        url: 'index.php?route=extension/module/log_order/log&user_token={{ user_token }}&order_id=' + orderId,
        type: 'GET',
        dataType: 'json',
        success: function(json) {
            // 处理响应
        },
        error: function(xhr, status, error) {
            // 处理错误
        }
    });
});

自定义控制器代码(admin/controller/extension/module/log_order.php)

<?php
namespace Opencart\Admin\Controller\Extension\Module;

class log_order extends \Opencart\System\Engine\Controller {
    public function log(): void {
        $json = array();

        // 检查用户登录和权限
        if (!isset($this->request->get['user_token']) || !$this->user->isLogged()) {
            $json['error'] = 'Permission denied or not logged in.';
        } elseif (!$this->user->hasPermission('modify', 'sale/order')) {
            $json['error'] = 'You do not have permission to modify orders.';
        } else {
            // 订单记录逻辑(暂未实现)
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

请求情况

点击按钮后,实际发起的请求URL是:
http://localhost/admin123/index.php?route=extension/module/log_order/log&amp;user_token=bcaa4bb96fb680351565d57951b2ef79&amp;order_id=2

但服务器直接返回401 Unauthorized,根本没走到我控制器里的逻辑。

我已经尝试过的排查步骤

  • 验证user_token:确认模板传递的token是正确的,和当前会话中的token一致
  • 会话检查:当前用户已登录,能正常访问其他后台页面
  • 权限检查:用户确实拥有sale/order的modify权限
  • 路由验证:控制器文件放在了正确的路径下,文件名和命名空间都没问题

有没有大佬能帮我看看哪里出问题了?感激不尽!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 10:39:51