Перейти к основному содержимому

WhatsApp Integration API

The WhatsApp Integration API enables secure messaging capabilities through WhatsApp Web API. This implementation provides connection management, QR code scanning for authentication, and message sending functionality.

Overview

This API provides several main operations:

  • WhatsApp Connection Management
  • QR Code Generation and Scanning
  • Message Sending
  • Connection Status Checking
  • Rate Limiting

Connection Flow

sequenceDiagram
participant App as Web App
participant API as Backend API
participant WA as WhatsApp
participant Phone as WhatsApp Phone

App->>API: 1. Get WhatsApp Status
API-->>App: Return connection status & QR if needed
Alt Not Connected
Phone->>App: 2. Scan QR Code
WA-->>API: 3. Establish Connection
API-->>App: Return success status
End
App->>API: 4. Send Messages
API->>WA: Forward messages
WA-->>Phone: Deliver messages

API Reference

Check WhatsApp Status

Retrieves the current connection status and QR code if needed for connection.

query WhatsAppStatus {
whatsAppStatus {
connected
qrCode
qrCodeSvg
}
}

Response

{
"data": {
"whatsAppStatus": {
"connected": false,
"qrCode": "base64_encoded_qr_code",
"qrCodeSvg": "data:image/png;base64,..."
}
}
}

Connect WhatsApp

Initiates a WhatsApp connection. If not already connected, generates a new QR code.

mutation WhatsAppConnect {
whatsAppConnect
}

Disconnect WhatsApp

Disconnects from WhatsApp and cleans up the session.

mutation WhatsAppDisconnect {
whatsAppDisconnect
}

Send WhatsApp Message

Sends a message to a specified phone number. Requires active WhatsApp connection.

mutation SendWhatsAppNotification($phoneNumber: String!, $message: String!) {
sendWhatsAppNotification(phoneNumber: $phoneNumber, message: $message)
}

Variables

{
"phoneNumber": "+1234567890",
"message": "Hello from OrbVPN!"
}

Test WhatsApp Connection

Tests the connection by sending a test message to a specified number.

mutation TestWhatsAppConnection($phoneNumber: String!) {
testWhatsAppConnection(phoneNumber: $phoneNumber)
}

Implementation Guide

Connection Management

  1. Check connection status:
const response = await client.query({
query: gql`
query CheckStatus {
whatsAppStatus {
connected
qrCode
qrCodeSvg
}
}
`,
});

if (!response.data.whatsAppStatus.connected) {
// Display QR code for scanning
const qrCode = response.data.whatsAppStatus.qrCodeSvg;
// Show QR code to user
}
  1. Handle connection:
// Connect to WhatsApp
const connectResponse = await client.mutate({
mutation: gql`
mutation Connect {
whatsAppConnect
}
`,
});

// Monitor status
const statusInterval = setInterval(async () => {
const statusResponse = await client.query({
query: gql`
query CheckStatus {
whatsAppStatus {
connected
}
}
`,
});

if (statusResponse.data.whatsAppStatus.connected) {
clearInterval(statusInterval);
// Handle successful connection
}
}, 2000);
  1. Send messages:
const sendMessage = async (phoneNumber: string, message: string) => {
try {
const response = await client.mutate({
mutation: gql`
mutation SendMessage($phoneNumber: String!, $message: String!) {
sendWhatsAppNotification(phoneNumber: $phoneNumber, message: $message)
}
`,
variables: { phoneNumber, message },
});

return response.data.sendWhatsAppNotification;
} catch (error) {
console.error("Failed to send message:", error);
throw error;
}
};

Rate Limiting

The system implements rate limiting with the following constraints:

  • Per Phone Number:

    • 10 messages per minute
    • 100 messages per hour
  • Global Limits:

    • 1000 messages per day
    • Maximum 5 concurrent connections

Error Handling

Common errors and their meanings:

Error CodeDescriptionSolution
NOT_CONNECTEDWhatsApp is not connectedInitiate connection and scan QR code
RATE_LIMITEDRate limit exceededWait for rate limit reset
INVALID_NUMBERInvalid phone number formatCheck number format (should include country code)
SEND_FAILEDMessage sending failedCheck connection and retry
QR_EXPIREDQR code has expiredRequest new QR code

Best Practices

  1. Connection Management

    • Monitor connection status regularly
    • Implement automatic reconnection
    • Store session data securely
    • Handle disconnections gracefully
  2. Message Sending

    • Validate phone numbers
    • Implement retry logic
    • Queue messages during connection issues
    • Monitor delivery status
  3. Security

    • Secure session storage
    • Regular session rotation
    • Rate limiting enforcement
    • Access control implementation
  4. User Experience

    • Clear connection status indication
    • Easy QR code scanning process
    • Proper error messaging
    • Message delivery confirmation

Session Management

The system maintains WhatsApp sessions with the following characteristics:

  • Sessions persist across server restarts
  • Automatic reconnection attempts
  • Maximum 5 reconnection attempts
  • 30-second delay between attempts

Phone Number Format

Phone numbers should be formatted as follows:

  • Include country code
  • Remove any special characters
  • Examples:
    • US: "14155552671"
    • UK: "447911123456"
    • International: "[:country_code][:number]"

Message Formats

Supported message types:

  1. Text Messages

    • Maximum length: 4096 characters
    • Unicode support
    • Line break support
  2. Media Messages (Future)

    • Images
    • Documents
    • Audio
    • Video

Security Considerations

  • QR codes expire after scanning
  • Sessions are encrypted
  • Rate limiting per phone number
  • IP-based restrictions
  • Access control per user/role
  • Message logging and auditing

Troubleshooting

Common issues and solutions:

  1. Connection Issues

    • Check internet connectivity
    • Verify WhatsApp phone is online
    • Ensure QR code is fresh
    • Check rate limits
  2. Message Failures

    • Verify phone number format
    • Check connection status
    • Monitor rate limits
    • Review error messages
  3. Session Problems

    • Clear existing session
    • Reconnect with new QR code
    • Check storage permissions
    • Verify file system access

Monitoring

Key metrics to monitor:

  • Connection status
  • Message success rate
  • Rate limit usage
  • Error frequency
  • Session duration
  • QR code scans
  • Message queue size