0
votes

I'm trying to change Box folder collaboration type for user from salesforce Apex trigger. The first thoughts were to use box.Toolkit but it looks like this class does not have updateCollaboration or changeCollaboration method, only create. I guess my only option is to use Box's Rest API. Is there any way I can get service account token in Apex so I can use it in a callout?

1
Could you provide a code snippet of what you have tried already?Frank Bryce

1 Answers

0
votes

I have created a special "Tokens" object in Salesforce with two fields: access token and refresh token. I then have a batch job that runs to update the access token every 55 minutes such that they never expired.

Here is a code snippet in APEX using the Tokens object.

@future(callout=true)
   public static void updateTokens(){
   //app info for authenticating 
    String clientID = 'MY_CLIENT_ID';
    String clientSecret = 'MY_CLIENT_SECRET';

    //look up value of existing refresh token
    Token__c myToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Refresh'];
    Token__c myAccessToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Access'];
    String refreshToken = myToken.Value__c;
    String accessToken = myAccessToken.Value__c;

    //variables for storing data
    String BoxJSON = '';
    String debugTxt = '';


    //callout to Box API to get new tokens
    HttpRequest reqRefresh = new HttpRequest();
    reqRefresh.setMethod('POST');
    String endpointRefresh = 'https://www.box.com/api/oauth2/token';
    reqRefresh.setEndpoint(endpointRefresh);
    String requestBody = ('grant_type=refresh_token&refresh_token=' + refreshToken + '&client_id=' + clientID + '&client_secret=' + clientSecret);
    reqRefresh.setBody(requestBody);
    System.debug('Body of refresh request: ' + requestBody);

    //Create Http, send request
    Http httpRefresh = new Http();
    Boolean successRefresh = false;
    while (successRefresh == false){
    try{
        HTTPResponse resRefresh = httpRefresh.send(reqRefresh);
        BoxJSON = resRefresh.getBody();
        System.debug('Body of refresh response: ' + BoxJSON);
        successRefresh = true;
    } 
    catch (System.Exception e){
        System.debug('Error refreshing: ' + string.valueof(e));
        if (Test.isRunningTest()){
            successRefresh = true;
        }
    }
}

Keep in mind that if you are using the Box for Salesforce integration your administrator can set the option for the permissions on the folders to sync with Salesforce permissions. This would reverse any changes you make to collaborations. Check out more about Box's Salesforce integration permissions here: https://support.box.com/hc/en-us/articles/202509066-Box-for-Salesforce-Administration#BfS_admin_perm