google-apps-scriptgoogle-apigoogle-oauthservice-accountsgoogle-groups-api

Authenticate Service Account from Apps Script


I'm trying to add members into a group using the API. I'm coding in the google script tool, however, I'm getting the error message:

{
     "error": {
         "errors": [
             {
                 "domain": "global",
                 "reason": "required",
                 "message": "Login Required",
                 "locationType": "header",
                 "location": "Authorization"
             }
         ],
         "code": 401,
         "message": "Login Required"
     }
}

I already added the scopes in the G SUITE domain, I already created service account, API key, OAuth 2.0 key. My request is currently so:

  var headers = {
    "apiKey" : "****",
    "clientId" : "*****.apps.googleusercontent.com"
  }

  var payload = {
    "email": user,
    "role": "MEMBER"
  }

  var options = {
    "method" : "post",
    "payload" : payload,
    "headers" : headers
  };

  var response = UrlFetchApp.fetch("https://www.googleapis.com/admin/directory/v1/groups/***/members", options);

What is missing, or what am I doing wrong? I've read all the documentation and still can not figure out what's wrong.


Solution

  • As I was coding through Google Scripts, I found a service that has the function I need. It's called Directory and it's inside the Admin SDK section of Google. Below is the link that leads to the documentation, where you have the examples:

    https://developers.google.com/apps-script/advanced/admin-sdk-directory

    In the end, my code looked like this:

    function insertMembers(){
      var ss = SpreadsheetApp.getActive()
      var sheet = ss.getSheetByName("")
    
      var membersInSheet = sheet.getRange(27, 3, sheet.getLastRow())
      var values = membersInSheet.getNumRows()
      var groupId = "email group"
    
      //Logger.log(membersInSheet)
    
      for (var i = 0; i < values; i++){
        var getMember = sheet.getRange(27+i, 3).getValue();
    
        var member = {
          email: getMember,
          role: 'MEMBER'
        };
    
        if (member != ''){
          var memberAdd = AdminDirectory.Members.insert(member, groupId);
          Logger.log(memberAdd);
    
        }
      }
    }
    

    No authentication, and no rest!