PHP code example of chengkangzai / laravel-waha-saloon-sdk

1. Go to this page and download the library: Download chengkangzai/laravel-waha-saloon-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chengkangzai / laravel-waha-saloon-sdk example snippets


return [
    'base_url' => env('WAHA_BASE_URL', ''),
    'api_key' => env('WAHA_API_KEY', ''),
];



use CCK\LaravelWahaSaloonSdk\Waha\Waha;

// 1. Create a WAHA client instance
$waha = new Waha();

// 2. Start a WhatsApp session (you'll need to scan QR code first time)
$sessionResponse = $waha->sessions()->startTheSession('default');

// 3. Send a text message
$messageResponse = $waha->sendText()->sendTextMessage(
    chatId: '[email protected]', // WhatsApp number with @c.us suffix
    text: 'Hello from Laravel WAHA SDK!',
    session: 'default',
    replyTo: null,
    linkPreview: null,
    linkPreviewHighQuality: null
);

// 4. Check if message was sent successfully
if ($messageResponse->successful()) {
    $messageData = $messageResponse->json();
    echo "Message sent! ID: " . $messageData['id'];
} else {
    echo "Failed to send message: " . $messageResponse->body();
}

use CCK\LaravelWahaSaloonSdk\Waha\Waha;

// Create a new WAHA client with default config (uses env vars)
$waha = new Waha();

// Or with a custom base URL and API key (overrides config)
$waha = new Waha(
    baseUrl: 'https://your-waha-instance.com',
    apiKey: 'your-api-key'
);

// Access different resources - each resource groups related API endpoints
$sessions = $waha->sessions();    // Session management
$chats = $waha->chats();         // Limited chat operations
$messages = $waha->sendText();   // Send text messages
$misc = $waha->misc();           // Most functionality (files, media, groups, etc.)
$contacts = $waha->contacts();   // Contact management
$overview = $waha->overview();   // Chat overview

// Get all active sessions (using misc resource)
$response = $waha->misc()->listAllSessions(null);
$sessions = $response->json();
foreach ($sessions as $session) {
    echo "Session: {$session['name']}, Status: {$session['status']}\n";
}

// Get detailed information about a specific session
$response = $waha->sessions()->getSessionInformation('default');
if ($response->successful()) {
    $session = $response->json();
    echo "Session Status: {$session['status']}\n";
    echo "Session Config: " . json_encode($session['config']) . "\n";
}

// Start a new session (first time 

// Send a simple text message
$response = $waha->sendText()->sendTextMessage(
    chatId: '[email protected]', // Individual chat
    text: 'Hello from Laravel WAHA SDK!',
    session: 'default',
    replyTo: null,
    linkPreview: null,
    linkPreviewHighQuality: null
);

// Send an image with caption (using misc resource)
$response = $waha->misc()->sendImage(
    chatId: '[email protected]',
    file: 'https://example.com/image.jpg', // URL or base64
    session: 'default',
    replyTo: null,
    caption: 'Check out this amazing image! 📸'
);

// Send an image from local file (base64)
$imageBase64 = base64_encode(file_get_contents('/path/to/image.jpg'));
$response = $waha->misc()->sendImage(
    chatId: '[email protected]',
    file: $imageBase64,
    session: 'default',
    replyTo: null,
    caption: 'Image from server storage'
);

// Send a document/file
$response = $waha->misc()->sendFile(
    chatId: '[email protected]',
    file: 'https://example.com/document.pdf', // URL or base64
    session: 'default',
    replyTo: null,
    caption: 'Important document'
);

// Send a video with caption
$response = $waha->misc()->sendVideo(
    chatId: '[email protected]',
    file: 'https://example.com/video.mp4',
    session: 'default',
    replyTo: null,
    asNote: false,
    caption: 'Watch this tutorial video!'
);

// Send voice message
$response = $waha->misc()->sendVoiceMessage(
    chatId: '[email protected]',
    file: 'https://example.com/audio.ogg', // URL or base64
    session: 'default',
    replyTo: null
);

// Send location
$response = $waha->misc()->chattingControllerSendLocation(
    chatId: '[email protected]',
    latitude: 37.7749,
    longitude: -122.4194,
    title: 'San Francisco Office',
    session: 'default',
    replyTo: null
);

// Send a poll
$pollData = [
    'name' => 'What\'s your favorite programming language?',
    'options' => ['PHP', 'JavaScript', 'Python', 'Java'],
    'selectableCount' => 1 // 1 for single choice, >1 for multiple
];
$response = $waha->misc()->sendPollWithOptions(
    chatId: '[email protected]',
    poll: $pollData,
    session: 'default',
    replyTo: null
);

// Check message delivery status
if ($response->successful()) {
    $messageData = $response->json();
    echo "Message sent successfully!\n";
    echo "Message ID: {$messageData['id']}\n";
    echo "Timestamp: {$messageData['timestamp']}\n";
} else {
    echo "Failed to send message: {$response->status()}\n";
    echo "Error: {$response->body()}\n";
}

// Get overview of all chats (->getChatsOverviewIncludesAllNecessaryThingsToBuildUiYourChatsOverviewPageChatIdNamePictureLastMessageSortingByLastMessageTimestamp(
    session: 'default',
    limit: null,
    offset: null,
    ids: null
);
$chats = $response->json();

foreach ($chats as $chat) {
    echo "Chat: {$chat['id']}\n";
    echo "Name: {$chat['name']}\n";
    echo "Last Message: {$chat['lastMessage']['body']}\n";
    echo "Unread Count: {$chat['unreadCount']}\n";
    echo "---\n";
}

// Get basic chat list
$response = $waha->misc()->getChats(
    session: 'default',
    sortBy: 'lastMessageTimestamp',
    sortOrder: 'desc',
    limit: '50',
    offset: '0'
);
$chatList = $response->json();

// Get messages from a specific chat with pagination
$response = $waha->chats()->getsMessagesInTheChat(
    session: 'default',
    chatId: '[email protected]',
    downloadMedia: 'true',
    limit: '50',
    offset: null,
    filterTimestampLte: null,
    filterTimestampGte: null,
    filterFromMe: null,
    filterAck: null
);
$messages = $response->json();

foreach ($messages as $message) {
    echo "From: {$message['from']}\n";
    echo "Text: {$message['body']}\n";
    echo "Time: {$message['timestamp']}\n";
    echo "Type: {$message['type']}\n"; // text, image, video, etc.
    echo "---\n";
}

// Mark chat as read
$response = $waha->chats()->readUnreadMessagesInTheChat(
    session: 'default',
    chatId: '[email protected]',
    messages: null,
    days: null
);

// Delete a specific message
$response = $waha->messages()->deletesMessageFromTheChat(
    session: 'default',
    chatId: '[email protected]',
    messageId: 'message_id_here'
);

// Clear all messages in a chat
$response = $waha->chats()->clearsAllMessagesFromTheChat(
    session: 'default',
    chatId: '[email protected]'
);

// Archive/unarchive a chat
$response = $waha->api()->archiveTheChat(
    session: 'default',
    chatId: '[email protected]'
);

$response = $waha->api()->unarchiveTheChat(
    session: 'default',
    chatId: '[email protected]'
);

// Get all contacts from the session
$response = $waha->contacts()->getAllContacts('default');
$contacts = $response->json();

foreach ($contacts as $contact) {
    echo "Name: {$contact['name']}\n";
    echo "Number: {$contact['id']}\n";
    echo "Is Business: " . ($contact['isBusiness'] ? 'Yes' : 'No') . "\n";
    echo "---\n";
}

// Get detailed information about a specific contact
$response = $waha->contacts()->getContactBasicInfo(
    session: 'default',
    contactId: '[email protected]'
);
$contact = $response->json();

echo "Contact Name: {$contact['name']}\n";
echo "Push Name: {$contact['pushname']}\n";

// Get contact's about info
$response = $waha->contacts()->getsTheContactAboutInfo(
    session: 'default',
    contactId: '[email protected]'
);
$about = $response->json();

// Check if a phone number exists on WhatsApp
$response = $waha->contacts()->checkPhoneNumberIsRegisteredInWhatsApp(
    session: 'default',
    phone: '1234567890'
);
$result = $response->json();

if ($result['numberExists']) {
    echo "Number exists on WhatsApp\n";
    echo "WhatsApp ID: {$result['numberExists']}\n";
} else {
    echo "Number does not exist on WhatsApp\n";
}

// You can also use misc resource to check number status
$response = $waha->misc()->checkNumberStatus(
    phone: '1234567890',
    session: 'default'
);

// Get contact's profile picture
$response = $waha->contacts()->getContactProfilePictureUrl(
    session: 'default',
    contactId: '[email protected]'
);
$profilePic = $response->json();

// Block a contact
$response = $waha->contacts()->blockContact(
    session: 'default',
    contactId: '[email protected]'
);

// Unblock a contact
$response = $waha->contacts()->unblockContact(
    session: 'default',
    contactId: '[email protected]'
);

// Get all groups you're part of
$response = $waha->misc()->getAllGroups(
    session: 'default',
    sortBy: null,
    sortOrder: null,
    limit: null,
    offset: null,
    exclude: null
);
$groups = $response->json();

foreach ($groups as $group) {
    echo "Group: {$group['name']}\n";
    echo "ID: {$group['id']}\n";
    echo "Participants: " . count($group['participants']) . "\n";
    echo "Description: {$group['description']}\n";
    echo "---\n";
}

// Create a new group
$response = $waha->misc()->createNewGroup(
    session: 'default',
    name: 'Laravel Developers',
    participants: ['[email protected]', '[email protected]']
);

if ($response->successful()) {
    $group = $response->json();
    echo "Group created: {$group['id']}\n";
}

// Get detailed group information
$response = $waha->groups()->getTheGroup(
    session: 'default',
    groupId: '[email protected]'
);
$groupDetails = $response->json();

// Add participants to a group (admin only)
$response = $waha->participants()->addParticipants(
    session: 'default',
    groupId: '[email protected]',
    participants: ['[email protected]', '[email protected]']
);

// Remove participants from a group (admin only)
$response = $waha->participants()->removeParticipants(
    session: 'default',
    groupId: '[email protected]',
    participants: ['[email protected]']
);

// Promote participants to admin
$response = $waha->admin()->promoteParticipantsToAdminUsers(
    session: 'default',
    groupId: '[email protected]',
    participants: ['[email protected]']
);

// Demote admins to regular participants
$response = $waha->admin()->demotesParticipantsToRegularUsers(
    session: 'default',
    groupId: '[email protected]',
    participants: ['[email protected]']
);

// Update group settings
$response = $waha->groups()->updatesTheGroupSubject(
    session: 'default',
    groupId: '[email protected]',
    subject: 'New Group Name'
);

$response = $waha->groups()->updatesTheGroupDescription(
    session: 'default',
    groupId: '[email protected]',
    description: 'This is our updated group description'
);

// Leave a group
$response = $waha->groups()->leaveTheGroup(
    session: 'default',
    groupId: '[email protected]'
);

// Get group invitation link (admin only)
$response = $waha->inviteCode()->getsTheInviteCodeForTheGroup(
    session: 'default',
    groupId: '[email protected]'
);
$inviteCode = $response->json();
echo "Invite link: https://chat.whatsapp.com/{$inviteCode['code']}\n";

// Revoke group invitation link (admin only)
$response = $waha->inviteCode()->invalidatesTheCurrentGroupInviteCodeAndGeneratesNewOne(
    session: 'default',
    groupId: '[email protected]'
);

// React to a message with emoji
$response = $waha->misc()->reactToMessageWithEmoji(
    messageId: 'message_id_here',
    reaction: '👍',
    session: 'default'
);

// Forward a message
$response = $waha->misc()->chattingControllerForwardMessage(
    chatId: '[email protected]',
    messageId: 'message_id_to_forward',
    session: 'default'
);

// Send contact vCard
$contacts = [
    [
        'id' => '[email protected]',
        'name' => 'John Doe'
    ]
];
$response = $waha->misc()->chattingControllerSendContactVcard(
    chatId: '[email protected]',
    contacts: $contacts,
    session: 'default',
    replyTo: null
);

// Set typing indicator
$response = $waha->misc()->chattingControllerStartTyping(
    chatId: '[email protected]',
    session: 'default'
);

// Stop typing indicator
$response = $waha->misc()->chattingControllerStopTyping(
    chatId: '[email protected]',
    session: 'default'
);

// Mark messages as seen
$response = $waha->misc()->chattingControllerSendSeen(
    chatId: '[email protected]',
    session: 'default',
    messageId: 'message_id_here',
    messageIds: null,
    participant: null
);

// Send interactive buttons message
$response = $waha->misc()->sendButtonsInteractiveMessage(
    chatId: '[email protected]',
    header: 'Choose an option',
    body: 'Please select one of the following:',
    footer: 'Powered by WAHA',
    buttons: [
        ['id' => 'btn1', 'title' => 'Option 1'],
        ['id' => 'btn2', 'title' => 'Option 2']
    ],
    session: 'default',
    headerImage: null
);

// Take a screenshot of the WhatsApp web interface
$response = $waha->misc()->screenshotControllerScreenshot('default');
$screenshot = $response->json();
echo "Screenshot saved\n";

// Set presence status (online, offline, typing, recording)
$response = $waha->misc()->setSessionPresence(
    session: 'default',
    chatId: '[email protected]',
    presence: 'typing' // online, offline, typing, recording
);

// Get presence status of a contact
$response = $waha->presence()->getThePresenceForTheChatIdIfItHasntBeenSubscribedItAlsoSubscribesToIt(
    session: 'default',
    chatId: '[email protected]'
);
$presence = $response->json();

// Subscribe to presence events
$response = $waha->presence()->subscribeToPresenceEventsForTheChat(
    session: 'default',
    chatId: '[email protected]'
);

// Health check
$response = $waha->misc()->checkTheHealthOfTheServer();
$health = $response->json();
echo "Service status: healthy\n";

// Ping the server
$response = $waha->misc()->pingTheServer();
echo "Server is responding\n";

// Get WAHA version
$response = $waha->misc()->getTheServerVersion();
$version = $response->json();
echo "WAHA Version: {$version['version']}\n";

// Get server environment
$response = $waha->server()->getTheServerEnvironment();
$env = $response->json();
echo "Environment: {$env['env']}\n";

// Get server status
$response = $waha->server()->getTheServerStatus();
$status = $response->json();

use CCK\LaravelWahaSaloonSdk\Waha\Waha;
use Saloon\Exceptions\Request\RequestException;

try {
    $waha = new Waha();
    
    // Always check session status before sending messages
    $sessionResponse = $waha->sessions()->getSessionInformation('default');
    $sessionData = $sessionResponse->json();
    
    if ($sessionData['status'] !== 'WORKING') {
        throw new Exception("Session not ready. Status: {$sessionData['status']}");
    }
    
    // Send message with error handling
    $response = $waha->sendText()->sendTextMessage(
        chatId: '[email protected]',
        text: 'Hello from Laravel!',
        session: 'default',
        replyTo: null,
        linkPreview: null,
        linkPreviewHighQuality: null
    );
    
    if (!$response->successful()) {
        throw new Exception("Failed to send message: {$response->body()}");
    }
    
    $messageData = $response->json();
    echo "Message sent successfully! ID: {$messageData['id']}\n";
    
} catch (RequestException $e) {
    // Handle HTTP request errors
    echo "Request failed: {$e->getMessage()}\n";
    echo "Response: {$e->getResponse()->body()}\n";
} catch (Exception $e) {
    // Handle other errors
    echo "Error: {$e->getMessage()}\n";
}
bash
php artisan vendor:publish --tag="waha-saloon-sdk-config"