index.ts
const oAuthRequestToken = await requestToken();
const authorizeURL = `https://api.twitter.com/oauth/authorize?oauth_token=${oAuthRequestToken.oauth_token}`;
console.log("Please go here and authorize", authorizeURL);
const pin = await input("Paste the PIN here:");
// Validate the PIN and get the access token
const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
console.log(oAuthAccessToken);
createXMedia('imageurl', oAuthAccessToken);
api.ts
export async function requestToken() {
try {
const requestTokenURL = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write";
const authHeader = oauth.toHeader(
oauth.authorize({
url: requestTokenURL,
method: "POST",
}),
);
const request = await fetch(requestTokenURL, {
method: "POST",
headers: {
Authorization: authHeader["Authorization"],
},
});
const body = await request.text();
return Object.fromEntries(new URLSearchParams(body)) as { oauth_token: string };
} catch (error) {
console.error("Error:", error);
throw error;
}
}
export async function accessToken({ oauth_token }, verifier) {
try {
const url = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const authHeader = oauth.toHeader(
oauth.authorize({
url,
method: "POST",
}),
);
const request = await fetch(url, {
method: "POST",
headers: {
Authorization: authHeader["Authorization"],
},
});
const body = await request.text();
return Object.fromEntries(new URLSearchParams(body)) as { oauth_token: string; oauth_token_secret: string };
} catch (error) {
console.error("Error:", error);
throw error;
}
}
const createXMedia = async (link:string, authData: { oauth_token: string; oauth_token_secret: string }) => {
const url = "https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image";
const token = {
key: authData.oauth_token,
secret: authData.oauth_token_secret,
};
const headers = oauth.toHeader(
oauth.authorize(
{
url,
method: "POST",
},
token,
),
);
const mediaFile = await fetch(link).then((e) => e.arrayBuffer());
const mediaResponse = await fetch(url, {
headers: {
Authorization: headers["Authorization"],
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST",
body: JSON.stringify({ media: Buffer.from(mediaFile).toString("binary") }),
});
await handleErrorCode(mediaResponse);
const mediaResponseBody: IXMediaPost = await mediaResponse.json();
return mediaResponseBody;
};
handleError code just check if the status is an error and prints the text, but essentially the API is returning an unable to authenticate you error 32. Tried on insomnia with the same headers etc.. get the same result
enter image description here
These are the permissions that i’m requesting, so nothing should be missing. Kinda lost here so would appreciate any help
Am expecting the API to return a 2xx code and return a media_id. Have tried following a bunch of tutorials, reading the guides etc.. but nothing seems to be working