googleapis / google-api-nodejs-client

Google's officially supported Node.js client library for accessing Google APIs. Support for authorization and authentication with OAuth 2.0, API Keys and JWT (Service Tokens) is included.
https://googleapis.dev/nodejs/googleapis/latest/
Apache License 2.0
11.45k stars 1.92k forks source link

Getting Invalid Argument error from Google Business Profile API while trying to create a location #3530

Open ahsanaasim opened 4 months ago

ahsanaasim commented 4 months ago

I am using Google's Business API to add a location from my Node.js application, but I'm encountering the following error:

{
    "error": "Request contains an invalid argument."
}

I am using the googleapis npm package and tried by commenting out all optional fields, leaving only the required fields in the request body. But, I'm still encountering an error. Here is my code:

app.post('/add-location', async (req, res) => {
    const { location, tokens } = req.body;
    oauth2Client.setCredentials(tokens);

    const mybusinessbusinessinformation = google.mybusinessbusinessinformation('v1');
    try {
        const response = await mybusinessbusinessinformation.accounts.locations.create({
            parent: 'accounts/' + process.env.ACCOUNT_ID,
            validateOnly: true,
            requestId: uuidv4(),
            requestBody: {

                // "name": "EVgo Charging Station",
                // "languageCode": "en",
                // "storeCode": "EVG123",
                "title": "EVgo Charging Station",
                // "phoneNumbers": {
                //     "primaryPhone": "+1 123-456-7890"
                // },
                // "categories": {
                //     "primaryCategory": {
                //         "name": "categories/gcid:electric_vehicle_charging_station",
                //         "displayName": "Electric vehicle charging station",
                //     },
                // },
                // "storefrontAddress": {
                //     "regionCode": "US",
                //     "locality": "Durham",
                //     "postalCode": "27707",
                //     "addressLines": ["4711 Hope Valley Rd", "Woodcroft Shopping Center"]
                // },
                // "websiteUri": "https://evgo.com",
                // "regularHours": {
                //     "periods": [
                //         {
                //             "openDay": "MONDAY",
                //             "openTime": {
                //                 "hours": 0,
                //                 "minutes": 0
                //             },
                //             "closeDay": "SUNDAY",
                //             "closeTime": {
                //                 "hours": 23,
                //                 "minutes": 59
                //             }
                //         }
                //     ]
                // },
                // "specialHours": {
                //     "specialHourPeriods": [
                //         {
                //             "startDate": {
                //                 "year": 2024,
                //                 "month": 12,
                //                 "day": 25
                //             },
                //             "endDate": {
                //                 "year": 2024,
                //                 "month": 12,
                //                 "day": 25
                //             },
                //             "closed": true
                //         }
                //     ]
                // },
                // "labels": [
                //     "EV Charging",
                //     "Fast Charging"
                // ],
                // "latlng": {
                //     "latitude": 35.951033,
                //     "longitude": -78.956228
                // },
                // "openInfo": {
                //     "status": "OPEN",
                //     "canReopen": true
                // },
                // "metadata": {
                //     "mapsUri": "https://maps.google.com/?q=EVgo+Charging+Station",
                //     "newReviewUri": "https://maps.google.com/review?place_id=ChIJzxbB6Gs7bIcRZZrPTeyb-0A"
                // },
                "profile": {
                    "description": "Fast and reliable electric vehicle charging station."
                },
                // "relationshipData": {
                //     "parentChain": "EVgo"
                // },
                // "moreHours": [
                //     {
                //         "hoursTypeId": "DRIVE_THROUGH",
                //         "periods": [
                //             {
                //                 "openDay": "MONDAY",
                //                 "openTime": {
                //                     "hours": 0,
                //                     "minutes": 0
                //                 },
                //                 "closeDay": "SUNDAY",
                //                 "closeTime": {
                //                     "hours": 23,
                //                     "minutes": 59
                //                 }
                //             }
                //         ]
                //     }
                // ],
            },
            auth: oauth2Client
        });
        console.log(response)
        res.send(response.data);
    } catch (error) {
        console.error(error)
        res.status(400).send({ error: error.message });
    }
});

here is detailed log

GaxiosError: Request contains an invalid argument.
    at Gaxios._request (/Users/workstation/Programming/Clients/-/gmb-microservice/node_modules/gaxios/build/src/gaxios.js:142:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async OAuth2Client.requestAsync (/Users/workstation/Programming/Clients/-/gmb-microservice/node_modules/google-auth-library/build/src/auth/oauth2client.js:429:18)
    at async /Users/workstation/Programming/Clients/-/gmb-microservice/server.js:52:26 {
  config: {
    url: 'https://mybusinessbusinessinformation.googleapis.com/v1/accounts/102094468378068712054/locations?validateOnly=true&requestId=54e30089-a836-441c-8eb0-bdd936c0a979',
    method: 'POST',
    apiVersion: '',
    userAgentDirectives: [ [Object] ],
    paramsSerializer: [Function (anonymous)],
    data: { title: 'EVgo Charging Station', profile: [Object] },
    headers: {
      'x-goog-api-client': 'gdcl/7.2.0 gl-node/20.8.0',
      'Accept-Encoding': 'gzip',
      'User-Agent': 'google-api-nodejs-client/7.2.0 (gzip)',
      Authorization: '<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.',
      'Content-Type': 'application/json'
    },
    params: {
      validateOnly: true,
      requestId: '54e30089-a836-441c-8eb0-bdd936c0a979'
    },
    validateStatus: [Function (anonymous)],
    retry: true,
    body: '{"title":"EVgo Charging Station","profile":{"description":"Fast and reliable electric vehicle charging station."}}',
    responseType: 'unknown',
    errorRedactor: [Function: defaultErrorRedactor],
    retryConfig: {
      currentRetryAttempt: 0,
      retry: 3,
      httpMethodsToRetry: [Array],
      noResponseRetries: 2,
      retryDelayMultiplier: 2,
      timeOfFirstRequest: 1722445004419,
      totalTimeout: 9007199254740991,
      maxRetryDelay: 9007199254740991,
      statusCodesToRetry: [Array]
    }
  },
  response: {
    config: {
      url: 'https://mybusinessbusinessinformation.googleapis.com/v1/accounts/102094468378068712054/locations?validateOnly=true&requestId=54e30089-a836-441c-8eb0-bdd936c0a979',
      method: 'POST',
      apiVersion: '',
      userAgentDirectives: [Array],
      paramsSerializer: [Function (anonymous)],
      data: [Object],
      headers: [Object],
      params: [Object],
      validateStatus: [Function (anonymous)],
      retry: true,
      body: '{"title":"EVgo Charging Station","profile":{"description":"Fast and reliable electric vehicle charging station."}}',
      responseType: 'unknown',
      errorRedactor: [Function: defaultErrorRedactor]
    },
    data: { error: [Object] },
    headers: {
      'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
      'cache-control': 'private',
      'content-encoding': 'gzip',
      'content-type': 'application/json; charset=UTF-8',
      date: 'Wed, 31 Jul 2024 16:56:44 GMT',
      server: 'ESF',
      'transfer-encoding': 'chunked',
      vary: 'Origin, X-Origin, Referer',
      'x-content-type-options': 'nosniff',
      'x-frame-options': 'SAMEORIGIN',
      'x-xss-protection': '0'
    },
    status: 400,
    statusText: 'Bad Request',
    request: {
      responseURL: 'https://mybusinessbusinessinformation.googleapis.com/v1/accounts/102094468378068712054/locations?validateOnly=true&requestId=54e30089-a836-441c-8eb0-bdd936c0a979'
    }
  },
  error: undefined,
  status: 400,
  code: 400,
  errors: [
    {
      message: 'Request contains an invalid argument.',
      domain: 'global',
      reason: 'badRequest'
    }
  ],
  [Symbol(gaxios-gaxios-error)]: '6.7.0'
}

Also, Is there detailed documentation available for the Google Business API in the googleapis npm package?

I am following the following URL for creating the request body

https://developers.google.com/my-business/reference/businessinformation/rest/v1/accounts.locations#Location

I have asked the same question in stackoverflow. https://stackoverflow.com/questions/78817586/getting-invalid-argument-error-from-google-business-profile-api-while-trying-to

ahsanaasim commented 3 months ago

I went through the gaxios.js file and added the following lines after line 142.

console.log("================")
                console.log(response)
                console.log(response.statusCode)
                console.log("translatedResponse")
                console.log(JSON.stringify(translatedResponse.data))
                console.log("================")

That way i am getting the real error from Google API. I found that there are some more required fields. So, I added them. Now getting another error saying

{"error":{"code":403,"message":"Unable to create due to: REASON_GOLA_CREATION_DISALLOWED_IN_INCORRECT_GROUP_TYPE","errors":[{"message":"Unable to create due to: REASON_GOLA_CREATION_DISALLOWED_IN_INCORRECT_GROUP_TYPE","domain":"global","reason":"forbidden"}],"status":"PERMISSION_DENIED"}}

Looking into the matter. I will update here

ahsanaasim commented 3 months ago

It seems, A location cannot be added under an Organization Account. Therefore, I created a Location Group Account under the Organization and used that Location Group Account ID. Finally it worked.

I created a location group using the following code.

const createLocationGroup = async (auth, groupName, primaryOwner) => {
    const mybusinessaccountmanagement = google.mybusinessaccountmanagement('v1');
    try {
        const response = await mybusinessaccountmanagement.accounts.create({
            auth: auth,
            requestBody: {
                accountName: groupName,
                primaryOwner: 'accounts/' + primaryOwner,
                type: 'LOCATION_GROUP'
            }
        });
        return response.data;
    } catch (error) {
        console.error('Error creating location group:', error);
        throw error;
    }
};
ahsanaasim commented 3 months ago

I have another question. How these values are added in the map. Which attributes are they?

Screenshot 2024-08-01 at 5 52 06 PM
faisalseraj commented 1 week ago

Hi @ahsanaasim,

I am getting the same error as you do.

Could you please guide me how did you get the Account ID? I can't find the Account ID placed in the google interface