生成令牌以调用 Dialogflow V2

Generate Token to call Dialogflow V2

我需要调用 Dialogflow V2 APIs,但为此我需要生成一个令牌。 我找到了很多关于如何执行此操作的代码,但对我不起作用。

我正在执行 API 生成令牌,然后将令牌传递给另一个 API 以调用 DialogFlow APIs。

任何人都可以帮助我如何生成令牌来调用 Dialogflow V2 APIs 吗?

我的API生成令牌代码如下:

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);

Dialogflow V2 不再使用 developer/client 访问令牌。您需要使用您的服务帐户密钥文件来访问 API。你可以关注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.

安装客户端库:

npm install @google-cloud/dialogflow

来自 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.`);
  }
}

下面的代码对我返回 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;
};