papi
papi

Reputation: 389

How to get how many hours has users spent playing my game? Steamworks API

How to get how many hours has users spent playing my game? Using Steamworks API and C# in Unity. I have went through a documentation but haven't found anything like that, and thinking that I am missing something.

I should've just went with a simple script that logs minutes played in its own game, but it's too late for that. If anyone can give me a hit or point me a right direction, I'd really appreciate it.

Upvotes: 5

Views: 5040

Answers (2)

sandolkakos
sandolkakos

Reputation: 302

I just started working with Steam API and also noticed there's no C++ API to get the user playtime (the time displayed in the Game Library). But after seeing @Timo Salomäki's post, I decided to investigate a bit more and found we can do it using the Steam Web Api to get data like this:

{
    "response": {
        "playtime_2weeks": 175,
        "playtime_forever": 332,
        "last_playtime": 1729575611,
        "first_playtime": 1726277368,
        "playtime_windows_forever": 179,
        "playtime_mac_forever": 153,
        "playtime_linux_forever": 0,
        "first_windows_playtime": 1726277368,
        "first_mac_playtime": 1726279511,
        "first_linux_playtime": 0,
        "last_windows_playtime": 1729575611,
        "last_mac_playtime": 1726519780,
        "last_linux_playtime": 0,
        "playtime_current_session": 10,
        "playtime_deck_forever": 0,
        "first_deck_playtime": 0,
        "last_deck_playtime": 0,
        "playtime_disconnected": 0
    }
}

So, we can make a WebRequest from the App and sum playtime_forever + playtime_current_session to get the reliable total time.

Here is the Unity C# code. Use it as you want and do not forget to do something safe with your Web API Key. It is not recommended to keep it inside your game.

using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Steamworks;
using UnityEngine;
using UnityEngine.Networking;

namespace OrGames.Stats
{
    public static class PlayTimeGetter
    {
        /// <summary>
        /// Access the Steam Web API to get the playtime of the current user in the current game.
        /// </summary>
        /// <param name="steamworksApiKey">See how to create your key here: https://partner.steamgames.com/doc/webapi_overview/auth#publisher-keys</param>
        /// <returns>Minutes: playtime_forever + playtime_current_session</returns>
        public static async Task<long> GetPlaytimeInMinutes(string steamworksApiKey)
        {
            ulong userSteamId = SteamUser.GetSteamID().m_SteamID;
            uint gameId = SteamUtils.GetAppID().m_AppId;

            string url =
                $"https://partner.steam-api.com/IPlayerService/GetSingleGamePlaytime/v1/?key={steamworksApiKey}&steamid={userSteamId}&appid={gameId}";

            using UnityWebRequest request = UnityWebRequest.Get(url);

            await request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                throw new Exception($"Failed to get playtime: {request.error}");
            }

            var data = JsonUtility.FromJson<SingleGamePlaytime>(request.downloadHandler.text);
            return data.Response.PlaytimeForever + data.Response.PlaytimeCurrentSession;
        }

        public class SingleGamePlaytime
        {
            [JsonProperty("response")]
            public PlaytimeResponse Response { get; set; }
        }

        public class PlaytimeResponse
        {
            [JsonProperty("first_playtime")]
            public long FirstPlaytime { get; set; }

            [JsonProperty("last_playtime")]
            public long LastPlaytime { get; set; }

            [JsonProperty("playtime_forever")]
            public long PlaytimeForever { get; set; }

            [JsonProperty("playtime_current_session")]
            public long PlaytimeCurrentSession { get; set; }
        }
    }
}

Upvotes: 0

Timo Salom&#228;ki
Timo Salom&#228;ki

Reputation: 7189

You might still have a chance to get it to work. As far as I know, there's a way to get the total hours played (as shown in the Gameplay stats) by using the deprecated Community XML Data:

Player Game Stats

To retrieve game stats, you will need the game's Steam Community name. Developers can contact Valve to obtain the community name for their game.

You can retrieve stats and achievements for a player per game using the player's 64-bit Steam ID with: Format: http://steamcommunity.com/profiles/[SteamID]/stats/[CommunityGameName]/?xml=1

Example: http://steamcommunity.com/profiles/76561197968575517/stats/L4D/?xml=1

In the example you can see the hoursPlayed field on the bottom of the image:

hoursPlayed field

Now, the problem obviously is that this is deprecated and Steam advices you to use the web APIs whenever possible. However, I haven't seen a way to access this data through the web API so I think that this is your best bet without rolling out a custom way of tracking playtime.

Upvotes: 4

Related Questions