Playbooks
Serving MomentPerks in Mobile ...
Unity - MomentPerks API Integration Guide
30 min
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 https //docs momentscience com/getting your api key ) new to momentperks api? the https //docs momentscience com/momentperks api enables you to display personalized offers to users at key moments in your application installation 1 download download the https //github com/adspostx/examples/tree/main/unity/momentsapi unity from the github repository 2 import into unity locate the https //github com/adspostx/examples/tree/feature/unity demoapp update/unity/momentsapi unity/moments/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 folder structure 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 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 https //docs momentscience com/getting your api key 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); docid\ yz38zu4 miummwtnnsg98 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 offer 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 } offerbeacons 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 https //github com/adspostx/examples/blob/feature/unity demoapp update/unity/momentsapi unity/moments/momentsapi/examples/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 https //github com/adspostx/examples/blob/main/unity/momentsapi unity/msapidemoapp/assets/scenes/demoscene unity or https //github com/adspostx/examples/blob/main/unity/momentsapi unity/msapidemoapp/assets/scenes/testoffersscene unity 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 display event tracking 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 close event tracking string closebeacon = offer beacons? close; if (!string isnullorempty(closebeacon)) { yield return offerservice sendtrackingrequest(closebeacon); } decline 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 decline event tracking 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 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 https //github com/adspostx/examples/blob/main/unity/momentsapi unity/moments/momentsapi/examples/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 open https //github com/adspostx/examples/blob/main/unity/momentsapi unity/moments/momentsapi/examples/offeruiexample cs 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 https //github com/adspostx/examples/blob/main/unity/momentsapi unity/moments/momentsapi/examples/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 https //github com/adspostx/examples/tree/main/unity/momentsapi unity/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 https //github com/adspostx/examples/tree/main/unity/momentsapi unity/msapidemoapp project in unity open teststartscene unity press play enter your api key explore the implementation running the demo scene open the https //github com/adspostx/examples/tree/main/unity/momentsapi unity/msapidemoapp project in unity open demoscene unity press play (pre configured api key included) next steps ready to deploy? complete the https //docs momentscience com/momentperks integration 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 mailto\ help\@momentscience com