The Customer library in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → is the $this->customer object through which all storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → code learns who is currently on the site: a logged-in customer or a guest, what group they belong to, their email, and their balance. The class itself is small, but prices for groups, checkoutThe order placement page. The fewer fields, the higher the conversion. More in the glossary →, the account area, and login modules all depend on it. That is why the differences between 3.0 and 4.1 matter here.
Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.
Where does $this->customer come from?
The object is created at the start of every request and placed in the registry. Any controllerCode that receives a request and prepares data. More in the glossary → or model gets it as a property, like the other core services (more in the article about the Registry).
- OpenCart 3.0: the
Cart\Customerclass is in thesystem/file. On the storefront,library/ cart/ customer.php catalog/creates it, and the customer's group is determined there as well.controller/ startup/ startup.php - OpenCart 4.1: the
\Opencart\System\Library\Cart\Customerclass, same path. On the storefront, a separatestartup/customercontroller creates it, which runs inaction_pre_actionright afterstartup/sessionandstartup/language.
The object also exists in the admin: in 3.0 it is created by admin/, in 4.1 by admin/. But the admin session has no customer_id, so there it is always a "guest." To check the administrator, use $this->user, not customer.
The main thing the constructor does: if the session has customer_id, it reads a row from the customer table with the condition status = '1' and fills in the properties. If the customer was disabled or deleted, the constructor calls logout(), and on the very next request the person becomes a guest. So, to immediately "kick" a customer off the site, it is enough to set their status to 0 in the admin: there is no need to clear sessions separately.
Another thing worth knowing about the constructor: on every request from a logged-in customer, it runs UPDATE customer with the current language_id and IP. In 3.0, SELECT with customer_ip is additionally executed and, if the IP is new, INSERT. In 4.1, the library's constructor does not write to customer_ip. For a regular store this is a minor detail. But if you have AJAX widgets that poll the site every few seconds, each such request writes to the customer table.
Which methods exist and how do they differ in 3.0 and 4.1?
The set of getters is almost the same, but the return types differ. This matters if you write a module for both branches or compare values strictly.
| Method | OpenCart 3.0 | OpenCart 4.1 |
|---|---|---|
isLogged() | returns customer_id (a string from the DB); for a guest null, after logout() in the same request '' | returns bool |
getId() | a DB row; for a guest null, after logout() '' | int, 0 for a guest |
getGroupId() | a DB row; for a guest null, after logout() '' | int |
getAddressId() | the value of the customer.address_id column | a separate query to address with the condition default = 1 |
getBalance() | the sum from customer_transaction, null if there are no transactions | float, 0 if there are no transactions |
getRewardPoints() | the sum from customer_reward, can also be null | float |
isSafe(), isCommenter() | none | present, from the safe and commenter columns |
The remaining getters (getFirstName(), getLastName(), getEmail(), getTelephone(), getNewsletter()) exist in both branches. This leads to two practical tips. First: do not write $this in code that must work on 3.0, because there the method returns the id. For a guest in 3.0 it returns null, and after logout() in the same request, ''. Both values are falsy, so do not compare them strictly. Second: getAddressId() in 4.1 makes a database query every time, so do not call it inside a loop.
Each getter returns what was read at the start of the request. If a module changed, say, the phone number through a model, getTelephone() will keep returning the old value until the end of the request. The structure of the tables themselves is described in the article about the customer table.
What does login() do and how are passwords stored?
The signature is the same in both branches: login($email, $password, $override = false), in 4.1 with the types string, string, bool and the return type bool. Email is compared case-insensitively, and the customer must have status = 1. On success, the method puts customer_id into the session and fills in the object's properties. It does nothing else: no cart, no addresses, no login attempt limit. All of that is handled by the controller that calls it.
Password hash
- OpenCart 3.0: the password is checked directly in SQL:
SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1(пароль)))))or the oldmd5. Registration and password change in theaccount/customermodel write a salted sha1 into thesaltcolumn. - OpenCart 4.1: first
password_verify(). If that does not match, it tries the old salted sha1, then md5. If the old format worked (orpassword_needs_rehash()says the hash is outdated), the password is immediately rewritten viapassword_hash(..., PASSWORD_DEFAULT).
In practice, this means that when moving from 3.0 to 4.1, customer passwords can be transferred as is: on first login, 4.1 will convert them to the modern hash by itself. The reverse does not work, because 3.0 does not understand password_hash() hashes.
The escaping trap
Request in both branches passes POST data through htmlspecialchars (how and why this works is described in the article about Request and Response). In 4.1, the login and registration controllers call html_entity_decode() before hashing, while in 3.0 the already converted string goes into the hash, and the same applies to login. As long as everything goes through standard forms, this is not noticeable. The problem appears when you create a customer or check a password from your own code: in 3.0, a password containing & or quotes must be passed in the same escaped form as the form, otherwise the hash will not match.
The $override parameter
With $override = true, the password is not checked at all, only the email and status. This is how the Login into Store button on the customer card in the admin works, as well as the orders API and logins through third-party services. Such a call should only happen after your own identity verification (a token, an OAuth signature, etc.). Never pass an email directly from the request into it.
How is the customer group determined and what is stored in the session?
Prices, discounts, special prices, and bonuses on the storefront are taken from config_customer_group_id, not from $this. Startup overrides this config key at the beginning of the request, and the order of sources differs between versions.
- OpenCart 3.0: first
session(set by the API when an administrator edits an order), then the logged-in customer's group, then->data['customer']['customer_group_id'] sessionfrom the guest checkoutPurchasing without registration. Enabled in the settings. More in the glossary →, otherwise the default group from the settings.->data['guest']['customer_group_id'] - OpenCart 4.1: first
session, then the logged-in customer's group. In 4.1, the->data['customer'] customerarray in the session is filled by login, registration, guest checkout, and profile editing alike.
So in a module that displays prices, take the group from $this. Then a guest who selected a "wholesale" group at checkout will see the same prices as the core. How the group gets into the cart calculation is covered in the article about the Cart library.
In both branches, sessions are stored by default by the db driver, so after login() there is no need to save anything separately: the data is written at the end of the request. How session drivers work is explained in the article about sessions and cache.
What is customer_token in OpenCart 4.1?
In 4.1, a second level of verification has been added to the account area. After login, the controller puts customer_token into the session (a string from oc_token(26)), and account pages open only when this same token is present in the URL. The check is done by the account/ method: it returns true only if the customer is logged in and the customer_token from GET matches the session value.
For a module author, two rules appear that did not exist in 3.0:
- Build links to account pages (your own or standard ones) with the
customer_tokenparameter, otherwise the customer will be redirected to the login page even though they are logged in. - Protect your own account page with the same call, not only with
isLogged().
Example: an account page in a module (OpenCart 4.1)
public function index(): void {
if (!$this->load->controller('account/login.validate')) {
$this->session->data['redirect'] = $this->url->link('extension/mymodule/account/bonus', 'language=' . $this->config->get('config_language'));
$this->response->redirect($this->url->link('account/login', 'language=' . $this->config->get('config_language'), true));
}
$data['history'] = $this->url->link('account/order', 'language=' . $this->config->get('config_language') . '&customer_token=' . $this->session->data['customer_token']);
// ...
}
In 3.0 there is no such token, and for an account page the $this check with a redirect to account/login is sufficient.
How do you log in a customer from your own module?
A typical task is login via Google, via an SMS code, or via a one-time link. login() with $override is only half the job here. The standard account/login controller does the rest, and the module needs to repeat it, otherwise the cart, addresses, or account area will behave strangely.
Example: login after your own identity verification (OpenCart 4.1)
// getCustomerByEmail() — метод власної моделі модуля, не ядра
$this->load->model('extension/mymodule/account/customer');
$customer_info = $this->model_extension_mymodule_account_customer->getCustomerByEmail($verified_email);
if ($customer_info && $customer_info['status'] && $this->customer->login($customer_info['email'], '', true)) {
$this->session->data['customer'] = [
'customer_id' => $customer_info['customer_id'],
'customer_group_id' => $customer_info['customer_group_id'],
'firstname' => $customer_info['firstname'],
'lastname' => $customer_info['lastname'],
'email' => $customer_info['email'],
'telephone' => $customer_info['telephone'],
'custom_field' => $customer_info['custom_field']
];
unset($this->session->data['order_id']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
$this->session->data['customer_token'] = oc_token(26);
}
Here $verified_email is the email that your module has already confirmed (through the OAuth provider's response or a code). getCustomerByEmail() is a method of the module's own model: a simple SELECT from the customer table by LCASE(email). In 3.0 the sequence is shorter: login($email, '', true), then unset($this and, if taxes are calculated based on the customer's address, the default address in payment_address or shipping_address, as account/login does. A ready-made example of such a login is discussed in the review of logging in via Google.
The limit on failed attempts (Max Login Attempts on the Option tab in the settings) is counted by the controller through the customer_login table, not by the library. A custom login form with a password must itself track attempts in customer_login in the same way as the standard login controller, otherwise password brute-forcing through it will not be limited.

The Login into Store button in the admin
Logging in as a customer from the administrator is implemented differently in each version. In 3.0, the admin writes a one-time token into the customer.token column and opens account/. In 4.1, the token goes into a separate customer_token table with the type login, and the login goes through account/login.token with the parameters email and code.

Summary
$this->customeris created at the start of every request, re-reads the customer from the database, and logs them out if the status is 0.- In 3.0, getters return DB rows, while
isLogged()returns the id. In 4.1, the types are strict, andgetAddressId()makes a query every time. - 4.1 verifies passwords through
password_verify()and itself migrates old sha1 and md5 hashes, so passwords from 3.0 carry over without a reset. - For prices and discounts, use
config_customer_group_id, not the group from the customer object. - In 4.1, account pages require
customer_token, and the library'slogout()does not clearsession['customer']. - Programmatic login is
login(..., true)plus the same session preparation thataccount/loginperforms.
Next, it is worth looking at how customer data flows into orders, in the article about checkout in code. Other materials on the cart, checkout, and statuses are collected in the section "Cart, checkout and orders in code".