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
8 changes: 8 additions & 0 deletions Assets/PlayroomKit/modules/Store.meta

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

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

namespace Playroom
{
[Serializable]
public class PlayerEntitlement<TMetadata>
{
public string id;
public string paymentId;
public string playerId;
public string skuId;
public bool free;
public bool active;
public bool deleted;
public DateTime createdAt;
public DateTime updatedAt;
public DateTime? startDate;
public DateTime? endDate;
public string type;
public string key;
public TMetadata metadata; // create your own class for metadata based on your needs.

private static PlayerEntitlement<TMetadata> FromJSONNode(JSONNode node, Func<string, TMetadata> metadataParser)
{
var rawMeta = node["metadata"]?.ToString() ?? "{}";

PlayerEntitlement<TMetadata> data = new()
{
id = node["id"]?.Value ?? string.Empty,
paymentId = node["paymentId"]?.Value ?? string.Empty,
playerId = node["playerId"]?.Value ?? string.Empty,
skuId = node["skuId"]?.Value ?? string.Empty,
startDate = DateTime.TryParse(node["startDate"]?.Value, out var sAt) ? sAt : null,
endDate = DateTime.TryParse(node["endDate"]?.Value, out var eAt) ? eAt : null,
free = node["free"] != null && node["free"].AsBool,
type = node["type"]?.Value ?? string.Empty,
key = node["key"]?.Value ?? string.Empty,
active = node["active"] != null && node["active"].AsBool,
deleted = node["deleted"] != null && node["deleted"].AsBool,
createdAt = DateTime.TryParse(node["createdAt"]?.Value, out var cAt) ? cAt : DateTime.MinValue,
updatedAt = DateTime.TryParse(node["updatedAt"]?.Value, out var uAt) ? uAt : DateTime.MinValue,
metadata = metadataParser(rawMeta)
};
return data;
}

public static List<PlayerEntitlement<TMetadata>> FromJSON(string jsonString, Func<string, TMetadata> metadataParser)
{
List<PlayerEntitlement<TMetadata>> entitlements = new();
JSONNode root = JSON.Parse(jsonString);

if (!root.IsArray)
Debug.LogWarning("Expected an array");

foreach (JSONNode item in root.AsArray)
{
var data = FromJSONNode(item, metadataParser);
entitlements.Add(data);
}

return entitlements;
}
}
}
11 changes: 11 additions & 0 deletions Assets/PlayroomKit/modules/Store/PlayerEntitlements.cs.meta

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

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

namespace Playroom
{
[Serializable]
public class SKU<TMetadata>
{
public string id;
public string name;
public string description;
public string type;
public string image;
public string key;
public bool active;
public bool deleted;
public DateTime createdAt;
public DateTime updatedAt;
public TMetadata metadata; // create your own class for metadata based on your needs.
public string price;
public string productId;

private static SKU<TMetadata> FromJSONNode(JSONNode node, Func<string, TMetadata> metadataParser)
{
var rawMeta = node["metadata"]?.ToString() ?? "{}";


SKU<TMetadata> data = new()
{
id = node["id"]?.Value ?? string.Empty,
name = node["name"]?.Value ?? string.Empty,
description = node["description"]?.Value ?? string.Empty,
type = node["type"]?.Value ?? string.Empty,
image = node["image"]?.Value,
key = node["key"]?.Value ?? string.Empty,
active = node["active"] != null && node["active"].AsBool,
deleted = node["deleted"] != null && node["deleted"].AsBool,
price = node["price"]?.Value ?? string.Empty,
productId = node["productId"]?.Value ?? string.Empty,
createdAt = DateTime.TryParse(node["createdAt"]?.Value, out var cAt) ? cAt : DateTime.MinValue,
updatedAt = DateTime.TryParse(node["updatedAt"]?.Value, out var uAt) ? uAt : DateTime.MinValue,
metadata = metadataParser(rawMeta)
};
return data;
}

public static List<SKU<TMetadata>> FromJSON(string jsonString, Func<string, TMetadata> metadataParser)
{
List<SKU<TMetadata>> skus = new();
JSONNode root = JSON.Parse(jsonString);

if (!root.IsArray)
Debug.LogWarning("Expected an array of SKUs");

foreach (JSONNode item in root.AsArray)
{
SKU<TMetadata> data = FromJSONNode(item, metadataParser);
skus.Add(data);
}

return skus;
}
}
}
11 changes: 11 additions & 0 deletions Assets/PlayroomKit/modules/Store/SKU.cs.meta

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

4 changes: 4 additions & 0 deletions Assets/Scenes/TestScene.unity
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,11 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: dc3a2b9cdc24aab40906ce4bcdee9943, type: 3}
m_Name:
m_EditorClassIdentifier:
baseUrl: https://ws.joinplayroom.com/api/store
gameApiKey: 510a71af-3a69-4f5d-9b9b-296a1871e624
text: {fileID: 1547749}
skus: []
entitlements: []
--- !u!4 &1054460207
Transform:
m_ObjectHideFlags: 0
Expand Down
111 changes: 111 additions & 0 deletions Assets/Scripts/GameManager.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Playroom;
using SimpleJSON;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;

public class GameManager : MonoBehaviour
{
[SerializeField] private string baseUrl = "https://ws.joinplayroom.com/api/store";
[SerializeField] private string gameApiKey;

private PlayroomKit playroomKit;

public TextMeshProUGUI text;
Expand All @@ -14,6 +20,72 @@ public class GameManager : MonoBehaviour

string skuId = "1371921246031319121";

[Header("SKUs")]
[SerializeField]
private List<SKU<CustomMetadataClass>> skus;

[Header("Entitlements")]
[SerializeField]
private List<PlayerEntitlement<CustomMetadataClass>> entitlements;

[Serializable]
public class CustomMetadataClass
{
public string packId;
}

public void FetchSKUS(Action<string> onRequestComplete = null)
{
StartCoroutine(GetSKUS(onRequestComplete));
}

private IEnumerator GetSKUS(Action<string> onRequestComplete = null)
{
var url = $"{baseUrl}/sku?gameId={UnityWebRequest.EscapeURL("FmOBeUfQO2AOLNIrJNSJ")}&platform={UnityWebRequest.EscapeURL("discord")}";

using (var req = UnityWebRequest.Get(url))
{
req.SetRequestHeader("x-game-api", gameApiKey);
yield return req.SendWebRequest();

if (req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"Error fetching SKUs: {req.error}");
}
else
{
onRequestComplete?.Invoke(req.downloadHandler.text);
}
}
}

public void FetchEntitlements(Action<string> onRequestComplete)
{
StartCoroutine(GetEntitlements(onRequestComplete));
}

private IEnumerator GetEntitlements(Action<string> onRequestComplete)
{
var url = $"{baseUrl}/entitlement?gameId={UnityWebRequest.EscapeURL("FmOBeUfQO2AOLNIrJNSJ")}";

using (var req = UnityWebRequest.Get(url))
{
//TODO: THIS IS FOR TESTING ONLY, REMOVE LATER
string token = "eyJhbGciOiJIUzI1NiJ9.eyJkaXNjb3JkSWQiOiI0NzY3MDk1MjQwMTE2MTQyMTkiLCJyb29tSWQiOiJEQ1JEX2ktMTM3NDY3NDQ2MDUyMjcxMzE1OS1nYy0xMjczNjA3Njg2ODE4MTA3NDAyLTEyNzQ5OTUxNDcyNjc4OTk0NTYiLCJnYW1lSWQiOiJGbU9CZVVmUU8yQU9MTklySk5TSiIsImd1aWxkSWQiOiIxMjczNjA3Njg2ODE4MTA3NDAyIiwiY2hhbm5lbElkIjoiMTI3NDk5NTE0NzI2Nzg5OTQ1NiIsImFjY2Vzc1Rva2VuIjoiV2FVNFV1RjJ6UEJOTzY1QWZISlNrR2RzaVBGOWpKIiwiYXV0aCI6ImRpc2NvcmQiLCJ0IjoxNzQ3ODE4MzYzfQ.bRvWY7SMafo0iQzfdp0N53Euu58eC35AZ6ruiCdgF0M";
req.SetRequestHeader("Authorization", $"Bearer {token}");
yield return req.SendWebRequest();

if (req.result == UnityWebRequest.Result.ConnectionError ||
req.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"Error fetching entitlements: {req.error}");
onRequestComplete?.Invoke(req.error);
yield break;
}
onRequestComplete?.Invoke(req.downloadHandler.text);
}
}

private void Awake()
{
playroomKit = new PlayroomKit();
Expand Down Expand Up @@ -56,11 +128,50 @@ private void Update()
});
}

if (Input.GetKeyDown(KeyCode.E))
{
FetchEntitlements((data) =>
{
text.text = "Entitlements fetched successfully!";
Debug.Log("Entitlements fetched successfully!");

entitlements = PlayerEntitlement<CustomMetadataClass>.FromJSON(data, ParseMetadata);
});
}

if (Input.GetKeyDown(KeyCode.S))
{
FetchSKUS((jsonString) =>
{
text.text = "SKUs fetched successfully!";
Debug.Log("SKUs fetched successfully!");

skus = SKU<CustomMetadataClass>.FromJSON(jsonString, ParseMetadata);
});
}

CustomMetadataClass ParseMetadata(string json)
{
JSONNode node = JSON.Parse(json);

return new CustomMetadataClass()
{
packId = node["packId"],
};
}

CustomMetadataClass ParseMetadataUnity(string json)
{
return JsonUtility.FromJson<CustomMetadataClass>(json);
}


if (Input.GetKeyDown(KeyCode.P))
{
// After InsertCoin has fully invoked
playroomKit.StartDiscordPurchase(skuId, (response) =>
{
text.text = "Purchase started successfully!";
Debug.Log($"Entitlement: {response}");
});
}
Expand Down