Skip to main content

Social Login

The loginWithSocial method authenticates players using their existing social media accounts (Google, Facebook). This provides a seamless login experience without requiring email or OTP verification.

How Social Login Works

  1. Player clicks "Login with Google" or "Login with Facebook"
  2. Your game uses the social platform's SDK to authenticate
  3. You receive player information from the social platform
  4. Pass this information to loginWithSocial
  5. Player is logged in automatically
info

Social login requires integration with the social platform's SDK (Google Sign-In, Facebook Login) in addition to the Moitribe SDK. This guide assumes you have already set up the social platform SDKs.

Basic Usage

After obtaining player information from the social platform, pass it to loginWithSocial:

Google Login

MoitribeSDK('my-game-id', 'loginWithSocial', {
social: {
socialplat: 'google',
id: 'google-user-id-123',
name: 'John Doe',
email: 'john@example.com',
picture: 'https://example.com/profile.jpg'
},
callback: (result) => {
if (result.success) {
console.log('Google login successful');
startGame();
} else {
console.error('Login failed:', result.msg);
}
}
});

Facebook Login

MoitribeSDK('my-game-id', 'loginWithSocial', {
social: {
socialplat: 'facebook',
id: 'facebook-user-id-456',
name: 'Jane Smith',
email: 'jane@example.com',
picture: 'https://graph.facebook.com/profile-pic.jpg'
},
callback: (result) => {
if (result.success) {
console.log('Facebook login successful');
startGame();
} else {
console.error('Login failed:', result.msg);
}
}
});

Parameters

ParameterTypeRequiredDescription
socialobjectYesSocial platform information
social.socialplatstringYesPlatform: 'google' or 'facebook'
social.idstringYesUnique user ID from platform
social.namestringNoPlayer's display name
social.emailstringNoPlayer's email address
social.picturestringNoProfile picture URL
callbackfunctionYesCalled with login result
warning

The socialplat and id fields are required. The SDK will return an error if either is missing.

Response Format

The callback receives:

{
success: boolean; // true if login succeeded
msg?: string; // Error message (if failed)
statuscode?: number; // Error code (if failed)
}

Success Response

{
success: true
}

After successful login, the SDK's loginCallback is automatically called with player data.

Error Response

{
success: false,
msg: 'Social platform or id cannot be empty',
statuscode: 110
}

Google Sign-In Integration

Complete example with Google Sign-In SDK:

HTML Setup

<!DOCTYPE html>
<html>
<head>
<script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
<div id="g_id_onload"
data-client_id="YOUR_GOOGLE_CLIENT_ID"
data-callback="handleGoogleSignIn">
</div>
<div class="g_id_signin" data-type="standard"></div>

<script src="node_modules/@veniso/moitribe-js/dist/moitribe-sdk.min.js"></script>
<script src="game.js"></script>
</body>
</html>

JavaScript Implementation

const GAME_ID = 'my-game-id';

// Google Sign-In callback
function handleGoogleSignIn(response) {
// Decode JWT token from Google
const token = response.credential;
const payload = parseJwt(token);

// Extract user information
const googleUser = {
id: payload.sub,
name: payload.name,
email: payload.email,
picture: payload.picture
};

// Login with Moitribe
loginWithGoogle(googleUser);
}

function loginWithGoogle(user) {
MoitribeSDK(GAME_ID, 'loginWithSocial', {
social: {
socialplat: 'google',
id: user.id,
name: user.name,
email: user.email,
picture: user.picture
},
callback: (result) => {
if (result.success) {
console.log('Google login successful');
// SDK loginCallback will be called with player data
} else {
console.error('Login failed:', result.msg);
showError('Failed to log in with Google');
}
}
});
}

// Helper to parse JWT token
function parseJwt(token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map((c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}

Facebook Login Integration

Complete example with Facebook SDK:

HTML Setup

<!DOCTYPE html>
<html>
<head>
<script async defer crossorigin="anonymous"
src="https://connect.facebook.net/en_US/sdk.js"></script>
</head>
<body>
<button onclick="loginWithFacebook()">Login with Facebook</button>

<script src="node_modules/@veniso/moitribe-js/dist/moitribe-sdk.min.js"></script>
<script src="game.js"></script>
</body>
</html>

JavaScript Implementation

const GAME_ID = 'my-game-id';

// Initialize Facebook SDK
window.fbAsyncInit = function() {
FB.init({
appId: 'YOUR_FACEBOOK_APP_ID',
cookie: true,
xfbml: true,
version: 'v18.0'
});
};

function loginWithFacebook() {
FB.login((response) => {
if (response.authResponse) {
// Get user information
FB.api('/me', {fields: 'id,name,email,picture'}, (user) => {
loginWithMoitribe({
id: user.id,
name: user.name,
email: user.email,
picture: user.picture.data.url
});
});
} else {
console.log('User cancelled login');
}
}, {scope: 'public_profile,email'});
}

function loginWithMoitribe(user) {
MoitribeSDK(GAME_ID, 'loginWithSocial', {
social: {
socialplat: 'facebook',
id: user.id,
name: user.name,
email: user.email,
picture: user.picture
},
callback: (result) => {
if (result.success) {
console.log('Facebook login successful');
// SDK loginCallback will be called
} else {
console.error('Login failed:', result.msg);
showError('Failed to log in with Facebook');
}
}
});
}

TypeScript Example

import MoitribeSDK from '@veniso/moitribe-js';

interface SocialLoginParams {
social: {
socialplat: 'google' | 'facebook';
id: string;
name?: string;
email?: string;
picture?: string;
};
callback: (result: SocialLoginResult) => void;
}

interface SocialLoginResult {
success: boolean;
msg?: string;
statuscode?: number;
}

interface SocialUser {
id: string;
name?: string;
email?: string;
picture?: string;
}

const GAME_ID = 'my-game-id';

function loginWithSocialPlatform(
platform: 'google' | 'facebook',
user: SocialUser
): void {
const params: SocialLoginParams = {
social: {
socialplat: platform,
id: user.id,
name: user.name,
email: user.email,
picture: user.picture
},
callback: (result: SocialLoginResult) => {
if (result.success) {
console.log(`${platform} login successful`);
} else {
handleLoginError(result, platform);
}
}
};

MoitribeSDK(GAME_ID, 'loginWithSocial', params);
}

function handleLoginError(
result: SocialLoginResult,
platform: string
): void {
console.error(`${platform} login failed:`, result.msg);
showError(`Failed to log in with ${platform}`);
}

Auto-Create Account

Social login automatically creates a new account if the player doesn't exist:

MoitribeSDK('my-game-id', 'loginWithSocial', {
social: {
socialplat: 'google',
id: 'new-user-123',
name: 'New Player',
email: 'newplayer@example.com',
picture: 'https://example.com/profile.jpg'
},
callback: (result) => {
if (result.success) {
// Could be new account or existing account
// Check via loginCallback
console.log('Login successful');
}
}
});

The SDK automatically:

  • Creates new account if id doesn't exist
  • Logs in to existing account if id exists
  • Updates profile information (name, email, picture) if provided

Receiving Player Data

After successful social login, the loginCallback is called:

MoitribeSDK('my-game-id', 'init', {
loginCallback: (result) => {
if (result.success) {
const player = result.playerdata;

console.log('Logged in as:', player.name);
console.log('Email:', player.emailid);
console.log('Profile picture:', player.profilehiresimg);

// Start game
startGame(player);
}
}
});

UI Examples

Multiple Login Options

<div id="login-screen">
<h1>Welcome to My Game</h1>

<button class="google-btn" onclick="loginWithGoogle()">
<img src="google-icon.png"> Continue with Google
</button>

<button class="facebook-btn" onclick="loginWithFacebook()">
<img src="facebook-icon.png"> Continue with Facebook
</button>

<div class="divider">OR</div>

<button class="email-btn" onclick="showEmailLogin()">
Continue with Email
</button>

<button class="guest-btn" onclick="playAsGuest()">
Play as Guest
</button>
</div>

Loading State

function loginWithGoogle() {
// Show loading
document.getElementById('login-buttons').disabled = true;
showLoading('Logging in with Google...');

// Trigger Google Sign-In
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed()) {
hideLoading();
showError('Google Sign-In is not available');
}
});
}

Error Handling

Handle common error scenarios:

MoitribeSDK('my-game-id', 'loginWithSocial', {
social: {
socialplat: 'google',
id: googleId,
name: name,
email: email
},
callback: (result) => {
if (result.success) {
console.log('Login successful');
} else {
// Handle specific errors
if (result.statuscode === 110) {
showError('Invalid social login information');
} else if (result.statuscode === 111) {
showError('Social platform not supported');
} else {
showError(result.msg || 'Login failed. Please try again.');
}
}
}
});

Account Linking

Players can link multiple social accounts to the same profile:

// First login with Google
loginWithGoogle(googleUser);

// Later, link Facebook account
// (Both will share the same player profile if email matches)
loginWithFacebook(facebookUser);
info

If two social accounts have the same email address, they will be linked to the same player account automatically.

Best Practices

1. Handle Sign-In Errors

Gracefully handle when social sign-in fails:

function handleGoogleSignInError(error) {
console.error('Google Sign-In error:', error);
showDialog({
title: 'Login Failed',
message: 'Unable to sign in with Google. Please try another method.',
buttons: [
{ text: 'Try Email', action: showEmailLogin },
{ text: 'Try Facebook', action: loginWithFacebook },
{ text: 'Play as Guest', action: playAsGuest }
]
});
}

2. Privacy Information

Explain what data you're accessing:

function showSocialLoginConsent() {
showDialog({
title: 'Login with Google',
message: 'We will access your basic profile information (name, email, profile picture) to create your account.',
buttons: [
{ text: 'Continue', action: proceedWithGoogleLogin },
{ text: 'Cancel', action: closeDialog }
]
});
}

3. One-Click Login

Use social platform tokens for automatic login:

// Check if user has existing social session
FB.getLoginStatus((response) => {
if (response.status === 'connected') {
// User is already logged into Facebook
// Automatically log them into your game
autoLoginWithFacebook(response.authResponse.userID);
} else {
// Show login button
showLoginScreen();
}
});

4. Fallback Options

Always provide alternative login methods:

<div id="login-options">
<button onclick="loginWithGoogle()">Login with Google</button>
<button onclick="loginWithFacebook()">Login with Facebook</button>
<a href="#" onclick="showEmailLogin()">Use Email Instead</a>
</div>
tip

Social login provides the smoothest player experience but always offer alternative authentication methods (email/OTP, guest) for players who prefer not to use social accounts.

Platform-Specific Considerations

Google Sign-In

  • Requires Google Developer Console setup
  • Need to configure OAuth consent screen
  • Works on web, Android, iOS
  • Supports one-tap sign-in

Facebook Login

  • Requires Facebook Developer App
  • Need to configure App Domain
  • Works on web, Android, iOS
  • Can request additional permissions (friends list, etc.)

Next Steps

After implementing social login:

Related authentication topics: