Socket
Book a DemoInstallSign in
Socket

whatsapp-number-checker

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

whatsapp-number-checker

A wrapper for the RapidAPI WhatsApp Data API with bulk checking and rate limiting support

latest
npmnpm
Version
1.1.0
Version published
Maintainers
1
Created
Source

WhatsApp Number Checker

A comprehensive wrapper for the RapidAPI WhatsApp Data API featuring advanced dual rate limiting, automatic retries, and bulk number verification with intelligent queue management.

Features

  • Dual Rate Limiting: Supports both window and monthly rate limits automatically extracted from API headers
  • Automatic Retries: Intelligent rate limit error handling with exponential backoff
  • Bulk Verification: Process multiple numbers with progress tracking and advanced options
  • Real-time Monitoring: Track API usage through response headers analysis
  • Required API Key: Mandatory API key validation in constructor
  • TypeScript: Fully typed for enhanced developer experience
  • Smart Queue: Automatic request management with dynamic adaptation
  • Phone Validation: Built-in phone number validation using google-libphonenumber

Installation

npm install whatsapp-number-checker

Setup

First, obtain an API key from RapidAPI WhatsApp Data.

⚠️ Important: The API key is required in the constructor and mandatory for accessing all methods.

Basic Usage

import { WhatsAppChecker } from 'whatsapp-number-checker';

const checker = new WhatsAppChecker({
  apiKey: 'YOUR_RAPIDAPI_KEY_HERE', // REQUIRED
  throwOnLimit: false, // Don't throw error after retries
  timeout: 15000, // 15 second timeout
  maxRetries: 3, // Retry up to 3 times on rate limit
  retryDelay: 1000 // Base delay between retries
});

// Check a single number (with automatic retries)
const result = await checker.checkNumber('+1234567890');
console.log(result);

Dual Rate Limiting System

The system automatically handles two types of rate limits extracted from API headers:

Window Rate Limit (Short-term)

  • Limit: 5 requests per window
  • Headers: x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset

Monthly Rate Limit (Long-term)

  • Limit: 5000 requests per month
  • Headers: x-ratelimit-requests-limit, x-ratelimit-requests-remaining, x-ratelimit-requests-reset
const checker = new WhatsAppChecker({ apiKey: 'YOUR_API_KEY' });

// Monitor current status for both limits
const rateLimitInfo = checker.getRateLimitInfo();
if (rateLimitInfo) {
  console.log('Window Rate Limit:');
  console.log(`  Used: ${rateLimitInfo.used}/${rateLimitInfo.limit}`);
  console.log(`  Remaining: ${rateLimitInfo.remaining}`);
  
  console.log('Monthly Rate Limit:');
  console.log(`  Used: ${rateLimitInfo.monthlyUsed}/${rateLimitInfo.monthlyLimit}`);
  console.log(`  Remaining: ${rateLimitInfo.monthlyRemaining}`);
}

// View current interval between requests (adapts automatically)
console.log(`Current interval: ${checker.getCurrentRateInterval()}ms`);

Bulk Verification with Advanced Options

const numbers = ['+1234567890', '+0987654321', '+1122334455'];

const bulkResult = await checker.checkBulk(numbers, {
  onProgress: (completed, total, current) => {
    console.log(`Progress: ${completed}/${total}`);
    
    if (current.data && !('error' in current.data)) {
      const data = current.data as any;
      console.log(`✅ ${current.number}: WhatsApp Contact: ${data.isWAContact}`);
    } else {
      console.log(`❌ ${current.number}: Error`);
    }
  },
  onRateLimit: (rateLimitInfo) => {
    console.log('Rate limit detected:');
    console.log(`  Window: ${rateLimitInfo.used}/${rateLimitInfo.limit}`);
    console.log(`  Monthly: ${rateLimitInfo.monthlyUsed}/${rateLimitInfo.monthlyLimit}`);
  },
  stopOnError: false
});

console.log('Summary:', bulkResult.summary);

Advanced Configuration

const checker = new WhatsAppChecker({
  apiKey: 'YOUR_API_KEY', // REQUIRED
  throwOnLimit: true, // Throw RateLimitError after all retries
  timeout: 15000,
  maxRetries: 5, // Up to 5 retries on rate limit
  retryDelay: 2000, // 2 second base delay (with exponential backoff)
  baseURL: 'https://whatsapp-data1.p.rapidapi.com' // Custom URL
});

try {
  const result = await checker.checkNumber('+1234567890');
} catch (error) {
  if (error.name === 'RateLimitError') {
    console.log('Rate limit exhausted after retries:', error.rateLimitInfo);
  }
}

API Reference

WhatsAppChecker

Constructor

new WhatsAppChecker(config: WhatsAppCheckerConfig)

Configuration

interface WhatsAppCheckerConfig {
  apiKey: string;              // Your RapidAPI key (REQUIRED)
  baseURL?: string;            // API base URL
  throwOnLimit?: boolean;      // Throw error after retries (default: false)
  timeout?: number;            // Timeout in ms (default: 10000)
  maxRetries?: number;         // Max retries on rate limit (default: 3)
  retryDelay?: number;         // Base delay between retries in ms (default: 1000)
}

Methods

checkNumber(number: string): Promise<CheckResult>

Verifies a single WhatsApp number with automatic retries and phone validation.

checkBulk(numbers: string[], options?: BulkCheckOptions): Promise<BulkCheckResult>

Verifies multiple numbers with advanced options and progress tracking.

getRateLimitInfo(): RateLimitInfo | null

Gets current rate limit information extracted from API headers (both window and monthly).

getCurrentRateInterval(): number

Gets current interval between requests (adapts dynamically based on rate limits).

getQueueLength(): number

Gets number of pending requests in queue.

clearQueue(): void

Clears pending request queue.

getLastResponseHeaders(): any

Gets the last response headers for debugging purposes.

Response Types

CheckResult

interface CheckResult {
  number: string;
  data: WhatsappPersonResponse | WhatsappBusinessResponse | { error: string; success: null } | null;
  error?: string;
  rateLimitInfo?: RateLimitInfo;
}

RateLimitInfo (Dual Rate Limits)

interface RateLimitInfo {
  // Window rate limit (short-term)
  remaining: number;           // From x-ratelimit-remaining
  limit: number;              // From x-ratelimit-limit
  reset: number;              // From x-ratelimit-reset (timestamp)
  used: number;               // Calculated: limit - remaining
  
  // Monthly rate limit (long-term)
  monthlyRemaining: number;    // From x-ratelimit-requests-remaining
  monthlyLimit: number;        // From x-ratelimit-requests-limit
  monthlyReset: number;        // From x-ratelimit-requests-reset (timestamp)
  monthlyUsed: number;         // Calculated: monthlyLimit - monthlyRemaining
}

WhatsApp API Response Types

Personal Account Response

interface WhatsappPersonResponse {
  _id: string;
  number: string;
  about: string;
  countryCode: string;
  isBlocked: boolean;
  isBusiness: boolean;
  isEnterprise: boolean;
  isGroup: boolean;
  isMe: boolean;
  isMyContact: boolean;
  isUser: boolean;
  isWAContact: boolean;       // Main indicator: Has WhatsApp
  name: string;
  phone: string;
  profilePic: string;
  pushname: string;
  shortName: string;
  type: string;
  // ... other fields
}

Business Account Response

interface WhatsappBusinessResponse {
  number: string;
  isBusiness: boolean;
  isEnterprise: boolean;
  isUser: boolean;
  isWAContact: boolean;       // Main indicator: Has WhatsApp
  name: string;
  shortName: string;
  verifiedLevel: number;
  verifiedName: string;
  countryCode: string;
  phone: string;
  businessProfile: BusinessProfile;
  // ... other fields
}

BulkCheckOptions

interface BulkCheckOptions {
  onProgress?: (completed: number, total: number, current: CheckResult) => void;
  onRateLimit?: (info: RateLimitInfo) => void;
  stopOnError?: boolean;
  maxRetries?: number;
}

BulkCheckResult

interface BulkCheckResult {
  results: CheckResult[];
  summary: {
    total: number;
    successful: number;
    failed: number;
    rateLimited: number;
  };
  rateLimitInfo?: RateLimitInfo;
}

Error Handling and Retries

RateLimitError with Automatic Retries

const checker = new WhatsAppChecker({
  apiKey: 'YOUR_API_KEY',
  maxRetries: 3,
  throwOnLimit: true
});

try {
  const result = await checker.checkNumber('+1234567890');
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log('Rate limit exhausted after 3 retries');
    console.log('Limit info:', error.rateLimitInfo);
    console.log('Window reset:', new Date(error.rateLimitInfo.reset * 1000));
    console.log('Monthly reset:', new Date(error.rateLimitInfo.monthlyReset * 1000));
  }
}

Retry Strategy

  • First attempt: Normal request
  • Rate limit detected: Extract info from headers
  • Calculate delay: Use reset time or exponential backoff
  • Retry: Up to maxRetries times
  • Fail or continue: Based on throwOnLimit setting

Window vs Monthly Handling:

  • Window limit hit: Short retry delays, waits for window reset
  • Monthly limit hit: Longer exponential backoff, doesn't wait for monthly reset

Best Practices

  • API Key: Always provide a valid API key
  • Rate Limiting: Trust the dynamic system, don't configure manual limits
  • Retries: Configure maxRetries based on your needs (3-5 recommended)
  • Monitoring: Use getRateLimitInfo() to monitor status
  • Bulk Operations: Use progress callbacks for user interfaces
  • Phone Format: Numbers can be with or without + prefix, the library handles formatting
  • Error Handling: Check for both API errors and request failures

Migration from Previous Version

If you were using the previous version with manual rateLimit:

// BEFORE (v1.0.0)
const checker = new WhatsAppChecker({
  apiKey: 'key',
  rateLimit: 2 // Manual configuration
});

// NOW (v1.1.0+)
const checker = new WhatsAppChecker({
  apiKey: 'key', // REQUIRED
  maxRetries: 3, // New: automatic retries
  retryDelay: 1000 // New: delay between retries
  // rateLimit is now extracted automatically from headers
  // Supports both window and monthly limits
});

Testing

Test Scripts

The library includes test scripts to validate functionality:

Single Number Test

# Test a single number
npm run test-api <API_KEY> <PHONE_NUMBER> [--verbose]

# Examples
npm run test-api "8ecfc15d5dmsh..." "+1234567890"
npm run test-api "8ecfc15d5dmsh..." "+59898297150" --verbose

Bulk Test (Multiple Numbers)

# Test multiple numbers
npm run test-bulk <API_KEY> <PHONE_1> [PHONE_2] [...] [--verbose] [--stop-on-error]

# Examples
npm run test-bulk "8ecfc15d5dmsh..." "+1234567890" "+0987654321" "+1122334455"
npm run test-bulk "8ecfc15d5dmsh..." "+1234567890" "+0987654321" --verbose
npm run test-bulk "8ecfc15d5dmsh..." "+1234567890" "+0987654321" --stop-on-error --verbose

Available flags:

  • --verbose, -v: Shows detailed information including rate limit headers
  • --stop-on-error: Stops processing on first error

Bulk test displays:

  • ✅ Real-time progress for each number
  • 📊 Detailed rate limit information (window and monthly)
  • 📈 Final success/error statistics
  • ⏱️ Total duration and request intervals
  • 🚨 Rate limit alerts

Complete Examples

See:

  • examples.ts - Basic and advanced examples
  • example-env.ts - Usage with environment variables

Contributing

Contributions are welcome! Please:

  • Fork the repository
  • Create a feature branch
  • Add tests for new functionality
  • Submit a pull request

License

MIT

Keywords

whatsapp

FAQs

Package last updated on 19 Jun 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts