[英]POST request issues to Twitter API
I have been using NextJS, Twitter-lite to build an application using the twitter app, I basically am trying to implement the functionality in which users can post a tweet from the app to their twitter accounts.我一直在使用 NextJS,Twitter-lite 来构建一个使用 twitter 应用程序的应用程序,我基本上是在尝试实现用户可以将推文从应用程序发布到他们的 Twitter 帐户的功能。 I have also used Next-Auth for implementing oAuth for twitter.
我还使用 Next-Auth 为 twitter 实现 oAuth。
So after some working, I have managed to make it work and highlight my error - Access tokens.因此,经过一番工作,我设法使其工作并突出显示我的错误 - 访问令牌。 I want to fetch access tokens from the user after they have logged in,
我想在用户登录后从用户那里获取访问令牌,
In the below example - I run this script and a post is updated to my account indeed在下面的示例中 - 我运行此脚本,并且确实将帖子更新到我的帐户
Here is my code for the api/twitter/post.js这是我的 api/twitter/post.js 代码
import Twitter from 'twitter-lite';
import { getSession } from 'next-auth/react'
import { getToken } from 'next-auth/jwt';
export default async (req, res) =>{
var Twit = require('twit')
const session = await getSession({ req });
const token = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET
});
console.log(token.twitter.accessToken)
var T = new Twit({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: 'process.env.TWITTER_ACCESS_TKN',
access_token_secret: 'process.env.TWITTER_ACCESS_TKN_SCRT'
});
T.post('statuses/update', { status: 'hello worldj!' }, function(err, data, response) {
console.log(data)
})
return res.status(200).json({ status: 'ok'});
}
Now this does work, when I hit my api route a new tweet is posted but only to 'my' account because I provided my access_tokens
, I would like to know how I can get users access tokens, I have already signed them in using NextAuth so I'm sure I'm just missing a few things.现在这确实有效,当我点击我的 api 路由时,一条新推文被发布但只发布到“我的”帐户,因为我提供了我的
access_tokens
,我想知道如何让用户访问令牌,我已经使用 NextAuth 登录了他们所以我确定我只是错过了一些东西。
So I figured this one out,所以我想出了这个,
In the call backs functions in the [...nextauth].js
, I was just fetching the access_tokens
with an outdated name and the new name is account.oauth_token
在
[...nextauth].js
的回调函数中,我只是用过时的名称获取access_tokens
,新名称是account.oauth_token
For anyone who ever encounters this issue - (Trying to fetch logged in users access tokens to access restricted twitter endpoints)对于遇到此问题的任何人 - (尝试获取登录用户访问令牌以访问受限 Twitter 端点)
callbacks: {
async jwt({ token, user, account = {}, profile, isNewUser }) {
if (account.provider && !token [account.provider]) {
token[account.provider] = {};
}
if(account.oauth_token) {
token[account.provider].accessToken = account.oauth_token;
}
if (account.oauth_token_secret) {
token [account.provider].refreshToken = account.oauth_token_secret;
}
return token
},
This is how you get the logged in users access_token
and access_token_secret
这是您获取登录用户
access_token
和access_token_secret
的方式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.