Search code examples
google-cloud-functionsgoogle-oauthgoogle-analytics-api

Google Cloud Functions Analytics API - Delete User OAuth2


need some help, please.

I have a cloud function to delete user data from Google Analytics, this function is triggered when I send a Pub/Sub message from my backend with a delete request. I'm using Google Analytics API, which was activated on my Google Cloud Console.

I followed this doc: https://developers.google.com/analytics/devguides/config/userdeletion/v3, but I didn't succeed in deleting the user via the cloud function.

cloud function:


function deleteGArecord(userObject) {

  const options = {
    method: "POST",
    url: "https://www.googleapis.com/analytics/v3/userDeletion/userDeletionRequests:upsert",
    headers: {
      //"Content-Type": "application/json",
    },
    body: JSON.stringify({
      kind: "analytics#userDeletionRequest",
      id: {
        type: "CLIENT_ID",
        userId: userObject.clientId,
      },
      webPropertyId: "UA-111111-000",
    }),
  };
  request(options, function (error, response) {
    if (error) {
      console.log(error);
    }
    console.log("ga user delete request:" + JSON.stringify(response));
  });
}

What I tried:

  1. Create OAuth client ID - application type web.
  2. Added this client on my Analytics property.
  3. Call the function when a delete request is sent.

Cloud function log:

"statusCode":401,"body":"{\n \"error\": {\n \"code\": 401,\n \"message\": \"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n \"errors\": [\n {\n \"message\": \"Login Required.

How I authenticate my cloud function to be able to send this hit. I've created the user already and I'm calling this function from the same project ClientId is...

Thanks in advance!


Solution

  • Request is missing required authentication credential.

    Your missing your authorization header. Your going to need a bearer token containing an access token with the correct authorized scopes

    User Deletion API

    Requires authorization with the following scope

    enter image description here

    Once you are authorized your looking at something like this.

    const options = {
        method: "POST",
        url: "https://www.googleapis.com/analytics/v3/userDeletion/userDeletionRequests:upsert",
        headers: {
          "Authorization": "Bearer " + access_token,
        },
    

    The issue will be how to get a cloud function to authorize to a google api.