Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Assets/PlayroomKit/PlayroomKit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,12 @@ public void OpenDiscordInviteDialog(Action callback = null)
CheckPlayRoomInitialized();
_playroomService.OpenDiscordInviteDialog(callback);
}

public void StartDiscordPurchase(string skuId, Action<List<Entitlement>> responseCallback = null)
{
CheckPlayRoomInitialized();
_playroomService.StartDiscordPurchase(skuId, responseCallback);
}
#endregion
}
}
8 changes: 8 additions & 0 deletions Assets/PlayroomKit/modules/Discord.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 74 additions & 0 deletions Assets/PlayroomKit/modules/Discord/Entitlement.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using SimpleJSON;

public enum EntitlementType
{
Unhandled = -1,
Purchase = 1,
PremiumSubscription = 2,
DeveloperGift = 3,
TestModePurchase = 4,
FreePurchase = 5,
UserGift = 6,
PremiumPurchase = 7
}

[Serializable]
public class Entitlement
{
public string Id;
public string SkuId;
public string ApplicationId;
public string UserId;
public int GiftCodeFlags;
public EntitlementType Type;
public string? GifterUserId;
public List<string>? Branches;
public DateTime? StartsAt;
public DateTime? EndsAt;
public string? ParentId;
public bool? Consumed;
public bool? Deleted;
public string? GiftCodeBatchId;

/// <summary>
/// Parse a JSONNode (from SimpleJSON) into an Entitlement instance.
/// </summary>
public static Entitlement FromJSON(JSONNode n)
{
var e = new Entitlement();

e.Id = n["id"] ?? throw new Exception("id is required");
e.SkuId = n["sku_id"] ?? throw new Exception("sku_id is required");
e.ApplicationId = n["application_id"] ?? throw new Exception("application_id is required");
e.UserId = n["user_id"] ?? throw new Exception("user_id is required");
e.GiftCodeFlags = n["gift_code_flags"].AsInt;
e.Type = (EntitlementType)n["type"].AsInt;

// optional / nullable
e.GifterUserId = n["gifter_user_id"].IsNull ? null : n["gifter_user_id"];

if (n["branches"].IsArray)
{
e.Branches = new List<string>();
foreach (var item in n["branches"].AsArray)
e.Branches.Add(item.Value);
}

// parse ISO date strings if present & non-null
string sa = n["starts_at"];
e.StartsAt = string.IsNullOrEmpty(sa) ? (DateTime?)null : DateTime.Parse(sa, null, System.Globalization.DateTimeStyles.RoundtripKind);

string ea = n["ends_at"];
e.EndsAt = string.IsNullOrEmpty(ea) ? (DateTime?)null : DateTime.Parse(ea, null, System.Globalization.DateTimeStyles.RoundtripKind);

e.ParentId = n["parent_id"].IsNull ? null : n["parent_id"];
e.Consumed = n["consumed"].IsNull ? (bool?)null : n["consumed"].AsBool;
e.Deleted = n["deleted"].IsNull ? (bool?)null : n["deleted"].AsBool;
e.GiftCodeBatchId = n["gift_code_batch_id"].IsNull ? null : n["gift_code_batch_id"];

return e;
}

}
11 changes: 11 additions & 0 deletions Assets/PlayroomKit/modules/Discord/Entitlement.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Assets/PlayroomKit/modules/Headers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,9 @@ private static extern string GetPersistentDataInternal(string key,
#region Discord
[DllImport("__Internal")]
private static extern void OpenDiscordInviteDialogInternal(Action callback = null);
#endregion

[DllImport("__Internal")]
private static extern void StartDiscordPurchaseInternal(string skuId, Action<string, string> callback);
#endregion
}
}
13 changes: 13 additions & 0 deletions Assets/PlayroomKit/modules/Helpers/CallbackManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ public static void InvokeCallback(string key, TurnData turnData)
$"Callback with key {key} is of unsupported type or incorrect number of arguments: {turnData}!");
}
}



public static void InvokeCallback(string key, List<TurnData> turnData)
{
Expand All @@ -111,6 +113,17 @@ public static void InvokeCallback(string key, List<TurnData> turnData)
$"Callback with key {key} is of unsupported type or incorrect number of arguments: {turnData}!");
}
}

public static void InvokeCallback(string key, List<Entitlement> Entitlement)
{
if (callbacks.TryGetValue(key, out Delegate callback))
{
if (callback is Action<List<Entitlement>> action) action?.Invoke(Entitlement);
else
Debug.LogError(
$"Callback with key {key} is of unsupported type or incorrect number of arguments: {Entitlement}!");
}
}

public static bool CheckCallback(string key)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ void RpcCallWrapper(string name, string data, RpcMode mode,
#endregion

#region Discord

void OpenDiscordInviteDialogInternalWrapper(Action callback = null);
#endregion

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ public void OpenDiscordInviteDialogInternalWrapper(Action callback = null)
{
OpenDiscordInviteDialogInternal(callback);
}


#endregion
}
}
Expand Down
1 change: 1 addition & 0 deletions Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = nul

#region Discord
public void OpenDiscordInviteDialog(Action callback = null);
public void StartDiscordPurchase(string skuId, Action<List<Entitlement>> callback = null);
#endregion


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,11 @@ public void OpenDiscordInviteDialog(Action callback = null)
callback?.Invoke();
}

public void StartDiscordPurchase(string skuId, Action<List<Entitlement>> callback = null)
{
DebugLogger.LogWarning("[MockMode] Discord purchase is currently not supported in browser mock mode!");
callback?.Invoke(new List<Entitlement>());
}
#endregion
}
#endif
Expand Down
6 changes: 6 additions & 0 deletions Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,12 @@ public void OpenDiscordInviteDialog(Action callback = null)
DebugLogger.LogWarning("[MockMode] Discord invite dialog is currently not supported in local mode!");
callback?.Invoke();
}

public void StartDiscordPurchase(string skuId, Action<List<Entitlement>> callback = null)
{
DebugLogger.LogWarning("[MockMode] Discord purchase is currently not supported in local mode!");
callback?.Invoke(new List<Entitlement>());
}
#endregion
}
}
26 changes: 26 additions & 0 deletions Assets/PlayroomKit/modules/PlayroomBuildService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,32 @@ public void OpenDiscordInviteDialog(Action callback = null)
CallbackManager.RegisterCallback(callback, "discordInviteDialog");
_interop.OpenDiscordInviteDialogInternalWrapper(OpenDiscordInviteDialogCallbackInvoker);
}

[MonoPInvokeCallback(typeof(Action<string, string>))]
private static void DiscordPurchaseCallback(string skuId, string result)
{
JSONNode root = JSON.Parse(result);

List<Entitlement> entitlements = new List<Entitlement>();

if (root != null && root.IsArray)
{
foreach (JSONNode item in root.AsArray)
{
Entitlement e = Entitlement.FromJSON(item);
entitlements.Add(e);
}
}

CallbackManager.InvokeCallback(skuId, entitlements);
}

public void StartDiscordPurchase(string skuId, Action<List<Entitlement>> callback = null)
{
CheckPlayRoomInitialized();
CallbackManager.RegisterCallback(callback, skuId);
StartDiscordPurchaseInternal(skuId, DiscordPurchaseCallback);
}
#endregion

#region Callbacks
Expand Down
29 changes: 29 additions & 0 deletions Assets/PlayroomKit/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,35 @@ mergeInto(LibraryManager.library, {
console.error("Failed to open Discord invite dialog:", error);
});
},

StartDiscordPurchaseInternal: function (skuId, callback) {
if (!window.Playroom) {
console.error(
"Playroom library is not loaded. Please make sure to call InsertCoin first."
);
return;
}

try {
// startPurchase internal…
Playroom.getDiscordClient().commands.startPurchase({sku_id: UTF8ToString(skuId)}).then((response) => {
console.log("[JSLIB]: Purchase started successfully.");
var keyPtr = stringToNewUTF8(skuId);
var returnData = stringToNewUTF8(JSON.stringify(response));

console.log("[JSLIB]: Purchase response: ", response);
console.warn("[JSLIB]: Purchase data json: ", JSON.stringify(response));

{{{ makeDynCall('vii', 'callback') }}}(keyPtr, dataStrPtr);
})
.catch((error) => {
console.error("[JSLIB]: Failed to start purchase:", error);
});
} catch (error) {
console.error("[JSLIB]: Error starting purchase:", error);
}
},

//#endregion


Expand Down
33 changes: 25 additions & 8 deletions Assets/Scripts/GameManager.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
using System;
using System.Collections.Generic;
using Playroom;
using TMPro;
using UnityEngine;

public class GameManager : MonoBehaviour
{
private PlayroomKit _kit;
private PlayroomKit playroomKit;

public TextMeshProUGUI text;

bool coinInserted = false;

string skuId = "123456789";

private void Awake()
{
_kit = new PlayroomKit();
playroomKit = new PlayroomKit();
}

private void Start()
{
_kit.InsertCoin(new InitOptions()
playroomKit.InsertCoin(new InitOptions()
{
gameId = "cW0r8UJ1aXnZ8v5TPYmv",
maxPlayersPerRoom = 2,
Expand All @@ -27,7 +31,7 @@ private void Start()

private void OnLaunchCallBack()
{
_kit.OnPlayerJoin(CreatePlayer);
playroomKit.OnPlayerJoin(CreatePlayer);
coinInserted = true;
}

Expand All @@ -40,16 +44,29 @@ private void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
Debug.Log("Token: " + _kit.GetPlayroomToken());
text.text = _kit.GetPlayroomToken();
Debug.Log("Token: " + playroomKit.GetPlayroomToken());
text.text = playroomKit.GetPlayroomToken();
}

if (Input.GetKeyDown(KeyCode.I))
{
_kit.OpenDiscordInviteDialog(()=>
playroomKit.OpenDiscordInviteDialog(() =>
{
text.text = "Discord invite dialog opened!";
});
}

if (Input.GetKeyDown(KeyCode.P))
{
// After InsertCoin has fully invoked
playroomKit.StartDiscordPurchase(skuId, (response) =>
{
foreach (var entitlement in response)
{
Debug.Log($"Entitlement: {entitlement}");
text.text += $"\nEntitlement: {entitlement}";
}
});
}
}
}