Skip to content

Instantly share code, notes, and snippets.

@zuzannamj
Last active October 7, 2021 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zuzannamj/cd60eb0e4c3e76a57fa021e2d3c17a8f to your computer and use it in GitHub Desktop.
Save zuzannamj/cd60eb0e4c3e76a57fa021e2d3c17a8f to your computer and use it in GitHub Desktop.
<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....xxxx)
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