User
The user module provides various account functionality that you can use to authenticate a user in your game. This means that the CrazyGames players who are logged in on the platform will be able to play games that require a user account without having to register in the game. They will also be logged in automatically in the game on other devices where they use the same CrazyGames account.
The account integration page already familiarized you with the possible SDK scenarios. For the scenarios where authentication is available, please consult the appropriate link below.
The user module can be accessed like this:
Info
For a demo, please consult the CrazySDK/Demo/UserModule
scene. You can run it directly in the Unity editor.
Check availability
Basic Implementation Full Implementation
The user account functionality is available only when your game is running on CrazyGames domains. It will not work on our partner domains that embed it, or on your whitelisted domains. Before using any user account features, you should always ensure that the user account system is available.
Get current user
Basic Implementation Full Implementation
You can retrieve the user currently logged in CrazyGames with the following method:
CrazySDK.User.GetUser(user =>
{
if (user != null)
{
Debug.Log("Get user result: " + user);
}
else
{
Debug.Log("User is not logged in");
}
});
If the user is not logged in CrazyGames, the returned user will be null
.
The returned user object contains the following fields:
System info
Basic Implementation Full Implementation
You can retrieve the system info like this:
var systemInfo = CrazySDK.User.SystemInfo;
Debug.Log(systemInfo.countryCode);
// For browser and os, format is the same as https://github.com/faisalman/ua-parser-js
Debug.Log(systemInfo.browser.name);
Debug.Log(systemInfo.browser.version);
Debug.Log(systemInfo.os.name);
Debug.Log(systemInfo.os.version);
Debug.Log(systemInfo.device.type); // possible values: "desktop", "tablet", "mobile"
Auth prompt
Basic Implementation Full Implementation
By calling this method, the log in or register popup will be displayed on CrazyGames. The user can log in their existing account, or create a new account. The method returns the user object.
CrazySDK.User.ShowAuthPrompt((error, user) =>
{
if (error != null)
{
Debug.LogError("Show auth prompt error: " + error);
return;
}
Debug.Log("Auth prompt user: " + user);
});
The following error codes can be returned:
showAuthPromptInProgress
- an auth prompt is already opened on the websiteuserAlreadySignedIn
- the user is already logged inuserCancelled
- the user closed the auth prompt without logging in or registering
Get user token
Basic Implementation Full Implementation
The user token contains the userId
of the player that is currently logged in CrazyGames, as well as other useful information (username
, profilePictureUrl
, etc). You should send it to your server when required, and verify/decode it there to extract the userId
. This is useful for linking the user accounts for example, where you can have a column "crazyGamesId" in your user table that will be populated with the user id from the token.
You can retrieve the user token with the following method:
CrazySDK.User.GetUserToken((error, token) =>
{
if (error != null)
{
Debug.LogError("Get user token error: " + error);
return;
}
Debug.Log("User token: " + token);
});
The token has a lifetime of 1 hour. The method will handle the token refresh. We recommend that you don't store the token, and always call this method when the token is required.
The following error codes can be returned:
userNotAuthenticated
- the user is not logged in CrazyGamesunexpectedError
The returned token can be decoded for testing purposes on jwt.io.
The token payload will contain the following data:
{
"userId": "UOuZBKgjwpY9k4TSBB2NPugbsHD3",
"gameId": "20267",
"username": "RustyCake.ZU9H",
"profilePictureUrl": "https://images.crazygames.com/userportal/avatars/16.png",
"iat": 1670328680,
"exp": 1670332280
}
When you need to authenticate the requests with your server, you should send the token together with the requests.
The token can be verified with the public key hosted at this URL https://sdk.crazygames.com/publicKey.json. We recommend that you fetch the key every time you verify the token, since it may change. Alternatively, you can implement a caching mechanism, and re-fetch it when the token fails to decode due to a possible key change.
Here is a TypeScript example that will help you decode and verify the token:
import * as jwt from "jsonwebtoken";
import axios from "axios";
export interface CrazyTokenPayload {
userId: string;
gameId: string;
username: string;
profilePictureUrl: string;
}
export const DecodeCGToken = async (
token: string
): Promise<CrazyTokenPayload> => {
let key = "";
try {
const resp = await axios.get(
"https://sdk.crazygames.com/publicKey.json"
);
key = resp.data["publicKey"];
} catch (e) {
console.error("Failed to fetch CrazyGames public key", e);
}
if (!key) {
throw new Error("Key is empty when decoding CrazyGames token");
}
const payload = jwt.verify(token, key, { algorithms: ["RS256"] });
return payload as CrazyTokenPayload;
};
Auth listener
Guideline
You can register user auth listeners that are triggered when the player logs in CrazyGames. A log out doesn't trigger the auth listeners, since the entire page is refreshed when the player logs out.
Action<PortalUser> lst = (user) => { Debug.Log("Auth listener, user: " + user); };
CrazySDK.User.AddAuthListener(lst); // add
CrazySDK.User.RemoveAuthListener(lst); // remove (for example on scene change)
After detecting a login using the Auth Listener, if you use the CrazyGames account as an identifier you should fetch the user's progress from your back-end.
If you rely on the CrazyGames automatic progress save, our system automatically reloads the game in case of a login.
Saving user data
Basic Implementation Full Implementation
By default, our APS system automatically backs up player data (PlayerPrefs, and the provided file name if present). The automatic backup isn't always the best solution, since we cannot reliably detect if any IndexedDB changes occur. That's why we also provide the SyncUnityGameData
that you can manually call to ensure the player data is saved at the opportune moments.
For more details, please check the APS page.
Account link prompt
Guideline
If you'd like to keep other sign in providers (Google or Facebook for example), you'll need to handle account linking between the CrazyGames account and the other providers. Check User linking page to find out more about user account linking.
For requesting the user's permission to link their CrazyGames account to the in-game account, please use the provided account link modal and avoid implementing it yourself. This provides the players with a standard modal, and also allows them to select the "Always link accounts" option (coming soon).
You can display the modal by calling the following method:
CrazySDK.User.ShowAccountLinkPrompt((error, answer) =>
{
if (error != null)
{
Debug.LogError("Show account link prompt error: " + error);
return;
}
Debug.Log("Account link answer: " + answer);
});
The answer will be true
if the player agrees to link the accounts, and false
otherwise.
The following error codes can be returned:
showAccountLinkPromptInProgress
- the link account modal is already displayeduserNotAuthenticated
- the user is not logged in CrazyGames
Testing
Basic Implementation Full Implementation
Local
When you are running the game in the editor, the method calls will return some hard-coded values.
You can customize the returned values in the CrazySDK/Resources/CrazyGamesSettings
object:
In the above image, you can also see the default values returned by the methods.