Unity - MomentPerks API Integration Guide
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) |
New to MomentPerks API? The MomentPerks API enables you to display personalized offers to users at key moments in your application.
Installation
1: Download
Download the MomentsAPI-Unity folder from the GitHub repository.
2: Import into Unity
- Locate the MomentsAPI folder in the downloaded files
- 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.json4: Import TextMeshPro (Optional)
If you plan to use the UI examples, import TextMeshPro:
- Go to Window โ TextMeshPro โ Import TMP Essential Resources
- Click Import
Installation complete! You're ready to configure.
Quick Start
Step 1: Create OfferManager GameObject
- In your Unity scene, create an empty GameObject
- Name it OfferManager
- 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
- Create a new empty GameObject (or use an existing one)
- Add the OfferLoader script to it
- In the Inspector, drag the OfferManager GameObject to the offerManager field
- Press Play in Unity
- Check the Console for success messages
Expected output: You should see a message like "โ Loaded 1 offers" followed by the offer title and description.
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);๏ปฟPayload values Custom payloads allow you to pass additional context to the Moments API for more targeted offer selection.
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
}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);
}
}See the full implemntation for SendTrackingRequest()๏ปฟ
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
Remember to disable development mode before releasing to production to avoid unnecessary logging overhead.
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:
- Create UI elements as described in the script comments
- Attach the script to a GameObject
- Assign UI references in the Inspector
- 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
- Open the MSAPIDemoApp project in Unity
- Open TestStartScene.unity
- Press Play
- Enter your API key
- Explore the implementation
Running the Demo Scene
- Open the MSAPIDemoApp project in Unity
- Open DemoScene.unity
- 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 [email protected]๏ปฟ