I’m developing a custom OpenCart 4.x module that adds a button to the order page to log order data via AJAX. The button makes a GET request to my custom controller, but I’m getting an “Invalid token session” error despite passing a valid user_token.
Button in order_info.twig:
$('#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) {
// handle response
},
error: function(xhr, status, error) {
// handle error
}
});
});
Controller
<?php
namespace OpencartAdminControllerExtensionModule;
class log_order extends OpencartSystemEngineController
{
public function log(): void
{
$json = array();
// Check if user is logged in and has permission
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 {
// Process order logging
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
When I click the button, the AJAX request goes to:
http://localhost/admin123/index.php?route=extension/module/log_order/log&user_token=bcaa4bb96fb680351565d57951b2ef79&order_id=2
But instead of reaching my controller, I get “401 Unauthorized”
What I’ve Tried:
- Verified user_token: The token is being passed correctly from the template
- Session check: The user is logged in and can access other admin pages
- Permission check: The user has modify permissions for orders
- Route verification: The controller file exists in the correct location
OpenCart 4.1.0.3