使用 Nodemailer 和 Firebase Cloud Functions 时错误授予 OAuth2 无效

Error invalid grant OAuth2 with Nodemailer and Firebase Cloud Functions

我有下一个问题。我使用 NodeJs、Typescript、OAuth2、Gmail 在 firebase 云函数中实现。我遵循了一个类似这样的教程 https://dev.to/chandrapantachhetri/sending-emails-securely-using-node-js-nodemailer-smtp-gmail-and-oauth2-g3a

我会在下面附上代码。问题是刷新令牌以某种方式被撤销或过期,它持续大约 8 天。我的解决方法是在 https://developers.google.com/oauthplayground 中生成一个新的刷新令牌,如本教程中所述,并修复了大约 8 天的新访问令牌请求。我试了很多东西都没有成功。

云函数日志中提供的错误与此类似,还有很多其他无法理解的东西

{
   error: 'invalid_grant',
   error_description: 'Token has been expired or revoked.' 
}

有人可以帮我解决这个问题吗?

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as nodemailer from "nodemailer";
import * as goole from "googleapis";
admin.initializeApp();

// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript

export const mailPedidos = functions.firestore
  .document("example/{exampleId}")
  .onCreate(async (snapshot, context) => {

    //business logic removed
    let name = "Carl";        
    let mail = "example@gmail.com";
    const mailOptions = {
      from: "Kuxon <fromExample@gmail.com>",
      to: mail,
      subject: "Example Subject",
      html: `<p style="font-size: 16px;">Name: ${name} </p>
            `, // email content in HTML
    };

    try {
      const CLIENT_ID =
        "CLIENTID";
      const CLIENT_SECRET = "CLIENTSECRET";
      const REDIRECT_URI = "https://developers.google.com/oauthplayground";
      const REFRESH_TOKEN =
        "REFRESHTOKEN";

      const oAuth2Client = new goole.google.auth.OAuth2(
        CLIENT_ID,
        CLIENT_SECRET,
        REDIRECT_URI
      );
      oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

      const accessToken = await oAuth2Client.getAccessToken();
      console.log("Access Token: " + accessToken);

      let aT: string | undefined = "";

      if (accessToken.token !== null) {
        aT = accessToken.token;
      }

      console.log("Access Token token: " + aT);

      const transporter = nodemailer.createTransport({
        service: "gmail",
        auth: {
          type: "OAuth2",
          user: "example@gmail.com",
          clientId: CLIENT_ID,
          clientSecret: CLIENT_SECRET,
          refreshToken: REFRESH_TOKEN,
          accessToken: aT,
        },
      });

      // returning result
      transporter.sendMail(mailOptions, (error: any, info: any) => {
        if (error) {
          console.log(error.toString());
        }
        console.log("Sended");
      });
    } catch (error) {
      console.log({ error });
    }
    return snapshot;
  }); 

这可能是因为 google 云平台的配置。

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

link 到相关线程:Do google refresh tokens expire?