PHP code example of imamnc / efihub-client

1. Go to this page and download the library: Download imamnc/efihub-client 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/ */

    

imamnc / efihub-client example snippets


$app->register(Efihub\EfihubServiceProvider::class);

$app->configure('efihub');

$app->withFacades();

class_alias(Efihub\Facades\Efihub::class, 'Efihub');

use Efihub\Facades\Efihub;

// GET with query params
$res = Efihub::get('/user', ['page' => 1]);

// POST JSON
$res = Efihub::post('/orders', ['sku' => 'ABC', 'qty' => 2]);

// PUT
$res = Efihub::put('/orders/123', ['qty' => 3]);

// DELETE
$res = Efihub::delete('/orders/123');

if ($res->successful()) {
    $data = $res->json();
}

// Multipart upload (form-data + file attachment)
$uploadRes = Efihub::postMultipart('/documents', ['type' => 'invoice'], [
    'file' => storage_path('app/invoices/jan.pdf'),
]);
if ($uploadRes->failed()) {
    // handle failure
}

// Also supports Laravel UploadedFile / Symfony UploadedFile
$uploadRes = Efihub::postMultipart('/documents', ['type' => 'invoice'], [
    'file' => $request->file('invoice'),
]);

// Multiple uploaded files for the same field
$uploadRes = Efihub::postMultipart('/documents', ['type' => 'invoice'], [
    'file' => [$request->file('invoice1'), $request->file('invoice2')],
]);

use Efihub\EfihubClient;

class UserService
{
    /** @var EfihubClient */
    private $efihub;

    public function __construct(EfihubClient $efihub)
    {
        $this->efihub = $efihub;
    }

    public function list(): array
    {
        $res = $this->efihub->get('/user');
        return $res->successful() ? $res->json() : [];
    }
}

use Illuminate\Http\Request;
use Efihub\Facades\Efihub;

class MediaController
{
    public function store(Request $request)
    {
        $request->validate([
            'file' => ['b::storage()->upload($uploadedFile, 'uploads/'.date('Y/m/d').'/');

        if ($url === false) {
            return back()->withErrors('Upload failed');
        }

        return back()->with('url', $url);
    }
}

Efihub::storage()->exists('uploads/photo.jpg'); // bool
Efihub::storage()->size('uploads/photo.jpg');   // int|null (bytes)
Efihub::storage()->delete('uploads/photo.jpg'); // bool

use Efihub\Facades\Efihub;
use Illuminate\Http\Request;

// Text generation with optional file attachment(s)
$text = Efihub::ai()->text(
    model: 'gpt-4o',
    prompt: 'Ringkas dokumen berikut dalam 5 poin.',
    instructions: 'Gunakan bahasa Indonesia yang singkat dan jelas.',
    attachments: $request->file('document')
);

// Image generation with optional attachments
$image = Efihub::ai()->image(
    model: 'flux',
    prompt: 'Buat ilustrasi landing page untuk brand furniture modern',
    instructions: 'Gunakan palet netral premium.',
    attachments: [
        $request->file('reference1'),
        $request->file('reference2'),
    ],
    options: [
        'ratio' => 'landscape',
        'quality' => 'high',
    ]
);

// Single uploaded file
Efihub::ai()->text('gpt-4o', 'Review this file', null, $request->file('file'));

// Multiple uploaded files
Efihub::ai()->image('flux', 'Generate based on these inputs', null, [
    $request->file('img1'),
    $request->file('img2'),
]);

// File path and raw content specs are also accepted by the underlying multipart client
Efihub::ai()->text('gpt-4o', 'Analyze this PDF', null, [
    'file' => storage_path('app/docs/report.pdf'),
]);

use Efihub\Facades\Efihub;

$ok = Efihub::socket()->dispatch(
    'orders:updates',
    'OrderUpdated',
    ['order_id' => 123, 'status' => 'updated']
);

if (!$ok) {
    // handle failure (log, retry, etc.)
}

use Efihub\Facades\Efihub;

$authUrl = Efihub::sso()->login();
if ($authUrl === false) {
    // log error and abort
}

return redirect()->away($authUrl);

$token = request('redirect_token');
$user = Efihub::sso()->userData($token);

if ($user === false) {
    // invalid token or request failed
} else {
    // $user['email'], $user['name'], ...
}

use Efihub\Facades\Efihub;

// List all registered agents
$agents = Efihub::whatsapp()->agents();
// returns: [ ['code' => 'AGENT1', ...], ... ]

// Get QR code image (base64 PNG) to display for scanning
$qr = Efihub::whatsapp()->agentQR('AGENT1');
// returns: 'data:image/png;base64,...' or null

// Check connection status
$status = Efihub::whatsapp()->agentStatus('AGENT1');
// returns: 'connected' | 'disconnected' | null

// Start a WhatsApp agent session
$started = Efihub::whatsapp()->agentStart('AGENT1');
if ($started) {
    // session started successfully
}

// Restart a WhatsApp agent session
$restarted = Efihub::whatsapp()->agentRestart('AGENT1');
if ($restarted) {
    // session restarted successfully
}

// Terminate a WhatsApp agent session
$terminated = Efihub::whatsapp()->agentTerminate('AGENT1');
if ($terminated) {
    // session terminated successfully
}

// Validate a phone number before sending
$valid = Efihub::whatsapp()->checkPhoneNumber('AGENT1', '628109998877');
if (!$valid) {
    // number is not on WhatsApp
}

use Efihub\Facades\Efihub;

// Send to a single recipient
$ok = Efihub::whatsapp()->sendMessage(
    sender: 'AGENT1',
    to: '+628109998877',
    message: 'Halo! Tes WhatsApp.'
);

// Send to a group
$ok = Efihub::whatsapp()->sendGroupMessage(
    sender: 'AGENT1',
    to: 'group-abc123', // group identifier
    message: 'Hello World!'
);

if (!$ok) {
    // log or retry
}

// Single file by path
$ok = Efihub::whatsapp()->sendAttachment(
    sender: 'AGENT1',
    to: '+628109998877',
    message: 'Berikut invoice kamu',
    attachment: storage_path('app/invoices/jan.pdf'),
);

// Raw contents with custom filename & MIME type
$ok = Efihub::whatsapp()->sendAttachment(
    sender: 'AGENT1',
    to: '+628109998877',
    message: 'Report CSV',
    attachment: [
        'contents' => file_get_contents(storage_path('app/tmp/report.csv')),
        'filename' => 'report.csv',
        'headers'  => ['Content-Type' => 'text/csv'],
    ],
);

// Multiple files to a group
$ok = Efihub::whatsapp()->sendGroupAttachment(
    sender: 'AGENT1',
    to: 'group-abc123',
    message: 'Semua dokumen',
    attachment: [
        storage_path('app/docs/a.pdf'),
        storage_path('app/docs/b.pdf'),
    ],
);

// Text message
Efihub::whatsapp()->sendMessage(
    sender: 'AGENT1',
    to: '+628109998877',
    message: 'Your order has been shipped.',
    ref_id: 'order-9988',
    ref_url: 'https://yourapp.com/orders/9988',
);

// Text message to a group
Efihub::whatsapp()->sendGroupMessage(
    sender: 'AGENT1',
    to: 'group-abc123',
    message: 'Bulk shipment processed.',
    ref_id: 'batch-42',
    ref_url: 'https://yourapp.com/batches/42',
);

// Attachment to a single recipient
Efihub::whatsapp()->sendAttachment(
    sender: 'AGENT1',
    to: '+628109998877',
    message: 'Berikut invoice kamu.',
    attachment: storage_path('app/invoices/jan.pdf'),
    ref_id: 'invoice-101',
    ref_url: 'https://yourapp.com/invoices/101',
);

// Attachment to a group
Efihub::whatsapp()->sendGroupAttachment(
    sender: 'AGENT1',
    to: 'group-abc123',
    message: 'Laporan bulanan.',
    attachment: storage_path('app/reports/jan.pdf'),
    ref_id: 'report-jan',
    ref_url: 'https://yourapp.com/reports/jan',
);

use Efihub\Facades\Efihub;

// Retrieve recent messages for an agent and phone number
$messages = Efihub::whatsapp()->getMessages(
    agentCode: 'AGENT1',
    phone: '+628109998877',
    limit: 10  // optional, defaults to 10
);

if (!empty($messages)) {
    foreach ($messages as $msg) {
        echo "From: {$msg['from']}, Message: {$msg['message']}";
    }
} else {
    // No messages or request failed
}

// Download media attachment from a specific message
$media = Efihub::whatsapp()->downloadMedia(
    agentCode: 'AGENT1',
    phone: '+628109998877',
    messageId: 'msg_abc123'
);

if ($media) {
    // $media contains media URL and metadata
    echo "Media URL: {$media->url}";
} else {
    // Media download failed
}

$client = app(\Efihub\EfihubClient::class);
$response = $client->post('/whatsapp/message', [ /* payload */ ]);
if ($response->failed()) {
    logger()->error('WA send failed', [
        'status' => $response->status(),
        'body'   => $response->json(),
    ]);
}
bash
php artisan vendor:publish --provider="Efihub\EfihubServiceProvider" --tag=config