Executing Google AppScript functions with JS, PHP and Android APIS

Pre Development

  1. Create project

    1. get project no:(to be set in Appscript Settings)
    2. create web client
    3. Get Client_ID(used in js, PHP and android app) and Client Secret(used in PHP ie backend app only) from Web client
    4. Add required scopes
    5. For JS ,get API key(used in javascript while intitializing gapi client (gapi.client.init).
    6. For Backend(PHP), Set Redirect URLs( for backend script to recieve Auth Code)
    7. For android, create SHA-1 certificate and set.
  2. Create App Script

    1. go to settings, set project number got above
    2. deploy as API executable
    3. get script ID. For API Executable scripts, this is deployment_Id in Manage Deployments. Used in js:gapi.client.request and PHP: $service->scripts->run and mService.scripts().run(scriptId, request).execute(); in Android
    4. Test directly to make sure there are no errors in the script.

PHP

Link

  1. download Google API Client Library with composer
    composer require google/apiclient:^2.15.0

    and

    require_once '/path/to/your-project/vendor/autoload.php';
  2. Declare credentials
    1. Client ID
    2. Client Secret
    3. Script ID
    4. SCOPES
  3. Initiate GoogleClient with correct redirect URL and scopes
  4. Create login link
  5. Create method fetchTokenFromAuthCode to get toke from code
    • token so got is JSON object will contain the following
      1. access_token
      2. expires_in
      3. refresh_token (first time login only)
      4. scope
      5. token_type
      6. id_token (only if profile and email scopes are requested)
      7. created
        {
        "access_token":"ya29.a0AfB_byBHMAjgaqzwtbS5lfvUGNESM_Hy1ebxWOoPbv6mtg5hO_1p343wNW6mBZvtexAvr9Je8HSO7x8q2Lsq1k_k6GiPtMowlkTUKPiUZrya9vJvbXUnw3vd9jf2J0j5LVa2VvQKK8LolYkAPGDk42no2f0JHTFV4gaCgYKAYQSARESFQGOcNnCKwegBmqHjgJqHhq6WkpNxQ0169",
        "expires_in":3599,
        "refresh_token":"1\/\/0gq2Nvl4NsFmxCgYIARAAGBASNwF-L9Ircs4nklgMCndIjnB1pnfafJrj7v4MPXew1NT-WXnGzrCCQ6NpwpfIfABIqAcY4Spsq98",
        "scope":"https:\/\/www.googleapis.com\/auth\/drive https:\/\/www.googleapis.com\/auth\/userinfo.profile https:\/\/www.googleapis.com\/auth\/userinfo.email https:\/\/www.googleapis.com\/auth\/script.external_request https:\/\/www.googleapis.com\/auth\/calendar.readonly openid",
        "token_type":"Bearer",
        "id_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IjgzOGMwNmM2MjA0NmMyZDk0OGFmZmUxMzdkZDUzMTAxMjlmNGQ1ZDEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIzNDQ2NDM3Mzk0MzMtcnVyN3JyOTh1NnM1MmY2cTI4ZXRzY2UybzdhamkyOXQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIzNDQ2NDM3Mzk0MzMtcnVyN3JyOTh1NnM1MmY2cTI4ZXRzY2UybzdhamkyOXQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDI5NjQxMzA4MTg3NDg1ODg5MjAiLCJlbWFpbCI6ImxlZ2FsbGl2ZWluZGlhQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdF9oYXNoIjoiSkxIODNDNFdJTU80dXczT284WnlaZyIsIm5hbWUiOiJMZWdhbCBMaXZlIiwicGljdHVyZSI6Imh0dHBzOi8vbGgzLmdvb2dsZXVzZXJjb250ZW50LmNvbS9hL0FDZzhvY0tvb3lCMUpaU3U1UVJmOXZuWHhaQm9PTFpnc3ptdEZyc1dZTDg4LXl2Rz1zOTYtYyIsImdpdmVuX25hbWUiOiJMZWdhbCIsImZhbWlseV9uYW1lIjoiTGl2ZSIsImxvY2FsZSI6ImVuIiwiaWF0IjoxNjk0MTU1NTY4LCJleHAiOjE2OTQxNTkxNjh9.MExYGhz7vWEHO0CzxVLsBzNcQ3zoMv1Zf1t7zuoDJuKvYG664YfOwCPucyLM1z_goddEnZCKrOe-XwFd3u1KsmTR_YGH446NkkJx7dsi7NXdCkJChvL-3dGtwG2VJVKvhcHYxg3oWm5gCQrcGKC3F-FYZR_GKsMyXissE31WXIKhvdYh06fMqppWabMj712-KR4o52A2QMWTR2M6k6V9eSOCPtuDrsivHIpofBrgCeOoAZYOQOgXjc_ftwynkFsufpQd8F93nsjMcmnj63YAjKaxZLCdCMG3ZdkXnMJguZ5oUeG0zEawCl7cI3HCLRsGL4C0q9T9oft1RYFVHtm0jQ",
        "created":1694155573}
  6. Initiate GoogleService with will be used to call API functions
  7. create setAccessToken method to refresh access_token if expired($this->googleClient->refreshToken).
  8. Before calling API fucntionsetAccessToken.
  9. call API function
  10. get result and display it

Javascript

Link

  1. Declare credentials.
    1. CLIENT_ID
    2. CLIENT_SECRET
    3. scriptId
    4. SCOPES
  2. initialize gis client. there are 2 ways
    1. Implicit method tokenClient = google.accounts.oauth2.initTokenClient (access key got directly in js. but refresh key will not be got).
    2. Authorisation Code model client = google.accounts.oauth2.initCodeClient (auth code recieved in JS. sent to backend which obtains token with refresh_token
  3. Initialize gapi.client
  4. get access key with either method above
  5. before API function call gapi.client.setToken
  6. call API function gapi.client.request
  7. get result and display it

Android

JAVA API for Google AppScripts

Two libraries for Google Auth

Getting Auth Code to get Refresh token from WebClient

  1. declare credentials
    1. CLIENT_ID
    2. scriptId
    3. SCOPES
  2. initiate GoogleAccountCredential mCredential object
    mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());
  3. Choose Account
private void chooseAccount() {
        startActivityForResult(
                mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
    }
  1. Get Token in onActivityResult
                        new Thread( () ->
                        {
                            try {
                                String token = mCredential.getToken();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            } catch (GoogleAuthException e) {
                                throw new RuntimeException(e);
                            }
                        }).start();
  2. new MakeRequestTask(mCredential).execute();