Skip to content

Unity API Guide

This guide provides complete instructions for integrating MomentPerks (Moments API) into your Unity games and applications. You'll learn how to load...

Overview

This guide provides complete instructions for integrating MomentPerks (Moments API) into your Unity games and applications. You’ll learn how to load personalized offers, display them to users, and track interactions, all with production-ready code examples.

What You’ll Build

By the end of this guide, you’ll have:

  • A working MomentPerks API integration in your Unity project
  • The ability to display personalized offers at key moments
  • Automatic tracking of user interactions and conversions

Prerequisites

Before you begin, ensure you have:

Requirement Details
Unity Version 2019.4 or later
.NET Version .NET Standard 2.0 or .NET 4.x
API Key Obtain from MomentScience dashboard (see Getting Your API Key)

Installation

1: Download

Download the MomentsAPI-Unity folder from the GitHub repository.

2: Import into Unity

  1. Locate the MomentsAPI folder in the downloaded files
  2. Copy the entire MomentsAPI folder into your Unity project’s Assets folder

3: Verify Installation

Confirm the following structure exists in your Unity project:

Assets/
└── MomentsAPI/
    ├── Models/
    │   ├── Offer.cs
    │   ├── OfferBeacons.cs
    │   ├── OfferResponse.cs
    │   └── OfferStyles.cs
    ├── Services/
    │   └── OfferService.cs
    ├── Utils/
    │   └── UserAgentUtil.cs
    ├── Examples/
    │   ├── OfferUIExample.cs
    │   └── ProgrammaticExample.cs
    ├── OfferManager.cs
    ├── README.md
    └── package.json

4: Import TextMeshPro (Optional)

If you plan to use the UI examples, import TextMeshPro:

  1. Go to Window → TextMeshPro → Import TMP Essential Resources
  2. Click Import

Quick Start

Step 1: Create OfferManager GameObject

  1. In your Unity scene, create an empty GameObject
  2. Name it OfferManager
  3. Add the OfferManager component to it

Step 2: Configure in Inspector

Set the following required fields in the Inspector:

Field Value Description
API Key Your API key Obtain from MomentScience dashboard
Development Mode Enabled Enable for testing, make sure to disable in production.
adpxfp test_fingerprint_123 Unique user identifier (fingerprint)
pubUserId test_user_123 Your publisher user ID
placement checkout Where offers are shown in your app

Step 3: Create a Script to Load Offers

Create a new C# script called OfferLoader.cs:

using UnityEngine;
using MomentsAPI;
using MomentsAPI.Models;

public class OfferLoader : MonoBehaviour
{
    [SerializeField] private OfferManager offerManager;

    void Start()
    {
        // Subscribe to offer loading events
        offerManager.OnOffersLoaded.AddListener(OnOffersLoaded);
        offerManager.OnError.AddListener(OnError);
        
        // Request offers from the API
        offerManager.LoadOffers();
    }

    void OnOffersLoaded(OfferResponse response)
    {
        if (response.HasOffers())
        {
            Debug.Log($"✅ Loaded {response.data.offers.Count} offers");
            
            // Access the first offer
            Offer firstOffer = response.data.offers[0];
            Debug.Log($"Title: {firstOffer.title}");
            Debug.Log($"Description: {firstOffer.description}");
        }
        else
        {
            Debug.Log("No offers available");
        }
    }

    void OnError(string error)
    {
        Debug.LogError($"Failed to load offers: {error}");
    }
    
    void OnDestroy()
    {
        if (offerManager == null) return;

        // Clean up event listeners
        offerManager.OnOffersLoaded.RemoveListener(OnOffersLoaded);
        offerManager.OnError.RemoveListener(OnError);
    }
}

Step 4: Attach Script and Test

  1. Create a new empty GameObject (or use an existing one)
  2. Add the OfferLoader script to it
  3. In the Inspector, drag the OfferManager GameObject to the offerManager field
  4. Press Play in Unity
  5. Check the Console for success messages

OfferManager Configuration

OfferManager Component

The OfferManager is the main entry point for the Moments API. It’s a MonoBehaviour that handles:

  • Loading offers from the API
  • Managing offer state
  • Handling user interactions (accept, decline, close)
  • Sending tracking beacons
  • Exposing Unity Events for UI integration

Inspector Configuration

Configure the OfferManager component using the Unity Inspector:

Field Type Required Description
apiKey string Yes Your Moments API key from the dashboard
adpxfp string Yes Unique user identifier (fingerprint)
pubUserId string Yes Your publisher user ID
placement string Yes Placement identifier (e.g., “checkout”, “menu”)
isDevelopmentMode bool No Enable for testing (logs additional debug info)
loyaltyBoost string No Loyalty boost level: "0", "1" or "2"
creative string No Creative parameter: "0" or "1"
campaignId string No Filter offers by specific campaign ID

Programmatic Configuration

You can also configure the OfferManager programmatically:

void Start()
{
    // Set API key
    offerManager.ApiKey = "your_api_key_here";
    
    // Configure optional parameters
    offerManager.loyaltyBoost = "1";
    offerManager.creative = "1";
    offerManager.campaignId = "campaign_123";
    
    // Load offers
    offerManager.LoadOffers();
}

Custom Payload

For advanced use cases, provide a custom payload with additional parameters:

Dictionary<string, string> customPayload = new Dictionary<string, string>
{
    { "ua", UserAgentUtil.GetUserAgent() },
    { "adpx_fp", "unique_fingerprint_12345" },
    { "pub_user_id", "user_12345" },
    { "placement", "main_menu" },
    { "user_level", "5" },
    { "user_currency", "USD" }
};

offerManager.LoadOffersWithCustomPayload(customPayload);

Understanding the Offer Model

An Offer represents a single promotional offer with the following structure:

public class Offer
{
    public string id;                    // Unique offer ID
    public string? title;                // Offer title
    public string? description;          // Offer description
    public string? image;                // Offer image URL
    public string? click_url;            // URL to open when accepted
    public string? cta_yes;              // positive CTA button text
    public string? cta_no;               // negative CTA button text
    public OfferBeacons? beacons;        // Tracking beacons
    public string? pixel;                // Display tracking pixel
    public string? adv_pixel_url;        // Advertiser pixel URL
}
public class OfferBeacons
{
    public string? close; // Beacon URL to fire when the offer is closed.

    public string? no_thanks_click; // Beacon URL to fire when user clicks on negative CTA.
}

UI Implementation

Basic UI Setup

The reusable classes includes a complete UI example at OfferUIExample.cs. This example demonstrates:

  • Loading and displaying offers
  • Handling user interactions
  • Navigating through multiple offers
  • Applying server-driven styles
  • Loading and displaying images
  • Sending tracking beacons

For displaying offers UI you can refer to either DemoScene OR TestOffersScene.

Applying Custom Styles

The Moments API returns style information that you can apply to your UI for consistent branding. Here’s how to apply these styles:

// Note: only few styles are implemented for reference. 
void ApplyStyles(OfferResponse response)
{
    if (response.data?.styles == null) return;
    
    OfferStyles styles = response.data.styles;
    
    // Apply background color
    string bgColor = styles.GetPopupBackground();
    if (ColorUtility.TryParseHtmlString(bgColor, out Color backgroundColor))
    {
        panelImage.color = backgroundColor;
    }
    
    // Apply text color
    string textColor = styles.GetTextColor();
    if (ColorUtility.TryParseHtmlString(textColor, out Color textColorValue))
    {
        titleText.color = textColorValue;
        descriptionText.color = textColorValue;
    }
    
    // Apply button colors
    string yesButtonBg = styles.GetButtonYesBackground();
    if (ColorUtility.TryParseHtmlString(yesButtonBg, out Color yesBgColor))
    {
        acceptButtonImage.color = yesBgColor;
    }
    
    string yesButtonText = styles.GetButtonYesColor();
    if (ColorUtility.TryParseHtmlString(yesButtonText, out Color yesTextColor))
    {
        acceptButtonText.color = yesTextColor;
    }
    
    string noButtonBg = styles.GetButtonNoBackground();
    if (ColorUtility.TryParseHtmlString(noButtonBg, out Color noBgColor))
    {
        declineButtonImage.color = noBgColor;
    }
    
    string noButtonText = styles.GetButtonNoColor();
    if (ColorUtility.TryParseHtmlString(noButtonText, out Color noTextColor))
    {
        declineButtonText.color = noTextColor;
    }
}

Implementing Event Tracking

Proper event tracking ensures accurate analytics and conversion attribution. The reusable classes handles most tracking automatically, but you need to trigger these events at the right time.

Display Tracking

Send display tracking when an offer appears on screen:

private IEnumerator HandleDisplayTrackingCoroutine(Offer offer)
{
    // Send request for pixel
    if (!string.IsNullOrEmpty(offer.pixel))
    {
        yield return _offerService.SendTrackingRequest(offer.pixel);
    }

    // Send request for advertiser pixel
    if (!string.IsNullOrEmpty(offer.adv_pixel_url))
    {
        yield return _offerService.SendTrackingRequest(offer.adv_pixel_url);
    }
}

Close Event Tracking

Track when a user closes the offer panel:

string closeBeacon = offer.beacons?.close;
if (!string.IsNullOrEmpty(closeBeacon))
{
    yield return _offerService.SendTrackingRequest(closeBeacon);
}

Positive CTA Event Tracking

Track when user accept an offer by tapping the positive CTA.

When user taps on positive CTA, you need to open click_url in external/inapp browser before moving to next offer. If the offer is last one and you are closing the offer panel then also send close beacon request.

private IEnumerator HandlePositiveActionCoroutine(Offer offer, int currentIndex, int totalOffers, Action<bool> onComplete)
        {
            // Open the click_url in external browser if available
            if (!string.IsNullOrEmpty(offer.click_url))
            {
                Application.OpenURL(offer.click_url);
            }

            // If this is the last offer, send the close beacon
            if (currentIndex >= totalOffers - 1)
            {
                string closeBeacon = offer.beacons?.close;
                if (!string.IsNullOrEmpty(closeBeacon))
                {
                    yield return _offerService.SendTrackingRequest(closeBeacon);
                }
            }

            // Return whether to move to next offer (true) or close page (false)
            bool showNextOffer = currentIndex < totalOffers - 1;
            onComplete?.Invoke(showNextOffer);
        }

Negative CTA Event Tracking

Track when a user declines an offer by tapping the negative CTA.

When a user taps the negative CTA (e.g., “No Thanks”), you need to send the no_thanks_click tracking request before moving to the next offer. If the declined offer is the last one and you’re closing the offers panel, also send the close beacon request.

private IEnumerator HandleNegativeActionCoroutine(
    Offer offer,
    int currentIndex,
    int totalOffers,
    Action<bool> onComplete
)
{
    // Send "No Thanks" beacon
    string noThanksBeacon = offer.beacons?.no_thanks_click;
    if (!string.IsNullOrEmpty(noThanksBeacon))
    {
        yield return _offerService.SendTrackingRequest(noThanksBeacon);
    }

    // If this is the last offer, send close beacon
    if (currentIndex >= totalOffers - 1)
    {
        string closeBeacon = offer.beacons?.close;
        if (!string.IsNullOrEmpty(closeBeacon))
        {
            yield return _offerService.SendTrackingRequest(closeBeacon);
        }
    }

    // Determine whether to show next offer or close
    bool showNextOffer = currentIndex < totalOffers - 1;
    onComplete?.Invoke(showNextOffer);
}

Testing

Enable development mode for detailed logging during testing:

offerManager.isDevelopmentMode = true;

This enables:

  • Verbose console logging
  • Request/response details
  • Tracking beacon verification

Examples and Demo Projects

UI Example

A complete UI implementation is available at OfferUIExample.cs.

Features demonstrated:

  • Loading and displaying offers
  • Handling user interactions
  • Navigating through multiple offers
  • Applying server-driven styles
  • Loading and displaying images
  • Sending tracking beacons

To use this example:

  1. Open Assets/MomentsAPI/Examples/OfferUIExample.cs
  2. Create UI elements as described in the script comments
  3. Attach the script to a GameObject
  4. Assign UI references in the Inspector
  5. Press Play to test

Programmatic Example

A programmatic implementation is available at ProgrammaticExample.cs.

Features demonstrated:

  • Creating OfferManager at runtime
  • Configuring API settings programmatically
  • Building custom payloads
  • Handling events
  • Simulating user interactions

Demo Application

A complete demo Unity project is available in the MSAPIDemoApp folder.

Demo Scenes

Scene Description
TestStartScene API key input and configuration
TestOffersScene Full offers display with complete UI
DemoScene Pre-configured with demo API key for quick testing

Running the Test Scene

  1. Open the MSAPIDemoApp project in Unity
  2. Open TestStartScene.unity
  3. Press Play
  4. Enter your API key
  5. Explore the implementation

Running the Demo Scene

  1. Open the MSAPIDemoApp project in Unity
  2. Open DemoScene.unity
  3. Press Play (pre-configured API key included)

Next Steps

Ready to deploy? Complete the MomentPerks API Implementation Checklist to verify your integration meets all best practices and requirements.


📢 If you’re running into any issues while going through the integration process, feel free to contact us at help@momentscience.com

Type to search…

↑↓ navigate↵ selectEsc close