Moments
Mobile
React Native
27min
overview this guide explains how to integrate the moments api into your react native application it covers setup, fetching offers, implementing the ui, and tracking user interactions follow these steps to integrate momentscience offers into your app with minimal overhead 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 check version requirements ensure your project is using react 18 0 0 or higher and react native 0 73 or higher verify that all dependencies are compatible with these versions plan your implementation identify offer display areas decide whether offers will appear as part of a screen or as full screen modal overlays frequency of display determine if offers should be shown once per session or every time a specific section is accessed getting started install dependency packages to enable api communication and device information retrieval, install the following dependencies axios for making http requests react native device info for accessing device details react native config for managing environment variables via a env file installation command npm install axios\@latest react native device info\@latest react native config\@latest implement android intent filter add the following intent filter to your androidmanifest xml to open offer links in an external browser androidmanifest xml \<queries> \<intent> \<action android\ name="android intent action view" /> \<category android\ name="android intent category browsable" /> \<data android\ scheme="https" /> \</intent> \</queries> fetch offers the moments api provides offer data based on query parameters and payload inputs to retrieve offers, implement a function that calls the moments api with the necessary parameters for complete details on moments api, refer to the moments api documentation https //docs adspostx com/moments api#rqin the function below acts as a wrapper for the moments api, handling query parameters and headers once implemented, you can call the fetchdata function anywhere in your app to retrieve offer data fetch and process offers data / high level function to fetch and process offers this function 1 sets up default query parameters 2 generates unique user identifier 3 makes api request 4 processes and normalizes response 5 handles errors default configuration loyaltyboost '0' creative '0' dev '1' (sandbox mode) @returns {promise\<array>} array of normalized offer objects @throws {error} when no offers are available or api request fails / export const getoffers = async () => { // set up default query parameters const queryparameters = { loyaltyboost '0', creative '0', }; // prepare request payload const payload = { // development mode flag // warning set to '0' in production or just skip it in production dev '1', // generate unique identifier for user tracking adpx fp (await generateuniqueid()) tostring(), }; try { // get api key from environment config const apikey = config api key; // make api request const response = await fetchmomentoffers(apikey, queryparameters, payload); // extract offers array with fallback to empty array const rawoffers = response? data? data? offers ?? \[]; // throw error if no offers received if (rawoffers length === 0) { throw new error('no offers available'); } // normalize and return offers return rawoffers map(offer => normalizeoffer(offer)); } catch (error) { // log error in development if ( dev ) { console log('error while fetching offers ', error); } // propagate error for upstream handling throw error; } }; moments api wrapper function / makes a direct api call to fetch offers @param {string} apikey authentication key for api access @param {object} queryparameters url query parameters @param {string} \[queryparameters loyaltyboost] loyalty boost parameter @param {string} \[queryparameters creative] creative parameter @param {string} \[queryparameters api key] added automatically from apikey @param {object} payload request body payload @param {string} \[payload ua] user agent string @param {string} \[payload dev] development mode flag @param {string} \[payload adpx fp] unique user identifier @returns {promise\<object>} api response object @throws {error} when api request fails / export const fetchmomentoffers = async ( apikey, queryparameters = {}, payload = {}, ) => { try { // fetch or use provided user agent const useragent = payload ua ?? (await getuseragent()); // set up request headers const headers = { 'content type' 'application/json', 'accept' 'application/json', 'user agent' useragent, }; // process query parameters const allqueryparameters = { api key apikey, queryparameters, }; // remove null/undefined values from query parameters const filteredqueryparameters = object fromentries( object entries(allqueryparameters) filter( (\[key, value]) => value !== null && value !== undefined, ), ); // remove null/undefined values from payload const filteredpayload = object fromentries( object entries(payload) filter( (\[key, value]) => value !== null && value !== undefined, ), ); // build query string for url const querystring = new urlsearchparams(filteredqueryparameters) tostring(); // construct complete api url const apiurl = `${config api base url}/offers json${ querystring ? `?${querystring}` '' }`; // execute api request const response = await axios post(apiurl, filteredpayload, {headers}); return response; } catch (error) { // enhanced error logging in development if ( dev ) { console log('error in fetchmomentoffers ', error); console log( 'error details ', error response || error request || error message, ); } // propagate error for upstream handling throw error; } }; refer to offersservice js for an api call demonstration and offermodel js for offers related details implement ui and event beacons after retrieving the offer data, the next step is to develop the user interface (ui) and integrate event beacons to track user interactions this section covers designing the offer display ui implementing navigation between offers tracking user engagement with event beacons embed offer ui this example features a modal, but you can implement any ui format that fits your application build the offer container ui the offer container ui is responsible for displaying multiple offers in a sequence it includes navigation buttons allow users to move between offers close button closes the offer container offer display area renders the current offer this component maintains the state of the current offer and handles user interactions such as button clicks and event beacon tracking define the offercontainerview component the offercontainerview component manages the state of offers and user interactions prop description offers an array of offer objects containing title, description, image, and cta buttons oncloseoffercta callback function triggered when the offercontainerview is closed it receives \ currentofferindex index of the displayed offer \ shouldfirepixel a boolean indicating whether to call firepixel() (see supporting functions https //docs momentscience com/react native#5whvj for details ) handle the close event the oncloseoffercta function is triggered when the user closes the offercontainerview the user taps the negative cta on the last offer it sends a request to the url defined in beacons? close before closing the view for more details on event tracking, refer to the "supporting functions" https //docs momentscience com/react native#5whvj section handling the close event code example import {firepixel} from ' /utils/util'; / @type {\[array|null, function]} offers data and setter / const \[offers, setoffers] = usestate(null); / @type {\[boolean, function]} offer closed state and setter / const \[isofferclosed, setofferclosed] = usestate(false); const handlecloseoffer = usecallback( (currentindex, shouldfirepixel) => { if ( dev ) { console log('\[momentscienceapidemo] close button tapped'); } // fire tracking pixel if required and available if (shouldfirepixel && offers && offers\[currentindex]? beacons? close) { firepixel(offers\[currentindex] beacons close); } setofferclosed(true); }, \[offers], ); for more details refer to useoffercontainer js , offercontainerview\ jsm , util js implement offer ui each individual offer is displayed using the offerview component this component includes an image, title, description, and two cta buttons define the offerview component prop description title the offer title imageurl the url of the offer image description a detailed description of the offer clickurl the url to open when either the offer image or the positive cta is tapped positivecta text for the positive cta button onimagecta a callback function triggered when the offer image is tapped this function fetches the clickurl and opens it in an external browser using the openurl function onpositivecta a callback function invoked when the positive cta is tapped it performs two actions β’ opens the url stored in click url in an external browser β’ advances to the next offer by invoking gotonextoffer() negativecta the text label for the negative call to action button, onnegativecta a callback function executed when the negative cta is tapped it sends a request using the url specified in beacons? no thanks click and then advances to the next offer by calling gotonextoffer() handling offer interactions code {currentoffer && ( \<offerview title={currentoffer title} description={currentoffer description} imageurl={currentoffer image} clickurl={currentoffer click url} onimagecta={handleimagecta} positivecta={currentoffer cta yes} onpositivecta={handlepositivecta} negativecta={currentoffer cta no} onnegativecta={handlenegativecta} /> )} for more details refer to offerview\ js , useoffercontainer js , useoffers js , offermodel js supporting functions device information functions get device user agent when calling our api, it's important to include the user agent parameter here's how you can retrieve its value for the device using the react native device info package fetching 'user agent' parameter import deviceinfo from 'react native device info'; export const getuseragent = async () => { return await deviceinfo getuseragent(); }; for more details refer to util js generating user identifiers to ensure effective tracking and offer management, the api requires a unique identifier for each user this identifier is passed as the adpx fp parameter in the fetch offers api request momentscience uses adpx fp to control the frequency of offer displays for a user prevent the same offer from appearing again when a user opts out the following function retrieves a device specific unique identifier using the react native device info package generating user identifiers import deviceinfo from 'react native device info'; import { platform } from 'react native'; export const generateuniqueid = () => { return platform select({ ios deviceinfo getuniqueid(), // uses idfv for ios android deviceinfo getandroidid(), // uses androidid for android default 'unknown', }); }; for ios uses getuniqueid() , which returns the identifier for vendors (idfv) for android uses getandroidid() , which retrieves the android id for other platforms returns " unknown " as a fallback this unique id should be passed as the adpx fp parameter in the fetch offers api request to maintain consistent tracking across sessions for more details refer to util js event tracking functions firepixel purpose the firepixel function is responsible for sending tracking requests (pixels) under specific conditions to log user interactions it sends http requests to predefined beacon urls when offercontainerview is closed sends a request to beacons close an offer is displayed sends a request to pixel negative cta is tapped sends a request to beacons no thanks click firepixel function import axios from 'axios'; import {linking} from 'react native'; import deviceinfo from 'react native device info'; export const firepixel = url => { if (url) { if ( dev ) { console log('\[momentscienceapidemo] inside fire pixel'); } axios get(url) then(response => { if ( dev ) { console log('\[momentscienceapidemo] fire pixel success ', response data); } }) catch(error => { console error('fire pixel error ', error); }); } }; openurl purpose opens a specified url in an external browser this is used when the user taps the offer image or a positive cta usage call openurl(url) with the target url the function first checks if the url can be opened and then launches it in the deviceβs browser openurl function import axios from 'axios'; import {linking} from 'react native'; import deviceinfo from 'react native device info'; export const openurl = async url => { if (url) { const supported = await linking canopenurl(url); if (supported) { await linking openurl(url); } else { if ( dev ) { console log(`\[momentscienceapidemo] cannot open url ${url}`); } } } }; for more details refer to util js reloading offers once the user closes the offer container ui, the next time you want to show offers, you need to reload them you can reset the offer state and fetch new data to reload offers for more details refer to useoffers js reload offers const reloadoffers = usecallback(() => { setofferclosed(false); // reset closed state setoffers(null); // clear existing offers setisloading(true); // show loading immediately fetchoffers(); // fetch new offers }, \[fetchoffers]); explore the momentscience example on github download and run it locally to see it in action π’ if you're running into any issues while going through the integration process, feel free to contact us at help\@momentscience com