Skip to content

Instantly share code, notes, and snippets.

@Ppang0405
Created November 14, 2022 18:31
Show Gist options
  • Save Ppang0405/52b093c49d9f7f43ff329c4d99b94307 to your computer and use it in GitHub Desktop.
Save Ppang0405/52b093c49d9f7f43ff329c4d99b94307 to your computer and use it in GitHub Desktop.
interface AnalyticsPayload {
username: string;
lastname: string;
firstname: string;
location: string;
}
const getIpAddress = async () => {
try {
const response = await fetch('https://api.ipify.org');
if (response.ok) {
let jsonResponse = await response.text();
// console.log(jsonResponse);
return jsonResponse;
} else {
console.log('HTTP-Error: ' + response.status);
return '';
}
} catch (error) {
return '';
}
};
const getLocation = async (ipAddress: string) => {
try {
const response = await fetch('https://iplocation.com/', {
'headers': {
'accept': '*/*',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8,vi;q=0.7',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'sec-ch-ua': '"Chromium";v="106", "Not;A=Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'sec-gpc': '1',
'x-requested-with': 'XMLHttpRequest'
},
'referrer': 'https://iplocation.com/',
'referrerPolicy': 'strict-origin-when-cross-origin',
'body': `ip=${ipAddress}`,
'method': 'POST',
'mode': 'cors',
'credentials': 'omit'
});
if (response.ok) {
let jsonResponse = await response.json();
// {
// "city": "Singapore",
// "company": "GSL Networks Pty",
// "continent_code": "AS",
// "country_code": "SG",
// "country_name": "Singapore",
// "found": 1,
// "ip": "86.48.11.107",
// "ip_header": "Your IP address",
// "isp": "GSL Networks Pty",
// "lat": 1.3036,
// "lng": 103.8554,
// "metro_code": null,
// "postal_code": "18",
// "region": null,
// "region_name": null,
// "time_zone": "Asia/Singapore"
// }
// console.log(jsonResponse.city);
return jsonResponse?.city;
} else {
console.log('HTTP-Error: ' + response.status);
return '';
}
} catch (error) {
return '';
}
};
export const getAnalyticsPayload = async (): Promise<AnalyticsPayload> => {
const {username, firstName, lastName} = store.getState().auth;
const location = await getLocation(await getIpAddress());
return {
username,
firstname: firstName,
lastname: lastName,
location,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment