clickzin_tracking_react_native
Version:
Clickzin Tracking SDK
333 lines (285 loc) • 9.29 kB
JavaScript
import { NativeModules } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
const { ClickzinInstallReferrerModule } = NativeModules;
const _API_URL = "https://api.clickzin.com/users/application-urls";
/**
* Log message in console
* @param {*} message
*/
const logInfo = (message) => {
console.log(`[Clickzin] ${message}`);
};
/**
* Log error in console
* @param {*} message
*/
const logError = (message) => {
console.error(`[Clickzin] ${message}`);
};
/**
* Save preferences
* @param {*} key
* @param {*} value
*/
const saveToPreference = async (key, value) => {
try {
logInfo(`Save To Preference : ${key} and value : ${value}`);
await AsyncStorage.setItem(key, value);
} catch (error) {
logError(`Failed to store in references key : ${key} and value : ${value}`);
throw new Error(
`Failed to store in references key : ${key} and value : ${value}`
);
}
};
/**
* Get Preferences
* @param {*} key
* @returns
*/
const getFromPreference = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
logInfo(`Get from Preference : ${key} and value : ${value}`);
return value;
} catch (error) {
logError(`Failed to retrieve ${key} from preference`);
throw new Error(`Failed to retrieve ${key} from preference`);
}
};
/**
* Process conversion my making rest api
* @param {*} url
* @param {*} utmParams
* @param {*} event
*/
const _processConversion = async (
url,
utmParams,
event,
onConversionTracked
) => {
try {
logInfo(
`_processConversion url : ${url} and utmParams : ${utmParams} & event : ${event}`
);
const finalUrl = url
.replace("#UID#", utmParams?.utm_uid)
.replace("#EVENT#", event);
logInfo(`_processConversion finalUrl : ${finalUrl}`);
// Configure the options
const options = {
method: "GET",
};
fetch(finalUrl, options)
.then(async (response) => {
logInfo(`Process conversion response : ${response}`);
const result = await response.text();
logInfo(`Process conversion result : ${result}`);
if (result === "success" || result === "Success") {
//5. Store the event as true
await saveToPreference(event, "true");
onConversionTracked && onConversionTracked();
}
})
.catch((err) => logError(`Process conversion error : ${err}`));
} catch (error) {
logError(`_processConversion error : ${error}`);
throw new Error(error);
}
};
const getInstallReferrerValues = () => {
logInfo(`getInstallReferrerValues `);
return new Promise((resolve, reject) => {
logInfo(`getInstallReferrerValues inside promise`);
ClickzinInstallReferrerModule.getInstallReferrer(
(error, referrerUrl, clickTimestamp, installTimestamp) => {
logInfo(
`getInstallReferrerValues error : ${error} , referrerUrl:${referrerUrl} clickTimestamp : ${clickTimestamp}, installTimestamp:${installTimestamp}`
);
if (error) {
reject(error);
} else {
resolve({ referrerUrl, clickTimestamp, installTimestamp });
}
}
);
});
};
/**
* get install referrer values
* @returns
*/
const getInstallReferrer = async () => {
try {
logInfo(`getInstallReferrer`);
//1. Check the install referrer is stored in preferences or not.
const valueFromPreference = await getFromPreference("referrer");
logInfo(`getInstallReferrer valueFromPreference : ${valueFromPreference}`);
//2. If already stored, return the value
if (valueFromPreference && valueFromPreference != undefined) {
return JSON.parse(valueFromPreference);
}
//3. Get the values from install referrer
const { referrerUrl, clickTimestamp, installTimestamp } =
await getInstallReferrerValues();
// const [installReferrer, referrerClickTimestamp, installBeginTimestamp] =
// result.split(",");
logInfo(`getInstallReferrer referrerUrl : ${referrerUrl}`);
logInfo(`getInstallReferrer clickTimestamp : ${clickTimestamp}`);
logInfo(`getInstallReferrer installTimestamp : ${installTimestamp}`);
//4. Prepare the data
const value = {
installReferrer: referrerUrl,
referrerClickTimestamp: Number(clickTimestamp),
installBeginTimestamp: Number(installTimestamp),
};
logInfo(`getInstallReferrer value : ${JSON.stringify(value)}`);
//5. Store the value in preference for future purpose
await saveToPreference("referrer", JSON.stringify(value));
return value;
} catch (error) {
logError(`getInstallReferrer error : ${error}`);
throw new Error(error);
}
};
const parseReferrer = (installReferrer) => {
const referrerParams = {};
const pairs = installReferrer.split("&");
pairs.forEach((pair) => {
const [key, value] = pair.split("=");
logInfo(
`parseReferrer referrerParams => ${decodeURIComponent(
key
)}:${decodeURIComponent(value || "")}`
);
referrerParams[decodeURIComponent(key)] = decodeURIComponent(value || "");
});
return referrerParams;
};
/**
* Track install
* @param { } apiKey
* @returns
*/
const trackInstall = async (apiKey, onConversionTracked) => {
try {
logInfo(`trackInstall`);
const valueFromPreference = await getFromPreference("initial_event");
logInfo(`trackInstall valueFromPreference : ${valueFromPreference}`);
if (valueFromPreference && valueFromPreference === "true") {
//0. Already initial_event is recorded.
logInfo(`trackInstall is already recorded`);
return;
}
//1. Get the install referrer data
const referrerData = await getInstallReferrer();
//2. This will include the parsed key-value pairs from the referrer string
const parsed = parseReferrer(referrerData.installReferrer);
logInfo(`trackInstall referrerParams utm_medium : ${parsed?.utm_medium}`);
logInfo(`trackInstall referrerParams utm_source : ${parsed?.utm_source}`);
//3. Check if source is from clickzin
if (!parsed?.utm_source?.includes("clickzin")) {
logInfo(" Only Clickzin source will be tracked");
return;
}
//3. Check if source is from clickzin
if (!parsed?.utm_uid) {
logInfo("UID values are must for tracking. ");
return;
}
//4. Prepare the options
const options = {
method: "GET",
headers: {
"X-API-KEY": `${apiKey}`,
},
};
logInfo(`trackInstall apiKey : ${apiKey} & _API_URL : ${_API_URL}`);
//5 Get the application api url to process the postback
fetch(_API_URL, options)
.then((response) => response.json())
.then((response) => {
//6. Process the conversion
logInfo(
`Get the application api url to process the postback response : ${response}`
);
if (response && response?.applicationPostBackUrl) {
_processConversion(
response.applicationPostBackUrl,
parsed,
"initial_event",
onConversionTracked
);
}
})
.catch((err) => logError(err));
} catch (error) {
logInfo(`trackInstall error : ${error}`);
throw new Error(error);
}
};
/**
* Track event
* @param {*} apiKey
* @param {*} event
* @returns
*/
const trackEvent = async (apiKey, event, onConversionTracked) => {
try {
logInfo(`trackEvent ${event}`);
const valueFromPreference = await getFromPreference(event);
logInfo(`trackEvent valueFromPreference : ${valueFromPreference}`);
if (valueFromPreference && valueFromPreference === "true") {
//0. Already initial_event is recorded.
logInfo(`trackEvent is already recorded`);
return;
}
//1. Get the install referrer data
const referrerData = await getInstallReferrer();
//2. This will include the parsed key-value pairs from the referrer string
const parsed = parseReferrer(referrerData.installReferrer);
logInfo(`trackEvent referrerParams utm_medium : ${parsed?.utm_medium}`);
logInfo(`trackEvent referrerParams utm_source : ${parsed?.utm_source}`);
//3. Check if source is from clickzin
if (!parsed?.utm_source?.includes("clickzin")) {
logInfo(" Only Clickzin source will be tracked");
return;
}
//3. Check if source is from clickzin
if (!parsed?.utm_uid) {
logInfo("UID values are must for tracking. ");
return;
}
//4. Prepare the options
const options = {
method: "GET",
headers: {
"X-API-KEY": `${apiKey}`,
},
};
//5 Get the application api url to process the postback
fetch(_API_URL, options)
.then((response) => response.json())
.then((response) => {
//6. Process the conversion
logInfo(`trackEvent response : ${response}`);
if (response && response?.applicationPostBackUrl) {
_processConversion(
response.applicationPostBackUrl,
parsed,
event,
onConversionTracked
);
}
})
.catch((err) => console.error(err));
} catch (error) {
logError(`trackEvent error : ${error}`);
throw new Error(error);
}
};
export default {
trackInstall,
trackEvent,
};