Lấy token google

 https://developers.google.com/oauthplayground/


🚀 Cách lấy CLIENT_ID + CLIENT_SECRET (Gmail API)

🔹 Bước 1: Tạo project

Vào: https://console.cloud.google.com/

Chọn New Project

Đặt tên → Create

🔹 Bước 2: Bật Gmail API

Vào APIs & Services → Library

Tìm: Gmail API

Click → Enable

🔹 Bước 3: Tạo OAuth Client

Vào APIs & Services → Credentials

Click Create Credentials → OAuth Client ID


👉 Nếu chưa config OAuth:


Chọn Configure consent screen

Chọn External

Điền:

App name (ví dụ: Mail Tool)

Email của bạn

Save

🔹 Bước 4: Tạo credentials

Application type: Web application

Redirect URI:

https://developers.google.com/oauthplayground


👉 Sau đó bạn sẽ thấy:


CLIENT_ID = xxx

CLIENT_SECRET = xxx

🔑 Bước 5: Lấy REFRESH_TOKEN (quan trọng)


Bạn vào:

👉 https://developers.google.com/oauthplayground


Setup:

Click ⚙️ (góc phải)

Tick:

Use your own OAuth credentials

Dán:

CLIENT_ID

CLIENT_SECRET

Lấy token:

Chọn scope:

https://mail.google.com/

Click Authorize APIs

Login Gmail

Click Exchange authorization code for tokens


👉 Bạn sẽ nhận:


refresh_token = xxxxxxxxx


const { google } = require("googleapis");


// ===== CONFIG =====

const CLIENT_ID = "YOUR_CLIENT_ID";

const CLIENT_SECRET = "YOUR_CLIENT_SECRET";

const REDIRECT_URI = "https://developers.google.com/oauthplayground";

const REFRESH_TOKEN = "YOUR_REFRESH_TOKEN";


// filter giống code bạn

const SUBJECT_FILTER = "Microsoft account security code";


// ===== AUTH =====

const oAuth2Client = new google.auth.OAuth2(

    CLIENT_ID,

    CLIENT_SECRET,

    REDIRECT_URI

);


oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });


const gmail = google.gmail({ version: "v1", auth: oAuth2Client });


// ===== GET EMAIL LIST =====

async function getUnreadMails() {

    try {

        const res = await gmail.users.messages.list({

            userId: "me",

            q: `is:unread subject:"${SUBJECT_FILTER}"`,

            maxResults: 10,

        });


        return res.data.messages || [];

    } catch (err) {

        console.error("Error getUnreadMails:", err.message);

        return [];

    }

}


// ===== GET MAIL DETAIL =====

async function getMailContent(messageId) {

    try {

        const res = await gmail.users.messages.get({

            userId: "me",

            id: messageId,

        });


        const parts = res.data.payload.parts || [];


        let body = "";


        for (const part of parts) {

            if (part.mimeType === "text/html") {

                body = Buffer.from(part.body.data, "base64").toString("utf8");

            }

        }


        return body;

    } catch (err) {

        console.error("Error getMailContent:", err.message);

        return "";

    }

}


// ===== PARSE OTP (custom giống bạn) =====

function extractOTP(html) {

    if (!html) return null;


    // ví dụ Microsoft code: 123456

    const match = html.match(/\b\d{4,8}\b/);

    return match ? match[0] : null;

}


// ===== MARK AS READ =====

async function markAsRead(messageId) {

    await gmail.users.messages.modify({

        userId: "me",

        id: messageId,

        requestBody: {

            removeLabelIds: ["UNREAD"],

        },

    });

}


// ===== MAIN FUNCTION =====

async function getOtpFromGmail() {

    const messages = await getUnreadMails();


    if (messages.length === 0) {

        console.log("No new mail");

        return [];

    }


    let results = [];


    for (const msg of messages) {

        const html = await getMailContent(msg.id);

        const otp = extractOTP(html);


        if (otp) {

            results.push({

                id: msg.id,

                otp,

            });


            // mark read giống IMAP markSeen

            await markAsRead(msg.id);

        }

    }


    return results;

}


// ===== RUN TEST =====

(async () => {

    const data = await getOtpFromGmail();

    console.log("OTP LIST:", data);

})();

Nhận xét

Bài đăng phổ biến từ blog này

Các cách fix mongodb khi bị lỗi

Dạo này bận chạy deadline quá nên post link trễ