Skip to content
Developerhome
X3

Scripts for token management

  Less than to read

  • Pre-request scripts to renew access token automatically

    const authen = {
        refresh_token : pm.environment.get('refreshToken'),
        client_id : pm.environment.get('clientId'),
        client_secret :  pm.environment.get('clientSecret'),
        grant_type : 'refresh_token',
        mode: 'application/json'
    };
    var body = JSON.stringify(authen);
    
    const echoPostRequest = {
    url: 'https://api.customerregion-sagex3.com/v1/token',
    method: 'POST',
    header: 'Content-Type:application/json',
    body: body
    };
    
    if (!pm.environment.get('accessTokenExpiry') ||
        !pm.environment.get('accessToken')
        ||pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
    
        //First use or access token expired
        pm.sendRequest(echoPostRequest, function (err, res) {
        console.log(err ? err : res.json());
            if (err === null) {
                //Saving the access token
                var responseJson = res.json();
                if (responseJson.access_token !== undefined) {
                    pm.environment.set('accessToken', responseJson.access_token)
                    var expiryDate = new Date();
                    //Saving the expiry date = date + 300 seconds (5 minutes)
                    expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
                    pm.environment.set('accessTokenExpiry', expiryDate.getTime());
                    //Saving the refresh token
                    pm.environment.set('refreshToken',  responseJson.refresh_token);
                }
            }
        });
    }
    

    Postman script