【问题标题】:Generate Token to call Dialogflow V2生成令牌以调用 Dialogflow V2
【发布时间】:2021-04-06 02:47:14
【问题描述】:

我需要调用 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);

【问题讨论】:

  • 在哪里运行您的应用程序?在谷歌云上?其他地方?
  • 我的应用在本地服务器上运行。
  • 您有服务帐户密钥文件吗? (我认为是的,因为您提供了一个私钥,它应该来自这个密钥文件!)

标签: javascript node.js google-cloud-platform dialogflow-es


【解决方案1】:

Dialogflow V2 不再使用开发者/客户端访问令牌。您需要使用您的服务帐户密钥文件来访问 API。您可以关注this article 来设置您的服务帐号。设置好服务帐号后,您可以查看dialogflow using nodejs 的示例实现。

安装客户端库:

npm install @google-cloud/dialogflow

来自github link的代码sn-p:

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

【讨论】:

    【解决方案2】:

    下面的代码对我有用,返回不记名令牌:

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

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 2019-04-28
      • 2015-10-07
      • 1970-01-01
      • 2019-01-27
      • 2014-09-11
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多