简单的博客机器人

时间:2018-08-30 20:45:49

标签: javascript node.js blogger google-oauth2

您好,我正在尝试使用以下方法为Blogspot创建一个简单的机器人 插入 发布 删除

但是我被oauth2Client困住了

我尝试什么:

1°获得令牌代码:

const oauth2Client = new google.auth.OAuth2(
  'CLIENT_ID ,
  'CLIENTE SECRET ID ',
  'REDIRECT URL '
);


const scopes = [
  'https://www.googleapis.com/auth/blogger'
];

const url = oauth2Client.generateAuthUrl({
  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',


  scope: scopes
});
console.log(url);

在浏览器中2°粘贴网址,以登录Google

3°然后加上音调代码

const {tokens} =  oauth2Client.getToken('TOKEN CODE THAT WAS RETURN )
oauth2Client.setCredentials({
  access_token: tokens, 
  // Optional, provide an expiry_date (milliseconds since the Unix Epoch)
   expiry_date: (new Date()).getTime() + (1000 * 60 * 60 * 24 * 7)
});


const blogger = google.blogger({
  version: 'v3',
  auth: oauth2Client
});

async function runSample () {
  console.log("running")
  const res = blogger.posts.insert({
    blogId: 'BLOGID',
    requestBody: {
      title: 'Hello from the googleapis npm module!',
      content: 'Visit https://github.com/google/google-api-nodejs-client to learn more!'
    }
  });
  console.log(res.data);
  return res.data;
}

runSample();

响应是

错误:未设置访问权限,刷新令牌或API密钥

我已经刷新了键和同样的旧东西

1 个答案:

答案 0 :(得分:0)

Tokens返回的

oauth2Client.getToken()对象包含一个access_token和refresh_token(还包含expires_in和token_type字段)。

所以您需要写:

oauth2Client.setCredentials({
  access_token: tokens.access_token,
  refresh_token: tokens.refresh_token,
  expiry_date: (new Date()).getTime() + (1000 * 60 * 60 * 24 * 7)
});

参考:https://developers.google.com/identity/protocols/OAuth2WebServer#handlingresponse