Notion error Invalid code: this code has already been used

28 views Asked by At

I am trying to create a notion access for my web application. The problem is I can successfully generate the access token, but when i use its its says its already used, how to fix it, my backend code is as below.

in front end after successful authentication, it will trigger the Api.

app.get("/login/:code", async (req, res) => {
  const { code } = req.params;
  console.log(code);
>! Generate an access token with the code we got earlier and the client_id and client_secret we retrived earlier
  try {
    const resp = await axios({
      method: "POST",
      url: "https://api.notion.com/v1/oauth/token",
      auth: { username: notionClientId, password: notionClientSecret },
      headers: { "Content-Type": "application/json" },
      data: { code, grant_type: "authorization_code" },
    });
>! You want to save resp.data.workspace_id and resp.data.access_token if you want to make requests later with this Notion account (otherwise they'll need to reauthenticate)
    console.log(resp.data.access_token, "this is the access token");
>! Use the access token we just got to search the user's workspace for databases
    console.log("response>>>>>>>>>", resp.data);
    if (!resp.data.access_token) {
      throw new Error("No Access Token");
    }
    const AccessToken = resp.data.access_token;
    const { data } = await axios({
      method: "POST",
      url: "https://api.notion.com/v1/search",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${AccessToken}`,
        "Notion-Version": "2022-02-22",
      },
      data: { filter: { property: "object", value: "database" } },
    });

    res.json({
      results: data?.results,
      access_token: resp.data.access_token,
    });
  } catch (error) {
    console.error("Error during Notion API request:", error);
  }
});
0

There are 0 answers