Created
August 26, 2020 09:04
-
-
Save O4epegb/5838cd14b15daf45dee28f192d78cf34 to your computer and use it in GitHub Desktop.
Telegram oauth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const openTgWindow = (options: { | |
bot_id: string; | |
request_access?: boolean; | |
lang?: string; | |
}, callback) => { | |
let timeoutId = null; | |
const popup_url = | |
'https://oauth.telegram.org/auth?bot_id=' + | |
encodeURIComponent(options.bot_id) + | |
'&origin=' + | |
encodeURIComponent( | |
location.origin || location.protocol + '//' + location.hostname | |
) + | |
(options.request_access | |
? '&request_access=' + encodeURIComponent(options.request_access) | |
: '') + | |
(options.lang ? '&lang=' + encodeURIComponent(options.lang) : ''); | |
const checkClose = (window: Window) => { | |
if (!window || window.closed) { | |
return getAuthData({ bot_id: options.bot_id }, (authData) => { | |
callback(authData); | |
}); | |
} else { | |
timeoutId = setTimeout(() => checkClose(window), 100); | |
} | |
}; | |
const popup = window.open(popup_url); | |
checkClose(popup); | |
window.addEventListener('message', (event) => { | |
let data; | |
if (event.source !== popup) return; | |
try { | |
data = JSON.parse(event.data); | |
} catch (e) { | |
data = {}; | |
} | |
if (data.event == 'auth_result') { | |
clearTimeout(timeoutId); | |
callback(data.result); | |
} | |
}); | |
return popup; | |
}; | |
const getAuthData = (options: { bot_id: string; lang?: string }, callback) => { | |
const xhr = new XMLHttpRequest(); | |
const url = 'https://oauth.telegram.org/auth/get'; | |
xhr.open('POST', url); | |
xhr.setRequestHeader( | |
'Content-Type', | |
'application/x-www-form-urlencoded; charset=UTF-8' | |
); | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState == 4) { | |
if (xhr.responseText) { | |
let result; | |
try { | |
result = JSON.parse(xhr.responseText); | |
} catch (e) { | |
result = {}; | |
} | |
if (result.user) { | |
callback(result.user); | |
} else { | |
callback(false); | |
} | |
} else { | |
callback(false); | |
} | |
} | |
}; | |
xhr.onerror = () => { | |
callback(false); | |
}; | |
xhr.withCredentials = true; | |
xhr.send( | |
'bot_id=' + | |
encodeURIComponent(options.bot_id) + | |
(options.lang ? '&lang=' + encodeURIComponent(options.lang) : '') | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment