I am using a Cloudflare worker and this is what my index.ts
file looks like:
const tweet = async () => {
console.log('tweet function ran')
let request = await fetch("https://api.twitter.com/2/tweets", {
method: "POST",
headers: {
Authorization: "Bearer <ACCESS TOKEN HERE>",
'user-agent': "v2CreateTweetJS",
'content-type': "application/json",
'accept': "application/json"
},
body: JSON.stringify({"text": "my remote Tweet"})
})
console.log(await request.json())
return new Response("This response ran")
}
addEventListener('fetch', (event: FetchEvent) => {
event.respondWith(tweet());
});
And when I run this code, I get this error:
<myusername>@<mycomputername> <myappname> % wrangler dev
👂 Listening on http://127.0.0.1:8787
🌀 Detected changes...
💁 Ignoring stale first change
tweet function ran
{ title: 'Unsupported Authentication', detail: 'Authenticating with OAuth 2.0 Application-Only is …OAuth 1.0a User Context, OAuth 2.0 User Context].', type: 'https://api.twitter.com/2/problems/unsupported-authentication', status: 403 }
[2022-04-23 21:41:58] GET <myappname>.<mycloudflarworkername>.workers.dev/ HTTP/1.1 200 OK
^C
<myusername>@<mycomputername> <myappname> %
How do I fix this? I would be fine with switching to v1 APIs but I can't find any info on how to do that either.
The error message
Authenticating with OAuth 2.0 Application-Only
Indicates that the bearer token sent in the API request represents the application and not the user on whose behalf the tweet is sent. You need to obtain a token for the user who is sending the tweet.
Tweet api only accepts user context authentication as per this:
https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets
However, the error seems to indicate that both OAuth 1.0 and OAuth 2.0 are supported.
The other documentation page confirms this by saying:
Please note that OAuth 1.0a is still required to issues requests on behalf of users.
https://developer.twitter.com/en/docs/authentication/oauth-2-0/application-only
So you should be fine with both methods.
OAuth 1.0a auth header is described here
https://developer.twitter.com/en/docs/authentication/oauth-1-0a/authorizing-a-request