using CSCMobiPlugin.FacebookInstant;
void Start()
{
// FbInstant.Instance đã được khởi tạo tự động
// Có thể sử dụng ngay:
// Load player data
StartCoroutine(FbInstant.Player.GetDataGame());
}
using CSCMobiPlugin.FacebookInstant;
using System.Collections;
// Lưu dữ liệu với key-value
FbInstant.Player.SetData("my_key", "my_value");
// Lưu dữ liệu game (sử dụng key mặc định "data_game")
string jsonData = JsonUtility.ToJson(gameData);
FbInstant.Player.SetDataGame(jsonData);
// Lưu ngay lập tức (bypass debounce)
FbInstant.Player.SetDataImmediate("critical_key", "critical_value");
// Flush tất cả pending updates
FbInstant.Player.FlushPendingUpdates();
// Tải dữ liệu (Coroutine)
IEnumerator LoadData()
{
yield return FbInstant.Player.IEGetData("my_key");
// Dữ liệu đã được lưu trong FbInstant.Player.DictData["my_key"]
// Hoặc sử dụng event
FbInstant.Player.OnDataReceived += (key, value) => {
Debug.Log($"Data received - Key: {key}, Value: {value}");
};
}
// Tải dữ liệu game
IEnumerator LoadGameData()
{
yield return FbInstant.Player.GetDataGame();
string data = FbInstant.Player.DataGame;
// Parse JSON...
}
// Kiểm tra data đã load xong chưa
bool isReady = FbInstant.Player.IsDataGameDone();
// Xóa dữ liệu
FbInstant.Player.ClearData();
// Subscribe to bot với position để tracking
FbInstant.Player.Subscribe("menu");
// Hoặc không truyền position (mặc định là empty string)
FbInstant.Player.Subscribe();
// Lắng nghe khi subscribe thành công
FbInstant.Player.OnSubscribed += (position) => {
Debug.Log($"User has subscribed at position: {position}!");
};
// Hoặc sử dụng backward compatibility
FbInstant.Instance.Subscribe("settings");
// Share với title và image base64
string imageBase64 = "iVBORw0KG..."; // Base64 string (có hoặc không có prefix)
FbInstant.FbShare.Share("My Game Title", imageBase64, "menu");
// Share với callbacks
FbInstant.FbShare.Share("My Game Title", imageBase64, "menu",
onCompleted: () => {
Debug.Log("Share thành công!");
},
onFailed: (error) => {
Debug.LogError($"Share thất bại: {error}");
}
);
// Lắng nghe events
FbInstant.FbShare.OnShareClick += (position) => {
Debug.Log($"Share clicked at position: {position}");
};
FbInstant.FbShare.OnShareCompleted += (position) => {
Debug.Log($"Share completed at position: {position}!");
};
FbInstant.FbShare.OnShareFailed += (error) => {
Debug.LogError($"Share failed: {error}");
};
// Invite bạn bè với title và image
FbInstant.FbInvite.Invite("Play with me!", imageBase64);
// Invite player cụ thể
FbInstant.FbInvite.InviteWithID("player_id_123");
// Invite với callbacks
FbInstant.FbInvite.Invite("Play with me!", imageBase64,
onCompleted: () => {
Debug.Log("Invite thành công!");
},
onFailed: (error) => {
Debug.LogError($"Invite thất bại: {error}");
}
);
// Invite with ID và callbacks
FbInstant.FbInvite.InviteWithID("player_id_123",
onCompleted: () => {
Debug.Log("Invite thành công!");
},
onFailed: (error) => {
Debug.LogError($"Invite thất bại: {error}");
}
);
// Lắng nghe events
FbInstant.FbInvite.OnInviteCompleted += () => {
Debug.Log("Invite completed!");
};
FbInstant.FbInvite.OnInviteFailed += (error) => {
Debug.LogError($"Invite failed: {error}");
};
// Preload interstitial ad (cần Ad Unit ID)
string interstitialAdUnitId = "YOUR_INTERSTITIAL_AD_UNIT_ID";
FbInstant.Interstitial.LoadInterstitial(interstitialAdUnitId);
// Kiểm tra sẵn sàng
if (FbInstant.Interstitial.IsInterstitialReady)
{
// Hiển thị ad
FbInstant.Interstitial.ShowInterstitial();
}
// Show với callback
FbInstant.Interstitial.ShowInterstitial(() => {
Debug.Log("Interstitial đã đóng!");
});
// Lắng nghe events
FbInstant.Interstitial.OnInterstitialLoaded += () => {
Debug.Log("Interstitial đã sẵn sàng!");
};
FbInstant.Interstitial.OnInterstitialLoadFailed += () => {
Debug.Log("Interstitial load failed!");
};
FbInstant.Interstitial.OnInterstitialClosed += () => {
Debug.Log("Interstitial đã đóng!");
};
// Preload rewarded video ad (cần Ad Unit ID)
string rewardedAdUnitId = "YOUR_REWARDED_AD_UNIT_ID";
FbInstant.RewardedVideo.LoadRewardedVideo(rewardedAdUnitId);
// Kiểm tra sẵn sàng
if (FbInstant.RewardedVideo.IsRewardedVideoReady)
{
// Hiển thị ad
FbInstant.RewardedVideo.ShowRewardedVideo();
}
// Show với callbacks
FbInstant.RewardedVideo.ShowRewardedVideo(
onCompleted: () => {
Debug.Log("Người chơi đã xem hết video! Cho thưởng!");
// Give reward here
},
onAdClosed: () => {
Debug.Log("Video đã đóng hoặc bị lỗi!");
}
);
// Lắng nghe events
FbInstant.RewardedVideo.OnRewardedVideoLoaded += () => {
Debug.Log("Rewarded video đã sẵn sàng!");
};
FbInstant.RewardedVideo.OnRewardedVideoLoadFailed += () => {
Debug.Log("Rewarded video load failed!");
};
FbInstant.RewardedVideo.OnRewardedVideoCompleted += () => {
Debug.Log("Người chơi đã xem hết video! Cho thưởng!");
};
FbInstant.RewardedVideo.OnRewardedVideoFailed += () => {
Debug.Log("Video không sẵn sàng hoặc bị lỗi!");
};
public class PurchaseInfo
{
public string purchaseToken; // Token để verify purchase
public string productID; // Product ID đã mua
public string paymentID; // Payment ID từ Facebook
public string signedRequest; // Signed request để verify
public string developerPayload; // Developer payload (có thể null)
public bool isConsumed; // Đã consume purchase chưa
public string paymentActionType; // Loại payment (ví dụ: "charge")
public string purchasePlatform; // Platform (ví dụ: "FB")
public PurchasePrice purchasePrice; // Thông tin giá
public long purchaseTime; // Timestamp khi mua
}
public class PurchasePrice
{
public string amount; // Số tiền (dạng string)
public string currency; // Mã tiền tệ (ví dụ: "VND", "USD")
}
public class ProductCatalog
{
public string description; // Mô tả product
public string imageURI; // URI hình ảnh (có thể null)
public string price; // Giá hiển thị (ví dụ: "158.785 ₫")
public long priceAmount; // Số tiền (dạng số, ví dụ: 158785)
public string priceCurrencyCode; // Mã tiền tệ (ví dụ: "VND", "USD")
public string productID; // Product ID
public string title; // Tiêu đề product
}
// Create shortcut (pin game) to home screen với position để tracking
FbInstant.Instance.CreateShortcutAsync("menu");
// Hoặc không truyền position (mặc định là empty string)
FbInstant.Instance.CreateShortcutAsync();
// Lắng nghe khi pin thành công
FbInstant.OnCreateShortcutCompleted += (position) => {
Debug.Log($"Game đã được pin tại vị trí: {position}!");
};
// Lắng nghe khi pin thất bại hoặc bị hủy
FbInstant.OnCreateShortcutFailed += (error) => {
Debug.LogError($"Pin game thất bại: {error}");
};
// Tạo payload cho custom update
var payload = new CustomUpdateWithOverlayPayload
{
action = "CUSTOM",
template = "VILLAGE_INVASION",
cta = new LocalizableContent
{
@default = "Join The Fight",
localizations = new Dictionary<string, string>
{
{ "en_US", "Join The Fight" },
{ "vi_VN", "Tham gia chiến đấu" }
}
},
text = new LocalizableContent
{
@default = "X just invaded Y's village!",
localizations = new Dictionary<string, string>
{
{ "en_US", "X just invaded Y's village!" },
{ "vi_VN", "X vừa xâm chiếm làng của Y!" }
}
},
image = "data:image/png;base64,iVBORw0KG...", // Base64 image
data = new Dictionary<string, object>
{
{ "myReplayData", "..." }
},
strategy = "IMMEDIATE",
notification = "NO_PUSH"
};
// Gửi update
FbInstant.Instance.UpdateAsync(payload);
// Lắng nghe events
FbInstant.OnUpdateCompleted += () => {
Debug.Log("Update đã được gửi thành công!");
// Có thể đóng game sau khi update
// FBInstant.quit(); // (cần implement trong JS)
};
FbInstant.OnUpdateFailed += (error) => {
Debug.LogError($"Update thất bại: {error}");
};
// Lấy ID của context hiện tại
string contextId = FbInstant.Context.GetID();
if (contextId != null)
{
Debug.Log($"Current context ID: {contextId}");
}
else
{
Debug.Log("Game is in solo context");
}
// Chuyển sang context khác
FbInstant.Context.SwitchAsync("context_id_123");
// Chuyển sang solo context (với xác nhận)
FbInstant.Context.SwitchAsync("SOLO");
// Chuyển sang solo context (im lặng, không có dialog)
FbInstant.Context.SwitchAsync("SOLO", switchSilentlyIfSolo: true);
// Switch với callbacks
FbInstant.Context.SwitchAsync("context_id_123",
onCompleted: () => {
Debug.Log("Đã chuyển context thành công!");
},
onFailed: (error) => {
Debug.LogError($"Chuyển context thất bại: {error}");
}
);
// Tạo context mới với một player
FbInstant.Context.CreateAsync("player_id_123");
// Tạo context mới với nhiều players
FbInstant.Context.CreateAsync(new List<string> { "player_id_1", "player_id_2" });
// Tạo context với friend picker (không có tham số)
FbInstant.Context.CreateAsync();
// Create với callbacks
FbInstant.Context.CreateAsync("player_id_123",
onCompleted: () => {
Debug.Log("Đã tạo context thành công!");
},
onFailed: (error) => {
Debug.LogError($"Tạo context thất bại: {error}");
}
);
// Lấy danh sách players trong context hiện tại
FbInstant.Context.GetPlayersAsync();
// Get players với callbacks
FbInstant.Context.GetPlayersAsync(
onReceived: (players) => {
Debug.Log($"Có {players.Count} players trong context");
foreach (var player in players)
{
Debug.Log($"Player ID: {player.id}, Name: {player.name}");
}
},
onFailed: (error) => {
Debug.LogError($"Lấy players thất bại: {error}");
}
);
// Mở dialog chọn context
FbInstant.Context.ChooseAsync();
// Choose với options
var options = new ChooseContextOptions
{
filters = new List<string> { "NEW_CONTEXT_ONLY" },
minSize = 3,
maxSize = 10
};
FbInstant.Context.ChooseAsync(options);
// Choose với callbacks
FbInstant.Context.ChooseAsync(
onCompleted: () => {
Debug.Log("Đã chọn context thành công!");
},
onFailed: (error) => {
Debug.LogError($"Chọn context thất bại: {error}");
}
);
// Lắng nghe events
FbInstant.Context.OnSwitchCompleted += () => {
Debug.Log("Context switch completed!");
};
FbInstant.Context.OnSwitchFailed += (error) => {
Debug.LogError($"Context switch failed: {error}");
};
FbInstant.Context.OnPlayersReceived += (players) => {
Debug.Log($"Received {players.Count} players");
};
FbInstant.Context.OnGetPlayersFailed += (error) => {
Debug.LogError($"Get players failed: {error}");
};
// Follow Facebook official page với position để tracking
FbInstant.Community.FollowOfficialPageAsync("menu");
// Join Facebook official group với position để tracking
FbInstant.Community.JoinOfficialGroupAsync("settings");
// Hoặc không truyền position (mặc định là empty string)
FbInstant.Community.FollowOfficialPageAsync();
FbInstant.Community.JoinOfficialGroupAsync();
// Lắng nghe events
FbInstant.Community.OnFollowPageSuccess += (position) => {
Debug.Log($"Đã follow page thành công tại vị trí: {position}");
};
FbInstant.Community.OnFollowPageFailed += (error) => {
Debug.LogError($"Follow page thất bại: {error}");
};
FbInstant.Community.OnJoinGroupSuccess += (position) => {
Debug.Log($"Đã join group thành công tại vị trí: {position}");
};
FbInstant.Community.OnJoinGroupFailed += (error) => {
Debug.LogError($"Join group thất bại: {error}");
};
// Đăng điểm session với callbacks (tùy chọn)
FbInstant.Instance.PostSessionScoreAsync(1000,
onCompleted: (score) => {
Debug.Log($"Session score posted: {score}");
},
onFailed: (error) => {
Debug.LogError($"Post session score failed: {error}");
}
);
// Hoặc không có callbacks
FbInstant.Instance.PostSessionScoreAsync(1000, null, null);
// Thiết lập coroutine runner (cần thiết để chạy coroutines)
FbInstant.Notification.SetCoroutineRunner(FbInstant.Instance);
// Lấy Access Token từ Facebook API
FbInstant.Notification.GetAccessToken(
"your_app_id",
"your_app_secret",
(token) => {
Debug.Log($"Access Token obtained: {token}");
// Lưu token để sử dụng cho các lần gửi notification sau
},
(error) => {
Debug.LogError($"Failed to get access token: {error}");
}
);
// Gửi notification với đầy đủ tham số
FbInstant.Notification.SendNotification(
"your_app_id", // App ID
"access_token", // Access Token từ GetAccessToken
"player_id_123", // Player ID của người nhận
"Title", // Tiêu đề notification
"Message", // Nội dung notification
300, // Schedule (giây) - PHẢI >= 300 (5 phút)
"label1", // Label (optional)
"https://example.com/image.jpg", // Media URL (optional)
(result) => {
Debug.Log($"Notification sent! Success: {result.success}, ID: {result.notification_id ?? "N/A"}");
},
(error) => {
Debug.LogError($"Failed to send notification: {error}");
}
);
// Gửi notification đơn giản (không có callbacks)
FbInstant.Notification.SendNotification(
"your_app_id",
"access_token",
"player_id_123",
"Title",
"Message",
600 // 10 phút
);
// Lắng nghe events
FbInstant.Notification.OnSendNotificationCompleted += (result) => {
Debug.Log($"Notification sent! Success: {result.success}, ID: {result.notification_id ?? "N/A"}");
};
FbInstant.Notification.OnSendNotificationFailed += (error) => {
Debug.LogError($"Failed to send notification: {error}");
};
// Hủy tất cả notifications của player
FbInstant.Notification.CancelAllNotification(
"your_app_id",
"access_token",
"player_id_123",
null, // Label = null để hủy tất cả
(result) => {
Debug.Log($"Notifications canceled! Success: {result.success}");
},
(error) => {
Debug.LogError($"Failed to cancel notifications: {error}");
}
);
// Hủy notifications theo label
FbInstant.Notification.CancelAllNotification(
"your_app_id",
"access_token",
"player_id_123",
"label1", // Chỉ hủy notifications có label này
(result) => {
Debug.Log($"Notifications canceled! Success: {result.success}");
},
(error) => {
Debug.LogError($"Failed to cancel notifications: {error}");
}
);
// Tạo GameObject mới
GameObject catalogObj = new GameObject("FBProductCatalog");
FBProductCatalogController controller = catalogObj.AddComponent<FBProductCatalogController>();
// Kiểm tra catalog đã load chưa
if (FBProductCatalogController.Instance.IsCatalogLoaded())
{
Debug.Log("Catalog đã sẵn sàng!");
}
// Lấy ProductCatalog theo productID
string productID = "com.yourgame.ruby100";
ProductCatalog product = FBProductCatalogController.Instance.GetProductCatalog(productID);
if (product != null)
{
Debug.Log($"Product: {product.title}");
Debug.Log($"Price: {product.price}");
Debug.Log($"Description: {product.description}");
}
// Lấy giá hiển thị (formatted string)
string price = FBProductCatalogController.Instance.GetFormattedPrice(productID);
if (price != null)
{
Debug.Log($"Price: {price}");
}
// Lấy priceAmount (long)
long priceAmount = FBProductCatalogController.Instance.GetPriceAmount(productID);
Debug.Log($"Price Amount: {priceAmount}");
// Lấy toàn bộ catalog
List<ProductCatalog> catalog = FBProductCatalogController.Instance.GetCatalog();
foreach (var product in catalog)
{
Debug.Log($"Product: {product.productID} - {product.title} - {product.price}");
}
// Reload catalog từ Facebook
FBProductCatalogController.Instance.LoadCatalogFromFbInstant();
// Trong Inspector:
// - productID: "com.yourgame.ruby100"
// - priceText: Assign TextMeshProUGUI component từ Button hoặc child GameObject
// Lắng nghe khi game đã sẵn sàng (sau khi startGameAsync hoàn thành)
FbInstant.OnStartGameReady += (playerId) => {
Debug.Log($"Game is ready! PlayerID: {playerId}");
// Game đã được khởi tạo, có thể bắt đầu gameplay
// PlayerID đã được set tự động
};
// Hoặc trong class
void Start()
{
FbInstant.OnStartGameReady += OnGameReady;
}
void OnGameReady(string playerId)
{
Debug.Log($"Game ready - PlayerID: {playerId}");
// Initialize game logic here
}
void OnDestroy()
{
FbInstant.OnStartGameReady -= OnGameReady;
}
// Lấy entry point data (Dictionary<string, object>)
Dictionary<string, object> entryPointData = FbInstant.Instance.GetEntryPointData();
if (entryPointData != null)
{
foreach (var kvp in entryPointData)
{
Debug.Log($"Entry Point Data - Key: {kvp.Key}, Value: {kvp.Value}");
}
}
else
{
Debug.Log("No entry point data available");
}
// Lấy entry point name (async)
FbInstant.Instance.GetEntryPointAsync();
// Get entry point với callbacks
FbInstant.Instance.GetEntryPointAsync(
onReceived: (entryPoint) => {
Debug.Log($"Entry point: {entryPoint}");
// Ví dụ: "admin_message", "timeline", "group", etc.
},
onFailed: (error) => {
Debug.LogError($"Get entry point failed: {error}");
}
);
// Lắng nghe events
FbInstant.OnEntryPointReceived += (entryPoint) => {
Debug.Log($"Entry point received: {entryPoint}");
};
FbInstant.OnGetEntryPointFailed += (error) => {
Debug.LogError($"Get entry point failed: {error}");
};
// Log event đơn giản
string error = FbInstant.LogEvent.LogEvent("my_custom_event");
if (error == null)
{
Debug.Log("Event logged successfully!");
}
else
{
Debug.LogError($"Event log failed: {error}");
}
// Log event với valueToSum
FbInstant.LogEvent.LogEvent("purchase_completed", 42.5);
// Log event với parameters
var parameters = new Dictionary<string, object>
{
{ "item_name", "sword" },
{ "item_category", "weapon" },
{ "level", 5 }
};
FbInstant.LogEvent.LogEvent("item_purchased", parameters);
// Log event với cả valueToSum và parameters
FbInstant.LogEvent.LogEvent("purchase_completed", 99.99, parameters);
// Lưu ý: Event name phải từ 2-40 ký tự, chỉ chứa '_', '-', ' ', và alphanumeric
// Parameters tối đa 25 cặp key-value
// Parameter keys phải từ 2-40 ký tự
// Parameter values phải < 100 ký tự
// Lắng nghe khi game bị pause (user chuyển sang window/tab khác hoặc chuyển app)
FbInstant.OnPause += () => {
Debug.Log("Game bị pause!");
// Lưu game state, pause gameplay, etc.
pauseGameplay();
};
// Lấy GSM Access Token (sau khi GSM init thành công)
string gsmAccessToken = FbInstant.Instance.GSMAccessToken;
// Lắng nghe khi GSM Access Token được nhận
// Token được set tự động từ JavaScript sau khi loginGSM thành công
if (!string.IsNullOrEmpty(FbInstant.Instance.GSMAccessToken))
{
Debug.Log("GSM Access Token available!");
// Sử dụng token để gọi các API GSM khác
}
// Lấy thông tin player
string playerID = FbInstant.Instance.PlayerID;
string playerName = FbInstant.Instance.PlayerName;
string avatarURL = FbInstant.Instance.PlayerAvatarURL;
// Lấy GSM Access Token (nếu có)
string gsmAccessToken = FbInstant.Instance.GSMAccessToken;
// Kiểm tra OS
bool isIOS = FbInstant.Instance.IsIOSDevice();
bool isAndroid = FbInstant.Instance.IsAndroidDevice();
string devicePlatform = FbInstant.Instance.GetCurrentDevice(); // "Android", "iOS", hoặc "Other"