Felipe Souza
Felipe Souza

Reputation: 67

Generate Token to call Dialogflow V2

I need to call a Dialogflow V2 APIs, but to do this i need to generate a token. I found many codes about how to do this, but doesn't work for me.

I'm doing an API to generate token and then pass the token to another API to call DialogFlow APIs.

Can anyone help me how to generate a token to call Dialogflow V2 APIs?

My API to generate token Code below:

const express = require('express');

const router = express.Router();

const googleAuth = require('google-oauth-jwt');

function generateAccessToken() {
        return new Promise((resolve) => {
                googleAuth.authenticate(
                        {
                                email: "<myemail>",
                                key: "<myprivatekey>",
                                scopes: "https://www.googleapis.com/auth2/v4/token",
                        },
                        (err, token) => {
                                resolve(token);
                        },
                );
        });
}

router.get('/token', async(req, res) => {
        try {
                let tok = await generateAccessToken();

                return res.status(200).send({ Token: tok});
        } catch(err) {
                return res.status(500).send({ error: 'Erro ao gerar token'});
        }
});

module.exports = app => app.use('/', router);

Upvotes: 0

Views: 531

Answers (2)

Felipe Souza
Felipe Souza

Reputation: 67

Below the code worked for me returning Bearer Token:

const express = require('express');

const router = express.Router();

const googleAuth = require('google-oauth-jwt');
const {google} = require('googleapis');
const request = require('request');

async function generateAccessToken2() {
        const jwtClient = new google.auth.JWT(
                "<email serviceaccount>",
                null,
                "<Private Key>",["https://www.googleapis.com/auth/indexing","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/dialogflow"],
                null
        );
        let tok = "";
        tok = jwtClient.authorize();
        return tok;
};

Upvotes: 0

Ricco D
Ricco D

Reputation: 7287

Dialogflow V2 no longer uses developer/client access tokens. You need to use your service account key file to access the API. You can follow this article to set up your service account. Once you have set up your service account, you can check the sample implementation of dialogflow using nodejs.

Install client library:

npm install @google-cloud/dialogflow

Code snippet from the github link:

const dialogflow = require('@google-cloud/dialogflow');
const uuid = require('uuid');

/**
 * Send a query to the dialogflow agent, and return the query result.
 * @param {string} projectId The project to be used
 */
async function runSample(projectId = 'your-project-id') {
  // A unique identifier for the given session
  const sessionId = uuid.v4();

  // Create a new session
  const sessionClient = new dialogflow.SessionsClient();
  const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        // The query to send to the dialogflow agent
        text: 'hello',
        // The language used by the client (en-US)
        languageCode: 'en-US',
      },
    },
  };

  // Send request and log result
  const responses = await sessionClient.detectIntent(request);
  console.log('Detected intent');
  const result = responses[0].queryResult;
  console.log(`  Query: ${result.queryText}`);
  console.log(`  Response: ${result.fulfillmentText}`);
  if (result.intent) {
    console.log(`  Intent: ${result.intent.displayName}`);
  } else {
    console.log(`  No intent matched.`);
  }
}

Upvotes: 1

Related Questions