Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<script runat="server">
Platform.Load("core", "1");
var client_id = "xxxxx", //add the client id from the installed package
client_secret = "xxxxxx", //add the client secret from the installed package
subdomain = "xxxxx", //add the 28 character subdomain (starts with mc....)
redirect_uri = "xxxxx"; //add the url of the CloudPage that hosts your app
var auth = true;
var authToken = Platform.Request.GetCookieValue("authToken");
if (authToken == null) {
var authCode = Request.GetQueryStringParameter("code");
if (authCode == null) {
Platform.Response.Redirect('https://' + subdomain + '.auth.marketingcloudapis.com/v2/authorize?response_type=code&client_id=' + client_id + '&redirect_uri=' + redirect_uri);
} else {
var url = 'https://' + subdomain + '.auth.marketingcloudapis.com/v2/token'
var contentType = "application/json";
var payload = {
"grant_type": "authorization_code",
"code": authCode,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri
};
try {
var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
if (accessTokenRequest.StatusCode == 200) {
var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response[0]);
var accessToken = tokenResponse.accessToken;
Platform.Response.SetCookie("authToken", accessToken);
auth = true;
}
} catch (error) {
auth = false;
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment