How to track admin domain install?

243 views
Skip to first unread message

Hoang Trinh

unread,
Sep 15, 2019, 7:21:06 AM9/15/19
to Google Apps Script Community

Hi everyone,

I'm trying to get the list of emails of users who installed my addon.


I'm using the onInstall trigger to get the email and push it to my database.


This is fine with individual installation (normal gmail or even admin who chooses to Individual Install)


But with Domain InstallonInstall event was not fired


So how can I track the Domain Installation?


Thank you.

Romain Vialard

unread,
Sep 16, 2019, 3:37:13 AM9/16/19
to Google Apps Script Community
You can use the LicenseNotification endpoint of the G Suite Marketplace API:

It will return the domain name & timestamp for each domain installation.

Hoang Trinh

unread,
Oct 1, 2019, 9:47:14 PM10/1/19
to google-apps-sc...@googlegroups.com
Sorry for a delay reply. 

Thank you very much. It works.

For those who find this in the future:

Using this API, we can have the result like this:

{
  "kind": "appsmarket#licenseNotificationList",
  "notifications": [
    {
      "kind": "appsmarket#licenseNotification",
      "id": "001566972002228000-000001",
      "applicationId": "xxx",
      "customerId": "te...@gmail.com",
      "timestamp": "1566972001590",
      "provisions": [
        {
          "kind": "appsmarket#provisionNotification",
          "editionId": "default_edition",
          "seatCount": "1"
        }
      ]
    },
    {
      "kind": "appsmarket#licenseNotification",
      "id": "001568364120883000-000001",
      "applicationId": "xxx",
      "customerId": "domainabc.com",
      "timestamp": "1568364119585",
      "provisions": [
        {
          "kind": "appsmarket#provisionNotification",
          "editionId": "default_edition",
          "seatCount": "-1"
        }
      ]
    },
    ...
  ],
  "nextPageToken": "001569976724468000-000001"
}

Inside the notifications array, notice some object that has "seatCount": "-1"


Those are domain installations that we are looking for.


We just need to get the value inside "customerId": "domainabc.com",

Faustino Rodriguez

unread,
Oct 2, 2019, 6:53:48 AM10/2/19
to Google Apps Script Community
Thanks
- Did you write a code in Google Apps Script?
- I tried (a bit) but couldn't make it work ...

Hoang Trinh

unread,
Oct 2, 2019, 7:43:14 AM10/2/19
to Google Apps Script Community
No, I didn't write code in Apps Script

With this API, I call API directly (using Axios library in Node.js + setup OAuth2 flow)

If you need guide to setup OAuth2 flow, please check this tutorial: https://developers.google.com/sheets/api/quickstart/nodejs

Inside the listMajors function (after getting the access token), instead of using googleapis, you just need to use Axios to call API directly.

Another way to call API after getting the access token is by using Postman

Faustino Rodriguez

unread,
Oct 2, 2019, 7:49:34 PM10/2/19
to Google Apps Script Community
Thanks!
Not sure if I can go that path, but I'll try it

Romain Vialard

unread,
Oct 3, 2019, 11:21:37 AM10/3/19
to Google Apps Script Community
@faustino, it's also possible to call that API from Apps Script (using UrlFetch) is preferable for you.
Where did you struggle when trying to do that?

Faustino Rodriguez

unread,
Oct 3, 2019, 11:49:41 AM10/3/19
to Google Apps Script Community
I did as follow in a script for testing

In the manifest added the scopes

And wrote this function
function testList() {
 
var applicationId = "736233853391"; // project number
 
var url = "https://www.googleapis.com/appsmarket/v2/licenseNotification/" + applicationId;
 
var param = {
    method
: "get",
    headers
: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions
:true,
 
};
 
var response = UrlFetchApp.fetch(url, param);
 
var content = response.getContentText();
 
 
Logger.log(content);
 
return;
}


When running that function, I got the following message in the Log
{"error":{"errors":[{"domain":"global","reason":"forbidden","message":"Not authorized to access the application ID"}],"code":403,"message":"Not authorized to access the application ID"}}


I guess I am missing something trivial or I am just totally wrong

Thanks for your help on this
Fausto

Romain Vialard

unread,
Oct 3, 2019, 11:55:52 AM10/3/19
to Google Apps Script Community
Ah yes, not sure why but you can't simply use Apps Script built-in oauth.
Best to try with the OAuth2 library and create a client ID and Secret in your add-on cloud console project, that you will reuse in the OAuth2 configuration. 

Romain Vialard

unread,
Oct 3, 2019, 12:02:03 PM10/3/19
to Google Apps Script Community
"To request access using OAuth 2.0, your application needs the scope information, as well as information that Google supplies when you register your application (such as the client ID and the client secret)."

Faustino Rodriguez

unread,
Oct 3, 2019, 12:06:46 PM10/3/19
to Google Apps Script Community
I will try that way and see how it goes
thanks again for your help

Dimu Designs

unread,
Oct 3, 2019, 8:07:23 PM10/3/19
to Google Apps Script Community
In addition to your previous steps, did you also try binding your Apps Script to a GCP Project and enabling the API from the Google Cloud console?

Faustino Rodriguez

unread,
Oct 4, 2019, 6:37:29 AM10/4/19
to Google Apps Script Community
yes, i did that (sorry i forgot to mention it)
i created a GCP project and enable the G Suite Marketplace API there

Faustino Rodriguez

unread,
Jan 27, 2020, 1:19:24 PM1/27/20
to Google Apps Script Community
I did try again to access the end point appsmarket/v2/licenseNotification/applicationId
- this time using gapi.client.request from a web app

But anyhow I try, I am always getting the Error "Not authorized to access the application ID"

I guess I am either missing something trivial or totally off the mark

See below the full code I am using as a proof of concept, with some notes on how I set the project settings (apiKey, clientId, etc)

++ Any help is very welcomed and appreciated +++

<!DOCTYPE html>
<html>

<head>
  <script>
    var app = {};
  </script>
</head>

<body>


  <script>
    function initClient() {
      /* Create a new project at GCP
      - Enable G Suite Marketplace API
      + Go to OAuth consent screen (edit) https://console.cloud.google.com/apis/credentials/consent/edit
      - add the scope ../auth/appsmarketplace.license
      - add authorized/verified domain from where this web app will run (e.g. mydomain.dev)
      + Go to API Credentials https://console.cloud.google.com/apis/credentials
      - Create an API key, restrict to G Suite Marketplace API
      - Create OAuth 2.0 Client ID, add Authorized JavaScript origins URI, like https://mydomain.dev
      */
      var API_KEY = 'api key created as above';
      var CLIENT_ID = 'oauth client id  created as above';

      gapi.client.init({
        'apiKey': API_KEY,
        'clientId': CLIENT_ID,
        'scope': SCOPE,
      }).then(function () {
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSignInStatus);
        updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      });
    }

    function handleClientLoad() {
      gapi.load('client:auth2', initClient);
    }

    function updateSignInStatus(isSignedIn) {
      if (isSignedIn) {
        console.log("Signed In");
        app.signedIn = true;
      }
      else {
        console.log("Signed Out");
        app.signedIn = false;
        if (app.autoSignIn) handleSignInClick();
      }
    }

    function handleSignInClick(event) {
      gapi.auth2.getAuthInstance().signIn();
    }

    function handleSignOutClick(event) {
      gapi.auth2.getAuthInstance().signOut();
    }
  </script>

  <script async defer src="https://apis.google.com/js/api.js?onload=handleClientLoad"></script>

  <script>
    function makeApiCall() {
      var APPLICATION_ID ="project-number-to-list-installs-from";
      gapi.client.request({
        'path': url,
      })
        .then(r => { console.log(r); console.log(JSON.stringify(r, null, 2)); })
        .catch(e => { console.log(e); console.log(JSON.stringify(e, null, 2)); })
    }
  </script>

  <button id="signin-button" onclick="handleSignInClick()">Sign in</button>
  <button id="signout-button" onclick="handleSignOutClick()">Sign out</button>
  <button id="signout-button" onclick="makeApiCall()">Test</button>
</body>

</html>

Andrew Apell

unread,
Jan 27, 2020, 2:00:28 PM1/27/20
to Google Apps Script Community
I would love to see a working solution written by someone who has implemented this... just an outline of sorts.

Hoang Trinh

unread,
Jan 27, 2020, 10:43:50 PM1/27/20
to Google Apps Script Community
const fs = require('fs')
const readline = require('readline')
const { google } = require('googleapis')
const axios = require('axios')

// If modifying these scopes, delete token.json.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json'

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err)
  // Authorize a client with credentials, then call the Google Sheets API.
  authorize(JSON.parse(content), getLicense)
})

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const { client_secret, client_id, redirect_uris } = credentials.web
  const oAuth2Client = new google.auth.OAuth2(
    client_id,
    client_secret,
    redirect_uris[0]
  )

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback)
    oAuth2Client.setCredentials(JSON.parse(token))
    callback(oAuth2Client)
  })
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  })
  console.log('Authorize this app by visiting this url:', authUrl)
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })
  rl.question('Enter the code from that page here: ', code => {
    rl.close()
    oAuth2Client.getToken(decodeURIComponent(code), (err, token) => {
      if (err)
        return console.error('Error while trying to retrieve access token', err)
      oAuth2Client.setCredentials(token)
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), err => {
        if (err) return console.error(err)
        console.log('Token stored to', TOKEN_PATH)
      })
      callback(oAuth2Client)
    })
  })
}

/**
 * Prints the names and majors of students in a sample spreadsheet:
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 */
function getLicense(auth) {
  axios
    .get(
      {
        headers: {
          Authorization: 'Bearer <insert your token here>'
        }
      }
    )
    .then(response => {
      console.log(JSON.stringify(response.data, null, 4))
    })
    .catch(error => {
      console.log(JSON.stringify(error.response.data, null, 4))
    })
}

 
Please check my implementation above (it's based on this example https://developers.google.com/sheets/api/quickstart/nodejs, you can read this example to understand how it works)

It worked for me before. But recently I always get error 500 Backend Error https://developers.google.com/drive/api/v3/handle-errors#resolve_a_500_error_backend_error

Google suggests that we try exponential backoff to retry the request, but I didn't implement it yet.

Andrew Apell

unread,
Jan 28, 2020, 12:07:23 AM1/28/20
to Google Apps Script Community
Many thanks Hoang... digging in now.

Chart Expo

unread,
Feb 4, 2020, 10:42:34 AM2/4/20
to google-apps-sc...@googlegroups.com
Hi Hoang,

I have published an add-on. On normal user installation i am getting user detail in onInstall trigger and then save it inside of my database. on next time opening of add-on, i load detail of normal user from database.
But, i have observed that on domain admin install, onInstall trigger is not fired.
Please guide me, which event/trigger called in case of domain admin install. As i want to store domain and admin information in database. 

Regards,
Shehbaz

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/3ca64de3-3cc6-4972-b5ce-1c4f24b0b2bb%40googlegroups.com.

Hoang Trinh

unread,
Feb 4, 2020, 10:22:00 PM2/4/20
to Google Apps Script Community
Hi,

For domain installs, there are no events. That's why I need to use the API that Romain suggested to get the information. 


On Tuesday, February 4, 2020 at 10:42:34 PM UTC+7, ChartExpo Add-on wrote:
Hi Hoang,

I have published an add-on. On normal user installation i am getting user detail in onInstall trigger and then save it inside of my database. on next time opening of add-on, i load detail of normal user from database.
But, i have observed that on domain admin install, onInstall trigger is not fired.
Please guide me, which event/trigger called in case of domain admin install. As i want to store domain and admin information in database. 

Regards,
Shehbaz

To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-community+unsub...@googlegroups.com.

Hrach Tamrazyan

unread,
Jul 18, 2022, 5:29:00 AM7/18/22
to Google Apps Script Community

Hello all,

Thanks for the info. We have tried but always getting the error. Any help?
Screenshot 2022-07-18 at 2.46.34 PM.png

rupam.p...@gmail.com

unread,
Feb 20, 2023, 4:39:02 AM2/20/23
to Google Apps Script Community
Is it working for anyone ? I am getting the error "Not authorized to access the application ID".
Reply all
Reply to author
Forward
0 new messages