# Customer Library in OpenCart: Customer, Login and Session in 3.0 and 4.1

> How the Customer library works in OpenCart 3.0 and 4.1: where $this->customer comes from, what login() does, how passwords are stored, the customer group and customer_token.

Джерело: https://opencartcode.com/en/wiki/dev-flows/customer-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

The Customer library in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) is the `$this->customer` object through which all [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) 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, [checkout](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#checkout), 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 [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) or model gets it as a property, like the other core services (more in the article about the [Registry](https://opencartcode.com/en/wiki/dev-architecture/registry-opencart)).

- **OpenCart 3.0:** the `Cart\Customer` class is in the `system/library/cart/customer.php` file. On the storefront, `catalog/controller/startup/startup.php` creates it, and the customer's group is determined there as well.
- **OpenCart 4.1:** the `\Opencart\System\Library\Cart\Customer` class, same path. On the storefront, a separate `startup/customer` controller creates it, which runs in `action_pre_action` right after `startup/session` and `startup/language`.

The object also exists in the admin: in 3.0 it is created by `admin/controller/startup/startup.php`, in 4.1 by `admin/controller/startup/application.php`. 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->customer->isLogged() === true` 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](https://opencartcode.com/en/wiki/dev-database/tablicia-customer-opencart).

## 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 old `md5`. Registration and password change in the `account/customer` model write a salted sha1 into the `salt` column.
- **OpenCart 4.1:** first `password_verify()`. If that does not match, it tries the old salted sha1, then md5. If the old format worked (or `password_needs_rehash()` says the hash is outdated), the password is immediately rewritten via `password_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](https://opencartcode.com/en/wiki/dev-architecture/opencart-request-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->customer->getGroupId()`. Startup overrides this config key at the beginning of the request, and the order of sources differs between versions.

- **OpenCart 3.0:** first `session->data['customer']['customer_group_id']` (set by the API when an administrator edits an order), then the logged-in customer's group, then `session->data['guest']['customer_group_id']` from the [guest checkout](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#guest-checkout), otherwise the default group from the settings.
- **OpenCart 4.1:** first `session->data['customer']`, then the logged-in customer's group. In 4.1, the `customer` array 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->config->get('config_customer_group_id')`. 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](https://opencartcode.com/en/wiki/dev-flows/opencart-shopping-cart).

> In 4.1, `$this->customer->logout()` removes only `customer_id` from the session. The `session->data['customer']` array and `customer_token` remain, and with them the customer's group in `config_customer_group_id`. The standard `account/logout` clears them separately. If you log a customer out from a module, repeat these `unset`.

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](https://opencartcode.com/en/wiki/dev-architecture/opencart-session).

## 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/login.validate` 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:

1. Build links to account pages (your own or standard ones) with the `customer_token` parameter, otherwise the customer will be redirected to the login page even though they are logged in.
2. Protect your own account page with the same call, not only with `isLogged()`.

Example: an account page in a module (OpenCart 4.1)

```php
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->customer->isLogged()` 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)

```php
// 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->session->data['guest'])` 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](https://opencartcode.com/en/blog/vkhid-cherez-google-v-opencart-ohliad-jet-reg).

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.

Option tab: the field for the maximum number of customer login attempts · OpenCart 4.1.0.4

### 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/login&token=...`. 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`.

Customer list: the action to log into the store on behalf of a customer · OpenCart 4.1.0.4

## Summary

- `$this->customer` is 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, and `getAddressId()` 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's `logout()` does not clear `session['customer']`.
- Programmatic login is `login(..., true)` plus the same session preparation that `account/login` performs.

Next, it is worth looking at how customer data flows into orders, in the article about [checkout in code](https://opencartcode.com/en/wiki/dev-flows/checkout-opencart-kod). Other materials on the cart, checkout, and statuses are collected in the section ["Cart, checkout and orders in code"](https://opencartcode.com/en/wiki/dev-flows).

## FAQ

**Can I get customer data in the admin through $this->customer?**

No, the object exists in the admin, but the admin session has no customer_id, so it is empty. Get customer data with the customer/customer model by id.

**How do I check in a Twig template whether the customer is logged in?**

Pass a flag from the controller, for example $data['logged'] = $this->customer->isLogged(). The template has no customer object, only variables from $data.

**Why does the customer get logged out after changing the domain or switching to https?**

The session is kept in a cookie tied to the domain and path. After the address changes, the browser does not send the old cookie, and the new domain has no customer_id in the session.

**Does the cart stay after the customer logs in?**

Yes, the Cart library links guest items to customer_id on the next request after login, so items from the guest cart are not lost.
