# List Notifications and Mark as Read In-Game

In this How-to, we’ll get all unread notifications for the logged in player, find a specific notification by a key and mark it as read.

## Prerequisites

* [A LootLocker account and a created game](https://docs.lootlocker.com/the-basics/readme)
* There are a few different systems that can cause notifications in LootLocker
  * [Triggers](https://docs.lootlocker.com/game-systems/triggers/how-to/setting-up-triggers-in-console)
  * Purchasing a [Catalog Item](https://docs.lootlocker.com/commerce/catalogs/how-to/setup-catalogs)
  * [Twitch Drops](https://docs.lootlocker.com/content/twitch-drops)
  * Custom notifications from the [admin api](https://ref.lootlocker.com/admin/api-15573621), Server SDK (using the SendNotificationToPlayer methods), or through the console (go to a player in the player list, choose actions, and "Send Notification").
* [An active Game Session](https://docs.lootlocker.com/players/authentication)
* A previously sent notification from for example an [invoked trigger](https://docs.lootlocker.com/game-systems/triggers/how-to/invoke-trigger-in-game) or a [successful purchase](https://docs.lootlocker.com/commerce/catalogs/how-to/setup-ingame-catalog-store).

To get the matched notification to a previous action (an invoked trigger, a purchase call), you need one or more of the following:

* **A purchase using virtual currency**: use the `catalog_listing_id`
* **An In App Purchase using Apple App Store**: use the `transaction_id`
* **An In App Purchase using Google Pla Store**: use the `product_id`
* **An In App Purchase using Steam Store**: use the `entitlement_id`
* **A trigger**: use the `trigger_key`
* **A twitch drop**: use the `twitch reward id`
* **A custom notification from server, console, or admin api**: use the notification type you set for the notification.

{% tabs %}
{% tab title="Unity" %}

```csharp
// We're only interested in unread notifications for this how to.
// If you want to see information about notifications you've previously marked as read then set this to true
bool showRead = false;

// The key that we saved from invoking a trigger, or calling a purchase to get the correct notification
string notificationKey = "saved_trigger_key_or_catalog_item_id_from_a_previous_response";

// You can optionally return only a specific priority
LootLocker.LootLockerEnums.LootLockerNotificationPriority? priority = null;

// You can optionally return only a specific type of notification. 
// Triggers and purchased items are of the type LootLocker.LootLockerStaticStrings.LootLockerNotificationTypes.PullRewardAcquired
string ofType = LootLocker.LootLockerStaticStrings.LootLockerNotificationTypes.PullRewardAcquired;

// The source of the notification: a type of purchase or trigger.
// Use the static strings provided in LootLocker.LootLockerStaticStrings.LootLockerNotificationSources 
// to specify what type of notification you are requesting.
// For purchases, use: 
// LootLocker.LootLockerStaticStrings.LootLockerNotificationSources.Purchasing.(the source of purchase: LootLocker, AppleAppStore, GooglePlayStore, SteamStore)
// For triggers, use: 
// LootLocker.LootLockerStaticStrings.LootLockerNotificationSources.Triggers
string notificationSource = LootLocker.LootLockerStaticStrings.LootLockerNotificationSources.Triggers;

// The Page and Count parameters are used for pagination.
// Count means count per page, and Page is what page to access.
// For example: A count of 100, and page 2 would list all notifications (if any) from 101-201
int count = 10;
int page = 1;
LootLockerSDKManager.ListNotifications(showRead, priority, ofType, notificationSource, count, page, (response) =>
{
    if (!response.success)
    {
        Debug.Log("Error, could not list notifications:" + response.errorData.message);
        // Add your own code here to handle the error
        return;
    }

    // A notifications request returns success even if no notifications were found,
    // handle that by checking if the notifications returned are null
    if (response.Notifications == null)
    {
        Debug.LogWarning("Error: no notifications found");
        // Add your own code to handle what should happen
        return;
    }

    // Get the desired notification
    LootLockerNotification[] matchingNotifications;
    bool notificationWasFound = response.TryGetNotificationsByIdentifyingValue(notificationKey, out matchingNotifications);
    
    if ( !notificationWasFound || matchingNotifications?.Length == 0 ) 
    {
        Debug.LogWarning("Error: Notification not found.");
        // Add your own code here to handle the error
        return;
    }

    // In this example we know that the trigger has only been invoked once so we can safely access the first element of the array
    LootLockerNotification desiredNotification = matchingNotifications[0];

    if (desiredNotification == null)
    {
        Debug.LogWarning("Error: Notification not found.");
        // Add your own code here to handle the error
        return;
    }

    // In this example we know that the notification is of the type LootLocker.LootLockerStaticStrings.LootLockerNotificationTypes.PullRewardAcquired all of which have the reward content body
    LootLockerNotificationContentRewardBody body;
    if (!desiredNotification.Content.TryGetContentBodyAsRewardNotification(out body))
    {
        Debug.LogWarning("Could not parse content body as reward notification.");
        // Add your own code here to handle the error
        return;                
    }

    // The enum value in the notification.Content.Body.Kind field shows what type of "thing" was rewarded, use that to know which field in the body contains the data about the reward.
    switch (body.Kind)
    {
        case LootLocker.LootLockerEnums.LootLockerNotificationContentKind.group:
            // The reward is a reward group which contains a list of "associations". Ie, a list of assets, currencies, or other similar things rewarded as one in this single reward.
            // Handle this in line with your game logic 
            Debug.Log($"Trigger with key '{notificationKey}' gave reward of type group. The group has name '{desiredNotification.Content.Body.Group.Name}', description '{desiredNotification.Content.Body.Group.Description}'. and {desiredNotification.Content.Body.Group.Associations.Length} associations.");
            break;
        case LootLocker.LootLockerEnums.LootLockerNotificationContentKind.currency:
            // The reward is a currency. Handle this in line with your game logic 
            Debug.Log($"Trigger with key '{notificationKey}' gave reward of type currency: {desiredNotification.Content.Body.Currency.Details.Amount} {desiredNotification.Content.Body.Currency.Details.Code}");
            break;
        case LootLocker.LootLockerEnums.LootLockerNotificationContentKind.asset:
            // The reward is an asset. Handle this in line with your game logic 
            Debug.Log($"Trigger with key '{notificationKey}' gave reward of type asset with name '{desiredNotification.Content.Body.Asset.Details.Name}'");
            break;
        case LootLocker.LootLockerEnums.LootLockerNotificationContentKind.progression_reset:
            // The reward is a progression reset. Handle this in line with your game logic 
            Debug.Log($"Trigger with key '{notificationKey}' gave reward of type progression reset which resets the progression named '{desiredNotification.Content.Body.Progression_reset.Details.Name}'");
            break;
        case LootLocker.LootLockerEnums.LootLockerNotificationContentKind.progression_points:
            // The reward is progression points. Handle this in line with your game logic 
            Debug.Log($"Trigger with key '{notificationKey}' gave reward of type progression points which gives the player {desiredNotification.Content.Body.Progression_points.Details.Amount} points in the progression named '{desiredNotification.Content.Body.Progression_points.Details.Name}'");
            break;
        default:
            Debug.LogWarning($"Unhandled case {body.Kind.ToString()}");
            break;
    }
    
    // After you've handled the notification in your game logic, remember to mark it as read.
    // This way it will not be returned on the next request unless you specifically request notifications marked as read.
    desiredNotification.MarkThisNotificationAsRead((response) =>
    {
        if (response.success)
        {
            Debug.Log("Marked notification as read");
        }
        else
        {
            Debug.LogWarning("Error marking notification as read: " + response.errorData.message);
            // Add your own code here to handle the error
        }
    });
});
```

{% endtab %}

{% tab title="Unreal" %}

<figure><img src="https://534367586-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVu1MPzezO-NgvC98xh%2Fuploads%2Fgit-blob-89db7fca59c3b1e4f9345769dab3d13fe57d3462%2FhowTo-listNotificationsAndMarkAsRead-UnrealBP.png?alt=media" alt=""><figcaption><p>Blueprint example of how to list notifications and subsequently mark the handled notifications as read. To copy the example, see <a href="https://blueprintue.com/blueprint/8wa1wn-m/">https://blueprintue.com/blueprint/8wa1wn-m/</a>.</p></figcaption></figure>

### Input

In this example, we're filtering notifications by their source using the triggers string. Other filters include:

* **Show Read**: Set to true to include previously read notifications.
* **Priority**: Fetch notifications of a specific priority.
* **Of Type**: Fetch notifications of a specific type, such as PullRewardAcquired for triggers and purchased items. If there are many notifications, use pagination to navigate through the data.

### Mark as read

Once a notification is processed in your game logic, mark it as read. This will exclude it from future requests unless you specifically request read notifications. This action should be applied to each item in the list of `handled notifications`.

### Logic for handling Notifications

When listing notifications, branch the completed event based on the success flag and add error handling for failed requests.

*Note on Pagination: The notification response includes pagination data to help you navigate large notification lists.*

We recommend branching the completed event from listing notifications on the success flag, and if you do this you will probably want to add error handling in case the request fails.

Here, we retrieve only unread notifications from the triggers source with default pagination (up to 10 items). We then filter further by `SuccessfullyInvokedTriggerKey` to narrow the list to specific triggers.

<figure><img src="https://534367586-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVu1MPzezO-NgvC98xh%2Fuploads%2Fgit-blob-9870746772e555ec48c0d942aeb6fb23860469a6%2FhowTo-HandleNotifications-UnrealBP.png?alt=media" alt=""><figcaption><p>Blueprint example of how to list notifications and subsequently mark the handled notifications as read. To copy the example, see <a href="https://blueprintue.com/blueprint/m9x3-yjs/">https://blueprintue.com/blueprint/m9x3-yjs/</a>.</p></figcaption></figure>

In this example, we simply print the notification info. Adapt this step to handle notifications based on your game’s requirements. Here, we assume that `SuccessfullyInvokedTriggerKey` provides a currency reward and only expand that information.

For a more general approach, iterate over all notifications to handle various sources and types relevant to your game. The example below outlines how to extract different types of rewards.

<figure><img src="https://534367586-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVu1MPzezO-NgvC98xh%2Fuploads%2Fgit-blob-c547cb281bf43784724f218fa50da56365df8916%2FhowTo-ExtractNotificationRewards-UnrealBP.png?alt=media" alt=""><figcaption><p>Blueprint example of how to extract reward information from a notification. To copy the example, see <a href="https://blueprintue.com/blueprint/kx16g174/">https://blueprintue.com/blueprint/kx16g174/</a>.</p></figcaption></figure>
{% endtab %}

{% tab title="REST" %}

```bash
curl --location --request GET 'https://api.lootlocker.io/game/notifications/v1?per_page=10&page=1' \
--header 'x-session-token: 3266edd928f5769545425469ac417fee456d8367' \

curl --location --request PUT 'https://api.lootlocker.io/game/notifications/v1/read' \
--header 'x-session-token: 3266edd928f5769545425469ac417fee456d8367' \
--header 'Content-Type: application/json' \
--data-raw '{
    "notifications": [
"01J6VYWY115186HY5N87HQDEC0",
"01J6VYWY0S1Z0MKKP9MTA8WZKB",
"01J6VYWY0F1MJ6E7QS93PZ4TQ7"
    ]
}'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
It is important to mark notifications as **read** after you have taken action on it, otherwise you will need to go through all notifications each time, which increases response times, resulting in a bad experience for your players.
{% endhint %}

## Conclusion

In this How-to, we’ve listed a notification and marked it as read. Notifications are to be called after a [purchase has been made](https://docs.lootlocker.com/commerce/catalogs) or after an invoked [trigger](https://docs.lootlocker.com/game-systems/triggers).
