# API reference

> Every public type, property, event and method in the Grovs Unity SDK 1.0.

Source: https://docs.grovs.io/docs/sdk/unity/api-reference

Everything is in the `GrovsSDK` namespace. All members are static on `Grovs`, except [`GrovsUnityIAP`](#grovsunityiap) and the [types](#types).

```csharp
using GrovsSDK;
```

- **No init call.** The native SDK starts before Unity with the values from [Project Settings](https://docs.grovs.io/docs/sdk/unity/quick-start#project-settings).
- **Threads.** Call the API from the Unity main thread. Every `Task` completes, and every callback and event runs, on the main thread. The one exception is [`ShouldShowInAppMessage`](#shouldshowinappmessage).
- **Tasks or callbacks.** Each async call has a `Task` version and a callback version. A failed task throws [`GrovsException`](#grovsexception). The callback gets the [`GrovsError`](#grovserror) instead, or `null` on success. Pending tasks have no timeout.
- **Not started.** If the native SDK didn't start (an empty API key, say), other calls do nothing and async calls fail with `SdkNotInitialized`.
- **Editor and other platforms.** Calls go to a stub that logs once per method and does nothing. Link calls fail with `UnsupportedPlatform`, purchase calls resolve `false`.

## At a glance

| Area                | Member                                                | Kind     | What it does                                      |
| ------------------- | ----------------------------------------------------- | -------- | ------------------------------------------------- |
| **Setup**           | [`SdkVersion`](#sdkversion)                           | property | Unity package version                             |
|                     | [`IsSupportedPlatform`](#issupportedplatform)         | property | `true` on iOS and Android players                 |
|                     | [`SetLogLevel`](#setloglevel)                         | method   | Native log level                                  |
|                     | [`ErrorOccurred`](#erroroccurred)                     | event    | SDK errors with no other place to go              |
| **Consent**         | [`SetEnabled`](#setenabled)                           | method   | Turns collection on or off, and saves the choice  |
|                     | [`IsEnabled`](#isenabled)                             | property | Whether Grovs is running                          |
| **Deep links**      | [`DeeplinkReceived`](#deeplinkreceived)               | event    | Opened links, buffered until the first subscriber |
|                     | [`LastDeeplink`](#lastdeeplink)                       | property | Most recent link                                  |
|                     | [`HandleUrl`](#handleurl)                             | method   | Opens a link tapped inside the game               |
| **Links**           | [`GenerateLinkAsync`](#generatelinkasync)             | method   | Creates a smart link                              |
|                     | [`GenerateLink`](#generatelink)                       | method   | Callback version                                  |
|                     | [`GetLinkDetailsAsync`](#getlinkdetailsasync)         | method   | Details of a link by path                         |
|                     | [`GetLinkDetails`](#getlinkdetails)                   | method   | Callback version                                  |
| **Users**           | [`SetUserIdentifier`](#setuseridentifier)             | method   | Your ID for the player                            |
|                     | [`SetUserAttributes`](#setuserattributes)             | method   | Attributes of the player                          |
| **Events**          | [`Track`](#track)                                     | method   | Tracks a custom event                             |
|                     | [`TrackScreenView`](#trackscreenview)                 | method   | Tracks a screen view                              |
|                     | [`SetGlobalTags`](#setglobaltags)                     | method   | Tags added to every event                         |
|                     | [`SetScreenAliases`](#setscreenaliases)               | method   | Renames screens for the dashboard                 |
| **Revenue**         | [`LogInAppPurchaseAsync`](#loginapppurchaseasync)     | method   | Logs a store purchase                             |
|                     | [`LogCustomPurchaseAsync`](#logcustompurchaseasync)   | method   | Logs a purchase outside the stores                |
|                     | [`GrovsUnityIAP.LogPurchaseAsync`](#logpurchaseasync) | method   | Logs a Unity IAP `Product`                        |
|                     | [`GrovsUnityIAP.LogOrderAsync`](#logorderasync)       | method   | Logs a Unity IAP 5 `Order`                        |
| **Push**            | [`SetPushToken`](#setpushtoken)                       | method   | Sets a push token Grovs can't see                 |
|                     | [`IsGrovsNotification`](#isgrovsnotification)         | method   | Checks if Grovs sent a push                       |
|                     | [`HandleNotificationOpen`](#handlenotificationopen)   | method   | Handles a tap from its payload                    |
| **In-app messages** | [`InAppMessageEvent`](#inappmessageevent)             | event    | Shown, clicked, dismissed, answered, failed       |
|                     | [`ShouldShowInAppMessage`](#shouldshowinappmessage)   | property | Veto for each message                             |
|                     | [`PauseInAppMessages`](#pauseinappmessages)           | method   | Holds messages back                               |
|                     | [`ResumeInAppMessages`](#resumeinappmessages)         | method   | Lets messages show again                          |
|                     | [`DiscardInAppMessages`](#discardinappmessages)       | method   | Drops the waiting message                         |
|                     | [`SetInAppExcludedScreens`](#setinappexcludedscreens) | method   | Screens where no message shows                    |
|                     | [`SetInAppDebugLogging`](#setinappdebuglogging)       | method   | Logs why campaigns were skipped                   |
| **Types**           | [`GrovsDeeplink`](#grovsdeeplink)                     | class    | An opened link                                    |
|                     | [`GrovsTracking`](#grovstracking)                     | class    | Campaign, source and medium                       |
|                     | [`GenerateLinkOptions`](#generatelinkoptions)         | class    | Link generation input                             |
|                     | [`GrovsRedirect`](#grovsredirect)                     | class    | One platform redirect                             |
|                     | [`InAppMessageEvent`](#inappmessageevent-type)        | class    | One in-app message event                          |
|                     | [`InAppEventType`](#inappeventtype)                   | enum     | In-app event kinds                                |
|                     | [`GrovsError`](#grovserror)                           | class    | Error code and message                            |
|                     | [`GrovsErrorCode`](#grovserrorcode)                   | enum     | Error categories                                  |
|                     | [`GrovsException`](#grovsexception)                   | class    | Thrown by failed tasks                            |
|                     | [`GrovsLogLevel`](#grovsloglevel)                     | enum     | Log verbosity                                     |
|                     | [`GrovsTransactionType`](#grovstransactiontype)       | enum     | Buy, cancel or refund                             |
| **Editor**          | [`GrovsSettings`](#grovssettings)                     | class    | The Project Settings asset                        |

---

## Setup

### SdkVersion

Kind: property

```csharp
public static string SdkVersion { get; }
```

The Unity package version, `"1.0.0"`. Not the native SDK version.

### IsSupportedPlatform

Kind: property

```csharp
public static bool IsSupportedPlatform { get; }
```

`true` on iOS and Android players. `false` in the Editor and on other platforms, and when the native bridge failed to start.

### SetLogLevel

Kind: method

```csharp
public static void SetLogLevel(GrovsLogLevel level)
```

Sets the native log level at runtime. The launch level comes from **Log level** in Project Settings (default `Error`). Android has no warn level, so `Warn` logs at `Info` there.

### ErrorOccurred

Kind: event

```csharp
public static event Action<GrovsError> ErrorOccurred
```

Errors that have no other place to be reported. Failed tasks and callbacks carry their own error.

- **iOS:** every asynchronous native SDK error.
- **Android:** in-app message failures and bridge errors only.

An exception thrown by a handler is logged and doesn't stop the other handlers.

---

## Consent

See [Privacy & Consent](https://docs.grovs.io/docs/sdk/unity/privacy).

### SetEnabled

Kind: method

```csharp
public static void SetEnabled(bool enabled)
```

Turns collection on or off and saves the choice on the device. The saved choice is used on every later launch and wins over **Start enabled**.

- Enabling replays the link that opened the game, if it arrived while disabled.
- While disabled, `HandleUrl` returns `false` and async calls fail with `SdkDisabled`.

### IsEnabled

Kind: property

```csharp
public static bool IsEnabled { get; }
```

`true` when the native SDK has started and is enabled. Always `false` in the Editor.

---

## Deep links

See [Deep linking](https://docs.grovs.io/docs/sdk/unity/deep-linking).

### DeeplinkReceived

Kind: event

```csharp
public static event Action<GrovsDeeplink> DeeplinkReceived
```

Fires for each opened link: universal links and App Links, the URI scheme, deferred deep links, Grovs push taps and `HandleUrl`.

- Links that arrive while there's no subscriber are kept, up to 20 (the oldest is dropped), and delivered in order to the first subscriber.
- An exception thrown by a handler is logged and doesn't stop the other handlers.

### LastDeeplink

Kind: property

```csharp
public static GrovsDeeplink LastDeeplink { get; }
```

The most recent link, or `null`.

### HandleUrl

Kind: method

```csharp
public static bool HandleUrl(string url)
```

Handles a link tapped inside the game. The result arrives in `DeeplinkReceived`.

- Throws `ArgumentNullException` for `null`, and `ArgumentException` when the URL isn't absolute with a scheme and a host.
- Returns `false` while Grovs is disabled.

---

## Links

See [Link creation](https://docs.grovs.io/docs/sdk/unity/link-creation).

### GenerateLinkAsync

Kind: method

```csharp
public static Task<string> GenerateLinkAsync(GenerateLinkOptions options)
```

Creates a smart link and returns its URL. `null` options create a link with no metadata.

- Throws `ArgumentException` when `options.Data` holds a value that isn't JSON-serializable.
- Fails with `LinkGenerationFailed`, `SdkDisabled`, `SdkNotInitialized` or `UnsupportedPlatform`.
- While authentication is retrying, iOS waits and Android fails right away.

### GenerateLink

Kind: method

```csharp
public static void GenerateLink(GenerateLinkOptions options, Action<string, GrovsError> callback)
```

Callback version of [`GenerateLinkAsync`](#generatelinkasync). The callback gets the link, or `null` and the error.

### GetLinkDetailsAsync

Kind: method

```csharp
public static Task<IReadOnlyDictionary<string, object>> GetLinkDetailsAsync(string path)
```

Returns the details the backend has for a link path, for example `"/abc"`. Throws `ArgumentNullException` for `null`. Fails with `LinkDetailsFailed` when there are none.

### GetLinkDetails

Kind: method

```csharp
public static void GetLinkDetails(string path, Action<IReadOnlyDictionary<string, object>, GrovsError> callback)
```

Callback version of [`GetLinkDetailsAsync`](#getlinkdetailsasync).

---

## Users

### SetUserIdentifier

Kind: method

```csharp
public static void SetUserIdentifier(string id)
```

Your ID for the player. `null` clears it.

### SetUserAttributes

Kind: method

```csharp
public static void SetUserAttributes(IDictionary<string, object> attrs)
```

Attributes of the player. Values must be JSON-serializable, otherwise it throws `ArgumentException`. `null` entries are dropped.

---

## Events

See [Events & screen tracking](https://docs.grovs.io/docs/sdk/unity/analytics).

### Track

Kind: method

```csharp
public static void Track(string name, IDictionary<string, object> properties = null, IList<string> tags = null)
```

Tracks a custom event.

- Throws `ArgumentNullException` for a `null` name, and `ArgumentException` for a property value that isn't JSON-serializable.
- Logs a warning, and still sends the event, for an empty or reserved name, properties over 8192 bytes of JSON, more than 20 tags, or a tag over 255 characters.

### TrackScreenView

Kind: method

```csharp
public static void TrackScreenView(string screenName, IDictionary<string, object> properties = null)
```

Tracks a screen view. Throws `ArgumentNullException` for a `null` name. Native automatic screen tracking is off, so this and **Track scenes** are the only sources of screen views.

### SetGlobalTags

Kind: method

```csharp
public static void SetGlobalTags(IList<string> tags)
```

Tags added to every event. `null` clears them.

### SetScreenAliases

Kind: method

```csharp
public static void SetScreenAliases(IDictionary<string, string> aliases)
```

Maps tracked screen names to the names shown in the dashboard, for example `{ "MainMenu", "Home" }`. `null` sends an empty map.

---

## Revenue

See [Revenue](https://docs.grovs.io/docs/sdk/unity/revenue).

### LogInAppPurchaseAsync

Kind: method

```csharp
public static Task<bool> LogInAppPurchaseAsync(string storeTransaction)
```

Logs a store purchase.

| Platform | `storeTransaction`                                                                            | Result                              |
| -------- | --------------------------------------------------------------------------------------------- | ----------------------------------- |
| iOS      | The StoreKit transaction ID, as a decimal string. Anything else fails with `InvalidArgument`. | The native SDK's result             |
| Android  | The Play Billing `Purchase.originalJson`                                                      | `true` once the call is handed over |

Throws `ArgumentException` for an empty or `null` string.

### LogCustomPurchaseAsync

Kind: method

```csharp
public static Task<bool> LogCustomPurchaseAsync(
    GrovsTransactionType type,
    int priceInCents,
    string currency,
    string productId,
    DateTime? date = null)
```

Logs a purchase outside the stores. `date` is the transaction date, `null` for now. Throws `ArgumentNullException` for a `null` currency or product ID. On Android the result is `true` once the call is handed over.

### GrovsUnityIAP

Kind: class

```csharp
public static class GrovsUnityIAP
```

In the `GrovsSDK.IAP` assembly, which compiles only when `com.unity.purchasing` 4.0 or newer is installed. Supports the Apple App Store, the Mac App Store and Google Play.

#### LogPurchaseAsync

Kind: method

```csharp
public static Task<bool> LogPurchaseAsync(Product product)
```

Logs a Unity IAP 4 or 5 `Product` from its receipt. Throws `ArgumentNullException` for `null`. Resolves `false`, with a warning, when the receipt can't be used.

#### LogOrderAsync

Kind: method · Since IAP 5.0

```csharp
public static Task<bool> LogOrderAsync(Order order)
```

Logs a Unity IAP 5 `Order`. Needs `com.unity.purchasing` 5.0 or newer. Throws `ArgumentNullException` for `null`. Resolves `false`, with a warning, when the order has no info or the receipt can't be used. On iOS, call it before confirming a consumable.

---

## Push

See [Push notifications](https://docs.grovs.io/docs/sdk/unity/push-notifications).

### SetPushToken

Kind: method

```csharp
public static void SetPushToken(string token)
```

Only needed when the game gets push tokens itself and Grovs can't see them. Grovs reads the APNs token from Unity on iOS and the FCM token from Firebase on Android.

### IsGrovsNotification

Kind: method

```csharp
public static bool IsGrovsNotification(IDictionary<string, string> data)
```

`true` when Grovs sent the notification with this data. `false` for `null`.

### HandleNotificationOpen

Kind: method

```csharp
public static bool HandleNotificationOpen(IDictionary<string, object> data)
```

Handles a tap on a Grovs notification that reached your code another way. Reports the open and delivers the link to `DeeplinkReceived`. Returns `false` for `null` or when the native SDK hasn't started. Values must be JSON-serializable.

---

## In-app messages

See [In-app messages](https://docs.grovs.io/docs/sdk/unity/in-app-messages).

### InAppMessageEvent

Kind: event

```csharp
public static event Action<InAppMessageEvent> InAppMessageEvent
```

Fires when a message is shown, clicked, dismissed, answered or fails. See [`InAppMessageEvent`](#inappmessageevent-type) for the fields.

### ShouldShowInAppMessage

Kind: property

```csharp
public static Func<string, bool> ShouldShowInAppMessage { get; set; }
```

Called with the campaign ID before a message shows. Return `false` to hold it back. `null` (the default) shows every message.

- Runs synchronously on a native thread: the main thread on iOS, the Android UI thread (not Unity's) on Android. Keep it fast and don't call Unity APIs from it.
- If it throws, the exception is logged and the message shows.

### PauseInAppMessages

Kind: method

```csharp
public static void PauseInAppMessages()
```

Holds messages back. The newest highest priority match waits.

### ResumeInAppMessages

Kind: method

```csharp
public static void ResumeInAppMessages()
```

Lets messages show again, starting with the one that waited, if it still qualifies.

### DiscardInAppMessages

Kind: method

```csharp
public static void DiscardInAppMessages(bool dismissCurrent = false)
```

Drops the waiting message. With `dismissCurrent: true`, also closes the one on screen.

### SetInAppExcludedScreens

Kind: method

```csharp
public static void SetInAppExcludedScreens(IList<string> screens)
```

No message shows on these screens. Names match tracked screen names. `null` clears the list.

### SetInAppDebugLogging

Kind: method

```csharp
public static void SetInAppDebugLogging(bool enabled)
```

Logs each campaign considered for an event and why it was skipped. Set the log level to `Info` to see it.

---

## Types

### GrovsDeeplink

Kind: class

```csharp
public sealed class GrovsDeeplink
{
    public string Link;
    public IReadOnlyDictionary<string, object> Data;
    public GrovsTracking Tracking;
    public bool FromPush;
    public string RawJson;
}
```

| Field      | Description                                                                                         |
| ---------- | --------------------------------------------------------------------------------------------------- |
| `Link`     | The opened link. Can be `null`.                                                                     |
| `Data`     | The link's custom payload. Never `null`. Whole numbers arrive as `long`, other numbers as `double`. |
| `Tracking` | Campaign, source and medium. Can be `null`.                                                         |
| `FromPush` | `true` when the link came from a Grovs push notification.                                           |
| `RawJson`  | The message as the native bridge sent it.                                                           |

### GrovsTracking

Kind: class

```csharp
public sealed class GrovsTracking
{
    public string Campaign;
    public string Source;
    public string Medium;
}
```

### GenerateLinkOptions

Kind: class

```csharp
public sealed class GenerateLinkOptions
{
    public string Title, Subtitle, ImageUrl;
    public IDictionary<string, object> Data;
    public IList<string> Tags;
    public GrovsRedirect IosRedirect, AndroidRedirect, DesktopRedirect;
    public bool? ShowPreviewIos, ShowPreviewAndroid;
    public bool? CopyToClipboardIos, CopyToClipboardAndroid;
    public string TrackingCampaign, TrackingSource, TrackingMedium;
}
```

All fields are optional. `null` fields are left out and use the dashboard or project defaults. See [Options](https://docs.grovs.io/docs/sdk/unity/link-creation#options).

### GrovsRedirect

Kind: class

```csharp
public sealed class GrovsRedirect
{
    public string Url;
    public bool OpenAppIfInstalled = true;
}
```

A redirect without a `Url` is ignored.

### InAppMessageEvent (type)

Kind: class

```csharp
public sealed class InAppMessageEvent
{
    public InAppEventType Type;
    public string CampaignId;
    public string ButtonId;
    public IReadOnlyDictionary<string, object> Payload;
    public string DismissReason;
    public object AnswerValue;
    public string Comment;
    public string FailureMessage;
}
```

| Field            | Description                                                 |
| ---------------- | ----------------------------------------------------------- |
| `Type`           | The event kind                                              |
| `CampaignId`     | The campaign. Can be `null` for `Failed` on iOS.            |
| `ButtonId`       | `Clicked` only. `null` when the message body was tapped.    |
| `Payload`        | `Clicked` with a key-value action                           |
| `DismissReason`  | `close_button`, `backdrop`, `swipe`, `app` or `orientation` |
| `AnswerValue`    | A `long` for stars or a `string` option ID                  |
| `Comment`        | The answer's comment, or `null`                             |
| `FailureMessage` | `Failed` only                                               |

### InAppEventType

Kind: enum

```csharp
public enum InAppEventType { Shown, Clicked, Dismissed, Answered, Failed }
```

### GrovsError

Kind: class

```csharp
public sealed class GrovsError
{
    public GrovsErrorCode Code;
    public string Message;
}
```

`ToString()` returns `"Code: Message"`.

### GrovsErrorCode

Kind: enum

```csharp
public enum GrovsErrorCode
{
    AuthenticationFailed,
    NetworkRequestFailed,
    EventDispatchFailed,
    LinkGenerationFailed,
    InAppDisplayFailed,
    LinkDetailsFailed,
    NotificationsError,
    SdkNotInitialized,
    SdkDisabled,
    InvalidArgument,
    UnsupportedPlatform,
    Unknown
}
```

| Code                   | Meaning                                                                              |
| ---------------------- | ------------------------------------------------------------------------------------ |
| `AuthenticationFailed` | The SDK couldn't authenticate. Check the API key, environment and URI scheme.        |
| `NetworkRequestFailed` | A network request failed.                                                            |
| `EventDispatchFailed`  | An event batch failed to send. The events stay queued.                               |
| `LinkGenerationFailed` | Link generation failed.                                                              |
| `InAppDisplayFailed`   | An in-app message couldn't be shown.                                                 |
| `LinkDetailsFailed`    | Link details couldn't be read.                                                       |
| `NotificationsError`   | Android: a push notification error.                                                  |
| `SdkNotInitialized`    | The native SDK didn't start, for example because the API key is empty.               |
| `SdkDisabled`          | Grovs is disabled. See [`SetEnabled`](#setenabled).                                  |
| `InvalidArgument`      | The native bridge refused an argument, for example a non-numeric iOS transaction ID. |
| `UnsupportedPlatform`  | The Editor or a platform other than iOS and Android.                                 |
| `Unknown`              | Anything else. `Message` has the details.                                            |

### GrovsException

Kind: class

```csharp
public sealed class GrovsException : Exception
{
    public GrovsError Error;
}
```

Thrown when an awaited Grovs task fails. `Message` is the error's message.

### GrovsLogLevel

Kind: enum

```csharp
public enum GrovsLogLevel { Info = 0, Warn = 1, Error = 2 }
```

### GrovsTransactionType

Kind: enum

```csharp
public enum GrovsTransactionType { Buy = 0, Cancel = 1, Refund = 2 }
```

---

## Editor

### GrovsSettings

Kind: class

```csharp
namespace GrovsSDK.Editor
{
    public class GrovsSettings : ScriptableObject
    {
        public const string AssetPath = "Assets/Grovs/GrovsSettings.asset";
        public static GrovsSettings LoadOrCreate();
    }
}
```

The asset behind **Edit → Project Settings → Grovs**. It's read by the build only, never at runtime. Its fields match the [settings table](https://docs.grovs.io/docs/sdk/unity/quick-start#project-settings): `apiKey`, `environment` (`GrovsEnvironment`: `TestForDevelopmentBuilds`, `Production`, `Test`), `baseUrl`, `startEnabled`, `clipboardDomains`, `uriScheme`, `linkDomains`, `pushEnabled`, `androidPushMode` (`GrovsAndroidPushMode`: `Auto`, `FirebaseUnity`, `Standalone`), `iosOwnNotificationDelegate`, `androidSmallIcon`, `googleServicesJsonPath`, `trackScenes` and `logLevel`.

`LoadOrCreate()` returns the asset, creating it at `AssetPath` if it's missing. Use it from build scripts to set values per build, for example the API key from a CI secret. Restore the old values after the build so real keys aren't saved to the asset.

**Grovs → Simulate Deep Link** opens a window that fires `DeeplinkReceived` in Play Mode. See [Testing links in the Editor](https://docs.grovs.io/docs/sdk/unity/deep-linking#testing-links-in-the-editor).
