首页 > 解决方案 > 生成令牌以调用 Dialogflow V2

问题描述

我需要调用 Dialogflow V2 API,但为此我需要生成一个令牌。我发现了很多关于如何做到这一点的代码,但对我不起作用。

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

谁能帮助我如何生成一个令牌来调用 Dialogflow V2 API?

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

标签: javascriptnode.jsgoogle-cloud-platformdialogflow-es

解决方案


Dialogflow V2 不再使用开发人员/客户端访问令牌。您需要使用您的服务帐户密钥文件来访问 API。您可以按照本文设置您的服务帐户。设置服务帐户后,您可以使用 nodejs检查对话流的示例实现。

安装客户端库:

npm install @google-cloud/dialogflow

来自github 链接的代码片段:

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

推荐阅读