# OAuth in OpenCart: Google and Social Login in Modules for 3.0 and 4.1

> How to set up Google and other OAuth provider login in OpenCart 3.0 and 4.1 modules: redirect URI, state, account linking table, customer creation, and the SameSite trap.

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

OAuth in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) is implemented as a module: the "Sign in with Google" button sends the customer to the provider, the provider returns them to your [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller)'s callback with a code, the module exchanges the code for user data, and logs the customer in through the Customer library. Neither 3.0 nor 4.1 includes built-in social login in the core. However, everything needed for it is available: [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) controllers, the customer model, the `login()` with the `$override` parameter, and events. Below is the complete flow and the places where such a module most often breaks.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## What does the OAuth flow look like in the store?

Sign-in uses the authorization code flow. It is supported by Google, Facebook, Apple, and most other providers. For Google, this is OpenID Connect on top of OAuth 2.0: in addition to the access token, the provider returns an ID token with the user identifier (`sub`) and email.

```mermaid
sequenceDiagram
  participant B as Browser
  participant S as Store
  participant G as Provider
  B->>S: clicks Sign in with Google
  S->>S: creates state and code_verifier in session
  S->>B: redirect to provider page
  B->>G: sign in and consent
  G->>B: redirect to callback with code and state
  B->>S: callback with code and state
  S->>S: checks state against session
  S->>G: exchanges code for tokens
  G->>S: ID token with sub and email
  S->>S: looks up link, creates or logs in customer
  S->>B: redirect to account or checkout
```

The module needs two public methods in the storefront controller: `login` (builds the provider URL and redirects) and `callback` (handles the response). File placement and routes are the same as for any module controller:

- **OpenCart 3.0:** `catalog/controller/extension/module/mysocial.php`, routes `extension/module/mysocial/login` and `extension/module/mysocial/callback`.
- **OpenCart 4.1:** `extension/mysocial/catalog/controller/module/mysocial.php`, routes `extension/mysocial/module/mysocial.login` and `extension/mysocial/module/mysocial.callback`. The extension must be installed, otherwise the namespace will not be registered.

The method separator (slash or dot) is explained in the article about [route= routing](https://opencartcode.com/en/wiki/dev-mvc/opencart-route). Store the client ID and secret in the module settings (for example `module_mysocial_client_id`, `module_mysocial_secret`), not in the code.

## Redirect URI: why does the provider say "mismatch"?

The provider accepts only the return address you registered in its console, matching it character for character. In OpenCart, it is easy to break in three ways.

1. **Encoded ampersands.** `$this->url->link()` in 3.0 encodes `&` as `&amp;` when arguments are passed. In 4.1 it does the same unless the third parameter (`$js`) is `true`. An address with `&amp;` will not match the registered one.
2. **Language parameter in 4.1.** Storefront links in 4.1 usually contain `language=uk-ua`. If the redirect URI is built with the language, it will differ for each store language, and the provider will reject those that are not registered. Build the callback without the language, and store the customer's language in the session along with `state`.
3. **Protocol and domain.** `http` instead of `https`, `www`, or without it are different addresses for the provider. Register the one the store actually runs on, and disable redirects on the callback path.

Example: login() method (OpenCart 4.1)

```php
public function login(): void {
    $state    = oc_token(32);
    $verifier = oc_token(64);

    $this->session->data['mysocial'] = [
        'state'    => $state,
        'verifier' => $verifier,
        'language' => $this->config->get('config_language'),
        'redirect' => $this->session->data['redirect'] ?? ''
    ];

    $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');

    $query = http_build_query([
        'client_id'             => $this->config->get('module_mysocial_client_id'),
        'redirect_uri'          => $this->callbackUrl(),
        'response_type'         => 'code',
        'scope'                 => 'openid email profile',
        'state'                 => $state,
        'code_challenge'        => $challenge,
        'code_challenge_method' => 'S256'
    ]);

    $this->response->redirect('https://accounts.google.com/o/oauth2/v2/auth?' . $query);
}

private function callbackUrl(): string {
    return $this->url->link('extension/mysocial/module/mysocial.callback', '', true);
}
```

Here `oc_token()` is a 4.1 core helper (it is called `token()` in 3.0). Empty arguments in `link()` mean the address will contain neither a language nor ampersands. In 3.0 the signature is `link($route, $args = '', $secure = false)`, so there the third parameter `true` requests an https address, not disabling encoding.

## The SameSite trap: the session is lost after returning from the provider

This is the most common cause of the "invalid state" error in OpenCart 4.1. Here is how it happens.

In 4.1 the session cookie is set with a SameSite [attribute](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#attribute). The value comes from the Session Samesite Cookie setting on the "Server" tab in System → Settings. The installer writes `Strict` there. With `Strict`, the browser does not send the cookie when the customer is redirected to your site from another domain, which is exactly what happens when the provider returns them to the callback.

The chain of consequences is as follows: the callback arrives without the cookie, `startup/session` opens a new empty session, `state` is not in it, and the check fails. Worse, the response sets a new session cookie, and the customer loses the previous session, for example with checkout data.

Server tab: SameSite setting for the session cookie · OpenCart 4.1.0.4

- **Lax** is the correct value for a store with sign-in via Google, Facebook, and similar providers that return the customer with a GET redirect. The cookie is sent when following a link from another site, but not in background POST requests from third-party pages.
- **None** is needed only for providers that return the response via a POST form (`response_mode=form_post`; this is what Apple sign-in does, for example, when requesting name and email). It works only together with HTTPS.

In 3.0 the session cookie is set without a SameSite attribute, and modern browsers apply the `Lax` default rules to it. So the GET callback receives the session without additional settings. How sessions work in both branches is described in the article about [sessions and cookies](https://opencartcode.com/en/wiki/dev-architecture/opencart-session).

## Callback: verification, code exchange, and customer lookup

The callback performs four steps in order. The order matters, and none of them can be skipped.

1. **Verify `state`** from the session via `hash_equals()` and immediately remove it from the session. Without this, a CSRF attack is possible: an attacker can "log in" the customer into the attacker's account.
2. **Exchange `code` for tokens** with a server-side POST request to the provider with `client_secret` and `code_verifier`. This request goes from the server, not from the browser.
3. **Get and verify the identity.** For Google, `sub` (the persistent user identifier), `email`, and `email_verified` are useful. If you parse the ID token manually, check `aud` (your client ID), `iss`, and expiration. It is simpler to request the data from the provider's userinfo endpoint using the access token.
4. **Find or create the customer and log them in.**

### Linking by sub, not by email

The provider's email may change, and the store may already have a customer with the same email registered with a password. Therefore, create a link table where the key is the pair "provider + sub":

Example: social account link table

```sql
CREATE TABLE IF NOT EXISTS `oc_mysocial_link` (
  `provider` varchar(16) NOT NULL,
  `subject` varchar(255) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `date_added` datetime NOT NULL,
  PRIMARY KEY (`provider`, `subject`),
  KEY `customer_id` (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

Lookup logic: first, look for a link by `sub`. If there is none, look up the customer by email via `getCustomerByEmail()` of the `account/customer` model, but only when the provider has confirmed the email (`email_verified`). Otherwise, anyone who creates a provider account with someone else's email will be signed into the store as that customer. If you find a match by a confirmed email, create the link. If not, create the customer. The core customer tables are described in the article about the [customer table](https://opencartcode.com/en/wiki/dev-database/tablicia-customer-opencart), and the module's tables are described in the article about [custom module tables](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-tables).

## How to create a customer and log them in?

Create the customer with the storefront `account/customer` model and the `addCustomer()` method, not with direct SQL. This way, core events on `addCustomer/after` will fire: the welcome email to the new customer (`mail/register`), the notification to the store owner, and the activity log entry. The trigger is `catalog/model/account/customer/addCustomer/after` in 3.0 and `catalog/model/account/customer.addCustomer/after` in 4.1.

Example: creating a customer from provider data (OpenCart 4.1)

```php
$this->load->model('account/customer');

$customer_id = $this->model_account_customer->addCustomer([
    'firstname'    => $profile['given_name'] ?? '',
    'lastname'     => $profile['family_name'] ?? '',
    'email'        => $profile['email'],
    'telephone'    => '',
    'password'     => oc_token(32),
    'custom_field' => []
]);
```

Things to know about this call:

- **All keys are required.** `addCustomer()` in both versions directly reads `firstname`, `lastname`, `email`, `telephone`, and `password`. If any key is missing, a PHP warning will appear, and the phone may turn out to be required by your checkout. Pass empty strings and ask the customer to complete the profile later.
- **The password is random.** A customer created via social login does not know the password. If they want to sign in the regular way, they can use password recovery.
- **The [customer group](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#customer-group)** is taken from `customer_group_id` only if it is among the groups allowed at registration. Otherwise, the default group is set. If that group requires approval, the customer is created with status 0, and `login()` will not let them in. In that case, show a message like "account awaiting approval" rather than a login error.
- **In 3.0**, `custom_field` expects an array with the key `account`, and the password is hashed with sha1 and a salt. A random token made of letters and digits causes no problems here.

The sign-in itself is `$this->customer->login($email, '', true)` plus session preparation performed by the standard `account/login` controller. In 4.1 this is the `session->data['customer']` array, a new `customer_token`, and clearing checkout data. The full list of steps for both versions is covered in the article about the [Customer library](https://opencartcode.com/en/wiki/dev-flows/customer-opencart). After sign-in, redirect the customer to the saved `redirect` or to their account, and be sure to pass the language they came from.

> If two-factor customer verification is enabled in 4.1 (Two-factor Security on the "Option" tab), `startup/authorize` redirects the customer to the verification page after any sign-in, including social login, until they have a valid token. Account for this in your scenario: signing in through a provider does not bypass the store's 2FA.

## What else should be considered in the module?

- **Button in the template.** Add it to the sign-in, registration, and checkout pages using an event on the view (`view/*/before` or `after`), or with your own module in the layout, rather than editing the theme template. This way the button survives theme updates.
- **Unlinking.** Give the customer a page in their account listing linked providers with an "unlink" button. In 4.1, such a page must verify `customer_token`.
- **Deleting a customer.** When an administrator deletes a customer, remove their links using an event on the admin model `customer/customer`. Otherwise, the next sign-in with the same `sub` will find a link to a nonexistent `customer_id`.
- **Installation and uninstallation.** The module's install `install()` creates the link table and events, and uninstall `uninstall()` removes them. Details are in the article about [module install and uninstall](https://opencartcode.com/en/wiki/dev-extensions/install-opencart-module).
- **Logs without secrets.** Log code exchange errors (HTTP code and provider error text), but do not write access tokens or `client_secret` to the log.

How this looks in a ready-made solution with admin configuration can be seen in the overview of [Google sign-in for OpenCart](https://opencartcode.com/en/blog/vkhid-cherez-google-v-opencart-ohliad-jet-reg).

## Summary

- Social login is an authorization code flow with two storefront controller methods: `login` and `callback`.
- Build the redirect URI without the language and without encoded ampersands, and register it with the provider exactly as it is, with the correct protocol and domain.
- In 4.1, change the session cookie SameSite from `Strict` (the value after installation) to `Lax`, otherwise the callback arrives without the session and the `state` check fails.
- Verify `state`, use PKCE, and exchange the code on the server.
- Link accounts by "provider + sub," and merge with an existing customer by email only when the provider has confirmed it.
- Create the customer via `addCustomer()` with all keys, and log in via `login(..., true)` with the same session preparation as `account/login`.

Other materials on exchanging data with external systems, including the [custom JSON endpoint](https://opencartcode.com/en/wiki/dev-api/api-endpoint-opencart), are collected in the ["API and integrations"](https://opencartcode.com/en/wiki/dev-api) section.

## FAQ

**Can I use one client ID for several stores in a multistore setup?**

Yes, if the redirect URI of each domain is registered in the provider's console. The callback for each store must lead to its own domain, because the session is tied to that domain.

**What should I do if the provider does not return an email?**

Some providers return email only with separate permission, or not at all. In that case, ask the customer to enter their email on an intermediate page and confirm it by email before creating the customer.

**Is consent to personal data processing required for social network login?**

Yes, you receive the name and email from a third party, so the store's privacy policy should describe this. Check the specific requirements under current legislation or consult a lawyer.

**Does social network login work at checkout without losing the cart?**

Yes, if the session is preserved after returning from the provider. The guest cart is linked to the customer after login, so first check the SameSite settings in 4.1.
