Playbooks
Serving Moments in Mobile Apps
React Native - Moments API Integration Guide
16 min
the moments api docid\ duaxqa4vbbpvihg4cqaac enables you to integrate dynamic, personalized offer experiences directly into your react native application this guide walks you through how to fetch offers, build the ui to display them, and track user interactions using event beacons by the end of this guide, youβll be able to configure your project for moments api access fetch offers using the provided api render offers using custom react native components track and report user engagement events such as impressions, dismissals, and clicks to explore a working example, see the momentscience react native demo on github prerequisites before diving into the integration process, there are a few preliminary steps you need to take obtain an api key before you start the integration, you must acquire a unique api key follow the instructions provided here to obtain your key verify supported versions ensure your project dependencies meet these requirements react native 0 73 or higher react 18 0 0 or higher install required packages run the following command in your project directory to install the necessary dependencies npm install axios react native config react native device info axios for making http requests react native device info for accessing device details react native config for accessing environment variables via a env file (optional) add android internet permission in your android/app/src/main/androidmanifest xml , add the following line to allow network requests \<uses permission android\ name="android permission internet" /> add android manifest queries block for android 11 and above, add the following \<queries> block outside the \<application> tag in your androidmanifest xml to allow opening offer urls in an external browser \<queries> \<intent> \<action android\ name="android intent action view" /> \<category android\ name="android intent category browsable" /> \<data android\ scheme="https" /> \</intent> \</queries> integration steps the moments api docid\ duaxqa4vbbpvihg4cqaac delivers personalized offer data based on a set of query parameters and request payload values in this section, youβll implement a utility function to retrieve and normalize offers for use in your ui for complete details on moments api, refer to the moments api documentation https //docs adspostx com/moments api#rqin step 1 fetch offers to retrieve personalized offers from the moments api, make a post request to the /offers json endpoint fetchmomentoffers function // api base url=https //api adspostx com/native/v4 const fetchmomentoffers = async ( apikey, queryparameters = {}, payload = {}, ) => { try { const useragent = payload ua ?? (await getuseragent()); const headers = { 'content type' 'application/json', accept 'application/json', 'user agent' useragent, }; const allqueryparameters = { api key apikey, queryparameters, }; const filteredqueryparameters = object fromentries( object entries(allqueryparameters) filter((\[, v]) => v != null) ); const filteredpayload = object fromentries( object entries(payload) filter((\[, v]) => v != null) ); const querystring = new urlsearchparams(filteredqueryparameters) tostring(); const apiurl = `${config api base url}/offers json${querystring ? `?${querystring}` ''}`; const response = await axios post(apiurl, filteredpayload, { headers }); return response; } catch (error) { logger log('\[fetchmomentoffers] error ', error); logger log('\[fetchmomentoffers] details ', error response || error request || error message); throw error; } }; payload example const payload = { adpx fp '\<unique value>', pub user id '\<unique value>', placement 'checkout', ua '\<user agent value>', }; request parameters name type description apikey string your momentscience api key required for authentication queryparameters object optional url query parameters such as loyaltyboost , creative , campaignid or any custom key supported by your api integration payload object request body containing user specific data (e g ua, adpx fp) common payload fields field type description adpx fp string unique user identifier pub user id string a unique, non pii identifier for the end user placement string an attribute that represents the specific page, section, or location where the offer unit was triggered dev string set to "1" to enable test mode ua string the user agent string returns a successful response returns a json object containing an array of offers metadata such as tracking beacons, creative assets, and eligibility flags optional styling rules see offersservice js , useoffers js , and offermodel js in the demo app for examples of how to request, consume, and structure offer data step 2 build the offer ui after retrieving offer data, the next step is to design a user interface that presents the offers and captures user actions such as claiming or dismissing them the ui components shown below are taken from our demo app and serve as reference implementations only you are free to build your own components based on your appβs design system and platform conventions for a detailed explanation of how each field in the offer object is used refer to the offer anatomy docid\ t8o0a 3bctma448n5pyhw this guide will help you understand how to map api fields to ui components and apply dynamic styling correctly offer container ui use the offercontainerview to manage and display a sequence of offers this component handles navigation, dynamic styling, and user interactions \<offercontainerview offers={offers} oncloseoffercta={handleofferclose} apistyles={apistyles} /> props property type description offers array list of offer objects retrieved from the api oncloseoffercta function callback triggered when the offer container is closed receives two parameters currentindex and shouldfirepixel apistyles object ui styles returned from the api for dynamic theming see offercontainerview\ js https //github com/adspostx/examples/blob/main/react native/momentsapidemoapp/src/components/offercontainerview\ js in the demo app for a working implementation individual offer ui use the offerview component to render a single offer and handles user interactions, including tapping the offer image clicking cta buttons triggering pixel events \<offerview title={currentoffer title} // offer headline description={currentoffer description} // offer description imageurl={currentoffer image} // url of the offer creative (image) clickurl={currentoffer click url} // url to open on image or positive cta tap onimagecta={handleimagecta} //called when the offer image is tapped positivecta={currentoffer cta yes} // label for the primary cta button onpositivecta={handlepositivecta} // called when the primary cta is tapped negativecta={currentoffer cta no} // label for the secondary cta button onnegativecta={handlenegativecta} // called when the secondary cta is tapped apistyles={apistyles? offertext} // optional styling applied to text or cta components /> see offerview\ js and useoffers js in the demo app for a working implementation step 3 track user interactions to measure user engagement and support advertiser attribution, fire tracking beacons (pixel urls) at key moments in the user journey the fireofferpixel utility sends http get requests to tracking urls provided in the offer metadata fireofferpixel const fireofferpixel = async (url) => { if (!url) return; try { logger log('inside fire pixel ', url); const response = await axios get(url); logger log('fire pixel success ', response data); } catch (error) { logger log('fire pixel error ', error); } }; when to fire beacons use fireofferpixel at the following points in the offer flow when the offer is displayed fire both pixel and adv pixel url if they exist fireofferpixel(offers\[currentofferindex]? pixel); fireofferpixel(offers\[currentofferindex]? adv pixel url); when the user taps βno thanksβ fire the no thanks click beacon if available fireofferpixel(offers\[currentindex] beacons? no thanks click); when the offer container is closed fire the close beacon to indicate the user exited the offer sequence fireofferpixel(offers\[currentindex] beacons? close see useoffercontainer js and useoffers js in the demo app for a working implementation next steps we recommend that you go through the moments api implementation checklist to verify your integration completing this checklist ensures that all best practices and requirements are met for a successful moments api deployment π’ if you're running into any issues while going through the integration process, feel free to contact us at help\@momentscience com