whatsapp-web.js icon indicating copy to clipboard operation
whatsapp-web.js copied to clipboard

feat: Switch between QR or phone number pairing method

Open MobCode100 opened this issue 7 months ago • 8 comments

PR Details

The ability to change the preferred login/authentication method either use QR code or pair with a phone number (Linked devices -> Link a device -> Link with phone number instead).

Description

  1. Added new option pairWithPhoneNumber which is an object containing the parameters for requestPairingCode function in Client.js. The attributes of this object are:
    • phoneNumber: Phone number in international, symbol-free format <COUNTRY_CODE><PHONE_NUMBER>
    • showNotification: Show notification to pair for the specified phone number
    • intervalMs: The interval in milliseconds on how frequent to generate pairing code (WhatsApp default to 3 minutes)
  2. On code and window.onCodeReceivedEvent event will run a callback once a code has been generated.

The inject function in Client.js will check if the phoneNumber option is set, and will switch to phone number pairing mode without running any QR related functions. intervalMs is the time to wait for the next generation of code to mitigate the problem of expired code.

Related Issue

closes #1787 resolves #3316

Motivation and Context

  1. Make it easier to user the requestPairingCode without having to manually utilize the function
  2. The code feels cleaner this way, normalizing the authentication method of QR and phone number
  3. Automatically generate new pairing code on/before expired.

How Has This Been Tested

To run or test this feature, run node app.js where app.js contains the following code:

const { Client, LocalAuth } = require('whatsapp-web.js');
const client = new Client(
    {
        puppeteer: {
            args: ['--no-sandbox'],
            headless: false
        },
        authStrategy: new LocalAuth({ dataPath: "." }),
        pairWithPhoneNumber: {
            phoneNumber: "12324354646",
            showNotification: true,
            intervalMs: 180000
        },
    }
);
client.on('code', (code) => {
    console.log("Linking code:",code);
});
client.initialize();

The pairing code should be displayed to the terminal every 3 minutes. Developer tools are used to inspect some variables while running in non-headless mode. So far, no issues have been encountered during testing on QR code functions or any other existing features.

Types of changes

  • [ ] Dependency change
  • [ ] Bug fix (non-breaking change which fixes an issue)
  • [x] New feature (non-breaking change which adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • [x] My code follows the code style of this project.
  • [x] I have updated the documentation accordingly (index.d.ts).

MobCode100 avatar Jul 03 '24 13:07 MobCode100