PHP code example of michotechnologies / michowapi-laravel

1. Go to this page and download the library: Download michotechnologies/michowapi-laravel 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/ */

    

michotechnologies / michowapi-laravel example snippets


use MichoTech\WApi\Facades\WApi;

WApi::messages()->sendText('260971000000', 'Hello from MichoWAPI!');

use MichoTech\WApi\Facades\WApi;

WApi::messages()->sendText('260971000000', 'Hello!');

use MichoTech\WApi\MichoWapi;

class NotificationController extends Controller
{
    public function __construct(protected MichoWapi $wapi) {}

    public function send(): void
    {
        $this->wapi->messages()->sendText('260971000000', 'Hello!');
    }
}

WApi::messages()->sendText('260971000000', 'Your exam results are ready.');

// From a file path
WApi::messages()->sendMedia('260971000000', '/path/to/photo.jpg', caption: 'School photo');

// From an SplFileInfo (e.g. from a Laravel uploaded file)
$file = $request->file('attachment'); // UploadedFile extends SplFileInfo
WApi::messages()->sendMedia('260971000000', $file, caption: 'Your invoice');

// From an open stream
$stream = fopen('/path/to/audio.mp3', 'r');
WApi::messages()->sendMedia('260971000000', $stream, filename: 'voice-note.mp3');

WApi::messages()->sendDocument(
    '260971000000',
    '/path/to/report.pdf',
    filename: 'Term 2 Report Card.pdf',
    caption: 'Please find your results attached.',
);

$results = WApi::messages()->sendBulk(
    ['260971111111', '260972222222', '260973333333'],
    'School fees for Term 3 are due. Log in to MichoSMS to view your balance.'
);

foreach ($results as $phone => $result) {
    $messageId = $result['data']['message_id'];
}

// All messages (paginated)
$messages = WApi::messages()->list();

// Filtered
$messages = WApi::messages()->list([
    'from_me' => true,                 // outbound only
    'type'    => 'image',              // chat | image | video | audio | document
    'chat_id' => '[email protected]',  // specific contact
    'page'    => 2,
]);

$message = WApi::messages()->find('3EB0A0B4F3...');

// $message['data']['status'] can be:
// queued | sent | delivered | read | failed

// Only inbound messages
$received = WApi::messages()->received(page: 1);

WApi::messages()->sync();

$chatMessages = WApi::messages()->forChat('[email protected]', page: 1);

// routes/api.php
Route::post('/webhooks/whatsapp', [WhatsAppWebhookController::class, 'handle']);

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: ['webhooks/*']);
})



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use MichoTech\WApi\Facades\WApi;

class WhatsAppWebhookController extends Controller
{
    public function handle(Request $request)
    {
        // Verify the payload signature
        if (! WApi::webhooks()->verify($request)) {
            abort(403, 'Invalid webhook signature.');
        }

        $event = WApi::webhooks()->parse($request);

        match ($event['event']) {
            'message.received'    => $this->onMessageReceived($event['data']),
            'message.sent'        => $this->onMessageSent($event['data']),
            'session.connected'   => $this->onConnected($event['session_id']),
            'session.disconnected'=> $this->onDisconnected($event['session_id']),
            default               => null,
        };

        return response()->json(['status' => 'ok']);
    }

    protected function onMessageReceived(array $data): void
    {
        // $data['from']    — sender's number
        // $data['message'] — message text
        // $data['type']    — text, image, audio, document, etc.
    }
}

use MichoTech\WApi\Facades\WApi;
use MichoTech\WApi\Exceptions\AuthenticationException;
use MichoTech\WApi\Exceptions\SessionNotConnectedException;
use MichoTech\WApi\Exceptions\RateLimitException;
use MichoTech\WApi\Exceptions\ValidationException;
use MichoTech\WApi\Exceptions\MichoWapiException;

try {
    WApi::messages()->sendText('260971000000', 'Hello!');

} catch (SessionNotConnectedException $e) {
    // WhatsApp session is disconnected — user needs to reconnect from dashboard
    Log::warning('WhatsApp session offline: ' . $e->getMessage());

} catch (RateLimitException $e) {
    // Too many requests — back off and retry
    Log::warning('MichoWAPI rate limit hit.');

} catch (ValidationException $e) {
    // Invalid request parameters
    Log::error('Validation failed: ' . $e->getMessage());
    Log::error('Fields: ' . json_encode($e->errors()));
    // Get errors for a specific field:
    $toErrors = $e->errorsFor('to');

} catch (AuthenticationException $e) {
    // Bad API key, revoked key, or key not linked to a session
    Log::error('Auth error: ' . $e->getMessage());

} catch (MichoWapiException $e) {
    // Any other API or network error
    Log::error('WApi error: ' . $e->getMessage());
}

use MichoTech\WApi\Facades\WApi;
use MichoTech\WApi\Exceptions\SessionNotConnectedException;

class SendResultsNotifications implements ShouldQueue
{
    public function handle(): void
    {
        Student::with('guardian', 'results')
            ->whereHas('results')
            ->chunk(50, function ($students) {
                foreach ($students as $student) {
                    try {
                        WApi::messages()->sendText(
                            $student->guardian->phone,
                            "Dear {$student->guardian->name}, {$student->name}'s " .
                            "Term 2 results are now available. Log in to MichoSMS to view them."
                        );
                    } catch (SessionNotConnectedException) {
                        // Stop immediately — no point continuing if session is down
                        $this->fail('WhatsApp session is not connected.');
                        return false;
                    }
                }
            });
    }
}

use MichoTech\WApi\Facades\WApi;

$pdfPath = storage_path("app/invoices/invoice-{$invoice->id}.pdf");

WApi::messages()->sendDocument(
    $client->phone,
    $pdfPath,
    filename: "Invoice-{$invoice->number}.pdf",
    caption: "Hi {$client->name}, please find your invoice attached.",
);

// In your webhook controller
protected function onMessageReceived(array $data): void
{
    $from    = $data['from'];
    $message = strtolower(trim($data['message'] ?? ''));

    $reply = match (true) {
        str_contains($message, 'results') => 'Log in to MichoSMS at michosms.com to view your results.',
        str_contains($message, 'fees')    => 'Fees can be paid via mobile money. Reply FEES for details.',
        default                           => 'Thank you for your message. We will get back to you shortly.',
    };

    WApi::messages()->sendText($from, $reply);
}
bash
php artisan vendor:publish --tag=michowapi-config