0

According to this https://ampscript.xyz/tips-and-tricks/how-to-create-store-use-rest-api-tokens-in-sfmc/. It explains that "There is no way to automatically refresh the token when it expires, which means that if we use the same token for about 20 minutes, our requests will start to return the error 401." I use the "Full code" in the article to regenerate the token. Unfortunately, I always get error 401.

The sample token that I get: n4Iu4WRSeDEPjkiged6mQg1ddr3dZnPVhiYTukZF1yGRPNUfA06vitpxxxxxxxxx

This is the reference code that I use (Final Code from the link):

<script runat='server'>

    Platform.Load('core', '1');

    var config = {
        endpoint: "https://{{ YOUR DOMAIN }}.auth.marketingcloudapis.com/v2/token",
        credentials: {
            "{{ BU ID }}": {
                "grant_type": "client_credentials",
                "client_id": "{{ CLIENT ID }}",
                "client_secret": "{{ CLIENT SECRET }}"
            }
        },
        storage: {
            de: "REST_Tokens",
            name: "DEMO"
        },
        bu: Platform.Function.AuthenticatedMemberID(),
        localDate: DateTime.SystemDateToLocalDate(Now())
    }

    try {

        var auth = retrieveToken();

        Write(Stringify(auth));

    } catch(error) {
        
        Write(Stringify(error));
        
    }

    function requestToken() {

        var request = HTTP.Post(config.endpoint, "application/json", Stringify(config.credentials[config.bu]));

        if (request.StatusCode == 200) {

            var result = Platform.Function.ParseJSON(request.Response[0]);

            var parsedDate = new Date(config.localDate);

            var expirationDate = new Date(parsedDate.getTime() + (result.expires_in * 1000));

            return {
                "token": result.access_token,
                "url": result.rest_instance_url,
                "expires": expirationDate
            }

        } else {
            
            throw "Couldn't request the token. Status: " + request.StatusCode;
        
        }
    }

    function retrieveToken() {

        var request = Platform.Function.LookupRows(config.storage.de, "Name", config.storage.name);

        var result = request[0];

        if(result != null && (new Date(config.localDate) < new Date(result.ExpirationDate))) {

            return {
                "token": decryptSymmetric(result.access_token),
                "url": decryptSymmetric(result.rest_instance_url),
                "expires": result.ExpirationDate
            }

        } else {

            var result = requestToken();

            var upsert = storeToken(result);

            if(upsert > 0) {
                
                return result;
                
            } else {
                
                throw "Token not saved"
                
            }
        }
    }

    function storeToken(result) {

        var rows = Platform.Function.UpsertData(
            config.storage.de,
            ["Name"], [config.storage.name],
            ["access_token", "rest_instance_url", "ExpirationDate"],
            [encryptSymmetric(result.token), encryptSymmetric(result.url), result.expires]
        );

        if(rows > 0) {
            
            return rows; 
            
        } else {
            
            throw "Token storage failed"
            
        }
    }
    
    function decryptSymmetric(str) {

        Variable.SetValue("@ToDecrypt", str)

        var scr = "";
            scr += "\%\%[";
            scr += "SET @Decrypted = DecryptSymmetric(@ToDecrypt, 'AES', 'pwd', @null, 'slt', @null, 'vec', @null)";
            scr += "Output(Concat(@Decrypted))";
            scr += "]\%\%";

        return Platform.Function.TreatAsContent(scr);
    }

    function encryptSymmetric(str) {

        Variable.SetValue("@ToEncrypt", str)

        var scr = "";
            scr += "\%\%[";
            scr += "SET @Encrypted = EncryptSymmetric(@ToEncrypt, 'AES', 'pwd', @null, 'slt', @null, 'vec', @null)";
            scr += "Output(Concat(@Encrypted))";
            scr += "]\%\%";

        return Platform.Function.TreatAsContent(scr);
    }
</script>
3
  • 1
    Please edit your question and provide a Minimal, Reproducible Example
    – identigral
    Sep 12 at 16:03
  • I’m guessing the issue is with scope and the call you are making
    – EazyE
    Sep 12 at 20:33
  • We cannot work off the example link you showed for sample content, as that works. So without being able to see what you implemented, we cannot find the difference and assist. Sep 13 at 12:58