Postman Pre-Request script to get access token for Twitch OAuth2
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
/* | |
* 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