0

I would like the get the External Key of the Data Extension related to the Journey Builder. From this step, I need to use the REST API integration and WSProxy. Then, to call the REST API, I need to use the token, right?

The sample token that I got: n4Iu4WRSeDEPjkiged6mQg1ddr3dZnPVhiYTukZF1yGRPNUfA06vitpxxxxxxxxxxxxx

Unfortunately, I always get error 401 every time I use such token even I just refresh the token.

I have followed the steps from this link to get token https://ampscript.xyz/tips-and-tricks/how-to-create-store-use-rest-api-tokens-in-sfmc/

I first create the Data Extension named Rest_Tokens enter image description here

Second, I create the encryption keys enter image description here enter image description here enter image description here

Then, i use this code from the given link to ask for the token.

<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
  • Two things. 1. Are you putting this token into the 'Authorization Header' along with 'Bearer '? eg Bearer 123212131231 because this is required in order to authorize, just the token alone will fail. 2. Can you share what is returned, does the return of the token fail or does that work and just the second call is failing? Commented Sep 18, 2021 at 16:29
  • @Gortonington 1. I did put the token into the 'Authorization Header' along with 'Bearer'. May I know where and how to put it, please? I've googled it, but I did not find one that works for me. 2. The given code gives me the token (sample token that I got: n4Iu4WRSeDEPjkiged6mQg1ddr3dZnPVhiYTukZF1yGRPNUfA06vitpxxxxxxxxxxxxx), but when I copy the token and use it, it returns status == 401.
    – Ben Inm
    Commented Sep 19, 2021 at 2:26
  • var config = { url: restBaseURI + "interaction/v1/eventDefinitions/", contentType: "application/json", header: { Authorization: "Bearer " + token } };
    – Ben Inm
    Commented Sep 19, 2021 at 2:55

0

You must log in to answer this question.