OAuth 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 implemented as a module: the "Sign in with Google" button sends the customer to the provider, the provider returns them to your controllerCode that receives a request and prepares data. More in the glossary →'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: storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → 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.
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/, routescontroller/ extension/ module/ mysocial.php extension/andmodule/ mysocial/ login extension/.module/ mysocial/ callback - OpenCart 4.1:
extension/, routesmysocial/ catalog/ controller/ module/ mysocial.php extension/andmysocial/ module/ mysocial.login extension/. The extension must be installed, otherwise the namespace will not be registered.mysocial/ module/ mysocial.callback
The method separator (slash or dot) is explained in the article about route= routing. 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.
- Encoded ampersands.
$thisin 3.0 encodes->url ->link() &as&when arguments are passed. In 4.1 it does the same unless the third parameter ($js) istrue. An address with&will not match the registered one. - 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 withstate. - Protocol and domain.
httpinstead ofhttps,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)
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 attributeA product characteristic that does not affect the price: material, weight, power. It is set in "Catalog → Attributes" and displayed on the "Specification" tab. More in the glossary →. 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.

- 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.
Callback: verification, code exchange, and customer lookup
The callback performs four steps in order. The order matters, and none of them can be skipped.
- Verify
statefrom the session viahash_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. - Exchange
codefor tokens with a server-side POST request to the provider withclient_secretandcode_verifier. This request goes from the server, not from the browser. - Get and verify the identity. For Google,
sub(the persistent user identifier),email, andemail_verifiedare useful. If you parse the ID token manually, checkaud(your client ID),iss, and expiration. It is simpler to request the data from the provider's userinfo endpoint using the access token. - 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
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, and the module's tables are described in the article about custom 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/ in 3.0 and catalog/ in 4.1.
Example: creating a customer from provider data (OpenCart 4.1)
$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 readsfirstname,lastname,email,telephone, andpassword. 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 groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary → is taken from
customer_group_idonly 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, andlogin()will not let them in. In that case, show a message like "account awaiting approval" rather than a login error. - In 3.0,
custom_fieldexpects an array with the keyaccount, 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 plus session preparation performed by the standard account/login controller. In 4.1 this is the session 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. After sign-in, redirect the customer to the saved redirect or to their account, and be sure to pass the language they came from.
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/*/beforeorafter), 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 samesubwill find a link to a nonexistentcustomer_id. - Installation and uninstallation. The module's install
install()creates the link table and events, and uninstalluninstall()removes them. Details are in the article about module install and uninstall. - Logs without secrets. Log code exchange errors (HTTP code and provider error text), but do not write access tokens or
client_secretto 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.
Summary
- Social login is an authorization code flow with two storefront controller methods:
loginandcallback. - 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) toLax, otherwise the callback arrives without the session and thestatecheck 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 vialogin(..., true)with the same session preparation asaccount/login.
Other materials on exchanging data with external systems, including the custom JSON endpoint, are collected in the "API and integrations" section.