Skip to content

Instantly share code, notes, and snippets.

@chuckreynolds
Last active January 8, 2022 02:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save chuckreynolds/1f7103f97534ba9555a8686a5a418650 to your computer and use it in GitHub Desktop.
Postman Pre-Request script to get access token for Twitch OAuth2
/*
* Twitch Helix OAuth2 Postman Pre-Request Script
* @see https://dev.twitch.tv/docs/authentication#registration
* @see https://learning.postman.com/docs/writing-scripts/pre-request-scripts/
*/
const authUrl = 'https://id.twitch.tv/oauth2/token';
const clientId = pm.collectionVariables.get('clientId');
const clientSecret = pm.collectionVariables.get('clientSecret');
const qs = {
'client_id': clientId,
'client_secret': clientSecret,
'grant_type': 'client_credentials',
'scope': ''
};
function param(object) {
let parameters = [];
for (var property in object) {
if (object.hasOwnProperty(property)) {
parameters.push(encodeURI(property + '=' + object[property]));
}
}
return parameters.join('&');
}
const getTokenRequest = {
method: 'POST',
url: `${authUrl}?${param(qs)}`,
header: 'Content-Type:application/json'
};
pm.sendRequest(getTokenRequest, (err, response) => {
const jsonResponse = response.json();
const newAccessToken = jsonResponse.access_token;
pm.collectionVariables.set('access_token', newAccessToken);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment