pedroslopez / whatsapp-web.js

A WhatsApp client library for NodeJS that connects through the WhatsApp Web browser app
https://wwebjs.dev
Apache License 2.0
14.93k stars 3.55k forks source link

Login failed using RemoteAuth cache #2452

Open yuzhongxingke opened 12 months ago

yuzhongxingke commented 12 months ago

Is there an existing issue for this?

Describe the bug

When using RemoteAuth to cache login status information, after scanning and logging in, I receive the message 'remote_session_saved'. When I resume logging in, but the end-to-end verification fails, it will automatically jump to the scanning page

Expected behavior

Expect to successfully log in to WhatsApp when restoring [RemoteAuth] login

Steps to Reproduce the Bug or Issue

  1. Start mongodb
  2. Start the nodejs service
  3. Open client HTML
  4. Scan code using WhatsApp
  5. Resume login operation

Relevant Code

service:

const MONGODB_URI = 'mongodb://127.0.0.1:27017/test';
mongoose.connect(MONGODB_URI).then(() => {
    console.log('Connected to database');
     store = new MongoStore({ mongoose: mongoose });
    //  console.log(store);
});

The following code is used for scanning related business
const createWhatsappSession = async (id,socket) => {
    const client = new Client({        
        puppeteer: {
            headless: true,
        },
        authStrategy: new RemoteAuth({
            clientId: id,
            store: store,
            backupSyncIntervalMs: 300000
        })
    });
    client.on('qr', (qr) => {
        socket.emit('qr',{qr});
    });
    client.on('remote_session_saved',()=>{
        console.log('remote-session saved');
        socket.emit('remote_session_saved',{
            message:'remote session saved'
        });
    })
    client.initialize();
}

The following code is used to restore WhatsApp login
const getWhatsappSession = async (id,socket) => {
    const client = new Client({
        puppeteer: {
            headless: false,
        },
        authStrategy: new RemoteAuth({
            clientId: id,
            store: store,
            backupSyncIntervalMs: 300000
        })
    });
    client.initialize();
}

Browser Type

Chromium

WhatsApp Account Type

Standard

Does your WhatsApp account have multidevice enabled?

Yes, I am using Multi Device

Environment

OS: windows10 whatsapp-web.js version: 1.22.1 or 1.22.2-alpha.0 Node.js Version: v14.20.0

Additional context

No response

yuzhongxingke commented 11 months ago

Has anyone also encountered this problem? Why does restoring login automatically redirect to the scan page? Can you help me! Thank you!

Brianderrick commented 11 months ago

I'm sorry, but I need more information to understand the problem you're facing. Could you please provide more details about the platform or application you're using and the specific issue you're encountering? Additionally, if you can provide any error messages or steps you've taken before encountering the problem, it would be helpful in diagnosing the issue and providing assistance.

yuzhongxingke commented 11 months ago

@Brianderrick Thank you for your reply. My current development scenario includes a client and a server, which mainly use RemoteAuth to receive multiple device login information and store it in mongodb. The client will display the WhatsApp QR code. When I successfully scan the code, it will trigger the server's RemoteAuth save process. When I open the client again, it will automatically restore the login status of my last scan (so that I don't need to log in again). The current problem is that scanning the code and storing mongodb are normal, but it fails when the login status is finally restored (it will enter the scanning page again instead of the chat page). This is not the result I expected. How can I solve this problem? Here is my detailed code:

`const express = require('express'); const app = express(); const fs = require('fs'); const bodyParser = require('body-parser'); const { Client,RemoteAuth,MessageMedia,LegacySessionAuth } = require('whatsapp-web.js'); const { MongoStore } = require('wwebjs-mongo'); const mongoose = require('mongoose'); const {Server} = require('socket.io'); const http = require('http'); const cors = require('cors') const server = http.createServer(app); app.use(cors()) app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', ''); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); let store; const MONGODB_URI = 'mongodb://127.0.0.1:27017/test'; const io = new Server(server,{ cors: { origin: '', methods: ['GET', 'POST'] }, }) app.use(bodyParser.json()); mongoose.connect(MONGODB_URI).then(() => { console.log('Connected to database'); store = new MongoStore({ mongoose: mongoose }); });

app.listen(4000, () => { console.log('API server started on port '); }); server.listen(3001, () => { console.log('Socket server started on port '); }); const allsessions = {}; const createWhatsappSession = async (id,socket) => { const client = new Client({ puppeteer: { headless: true, }, authStrategy: new RemoteAuth({ clientId: id, store: store, backupSyncIntervalMs: 300000 }) }); client.on('qr', (qr) => { socket.emit('qr',{qr}); }); client.on('authenticated', (session) => { console.log('AUTHENTICATED:::', session); }) client.on('ready', () => { console.log('READY--1'); allsessions[id] = client; socket.emit('ready',{id,message:'client is ready'}); }); client.on('remote_session_saved',()=>{ console.log('remote-session saved'); socket.emit('remote_session_saved',{ message:'remote session saved' }); }) client.initialize(); }

const getWhatsappSession = async (id,socket) => { const client = new Client({ puppeteer: { headless: false, }, authStrategy: new RemoteAuth({ clientId: id, store: store, backupSyncIntervalMs: 300000 }) }); client.initialize(); }

io.on('connection', (socket) => { socket.on('disconnect', () => { console.log('user disconnected'); }); socket.on('getsession', (data) => { console.log('getsession',data); var obj = JSON.parse(data) const {id} = obj.uuid; getWhatsappSession(id,socket); }); socket.on('connected', (data) => { console.log('connected to the server',data); socket.emit('hello','hello from the server'); }); socket.on('createSession', (data) => { console.log('creating session for a user', data); var obj = JSON.parse(data) const {id} = obj.uuid; createWhatsappSession(id, socket) .then(() => { const successMessage = "Session created successfully"; socket.emit('sessionCreated', { message: successMessage }); }) .catch((error) => { const errorMessage = "Failed to create session"; socket.emit('sessionCreationFailed', { message: errorMessage }); }); }); });`

"dependencies": { "body-parser": "^1.20.2", "cors": "^2.8.5", "express": "^4.18.2", "mongoose": "^7.3.0", "react-qr-code": "^2.0.11", "socket.io": "^4.6.2", "socket.io-client": "^4.6.2", "whatsapp-web.js": "^1.22.1", "wwebjs-mongo": "^1.1.0" }

Node versions have been tested from 14 to 18 Whatsapp-web.js versions have also been tested from 1.21.1 to 1.22.2 alpha.0

Operating steps (both the client and server are deployed on the same computer):

  1. When the server receives the createSession message, it will create a Client and return the WhatsApp QR code

  2. After the user successfully scans the code and logs in, Remote Auth will cache the login status information to mongodb

  3. When the client opens the page again, a getsession message will be sent. After receiving the information, the server will restore the login status and pop up the WhatsApp webpage for end-to-end verification (this step will now fail and cannot be verified)

abhikhedekar4241 commented 11 months ago

Hi @yuzhongxingke, were you able to find a solution on this by any chance?

mdvazid commented 11 months ago

Facing the Same issue , While fetching Session from mongo i m getting logged out @yuzhongxingke @Brianderrick did you guys find any solution for this ?

abhikhedekar4241 commented 11 months ago

I referred to implementation in this repository. This fixed for me. I am using S3Store for RemoteAuth

https://github.com/nkbhasker/nest-whatsapp

bymarcelo commented 1 month ago

I fixed it in an official/recommended way on this commit: https://github.com/pedroslopez/whatsapp-web.js/pull/3200 Encourage maintainers to approve the PR.

While the PR is not approved, you can use my fork like this:

npm install github:bymarcelo/whatsapp-web.js#fix-remote-auth-unzip

NOTE: Recommended to use node version >= 18, tested v20