PHP code example of funnelchat / funnelchat-php

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

    

funnelchat / funnelchat-php example snippets


use Funnelchat\Funnelchat;

$funnelchat = new Funnelchat(apiKey: getenv('FUNNELCHAT_API_KEY'));

// Your WhatsApp numbers (permission WhatsApp numbers → View). The `id` of each one is the `device_id` you send with.
foreach ($funnelchat->devices->list() as $device) {
    echo $device['id'], ' ', $device['number'], "\n";
    // What that number can do through the API: messages and the delivery statuses it reports.
    var_dump($device['capabilities']['messages']['templates'], $device['capabilities']['statuses']);
}

$window = $funnelchat->contacts->metaWindow(2001, ['device_id' => 3]);

if ($window['is_open']) {
    $result = $funnelchat->messages->send(2001, [
        'device_id' => 3,
        'phone' => '5491100000000',            // the phone of the same contact, without +
        'text' => 'Hi! Here is the info you asked for.',
        'client_reference' => 'order-8841',    // optional: your reference to follow it
    ]);
    echo $result['message']['id'], ' ', $result['message']['status'], "\n"; // 9001 queued
}

$funnelchat->messages->send(2001, [
    'device_id' => 3,
    'phone' => '5491100000000',
    'file' => 'https://files.example/download?signature=…',
    'file_type' => 'document',
    'file_name' => 'invoice.pdf',
]);

$funnelchat->templates->send(3, '45', [
    'phone' => '5491100000000',
    'contact_id' => 2001,
    'template_variables' => ['body' => ['Lucía']], // the body variables, in order
]);

$funnelchat->messages->sendForm(2001, ['form_id' => 12, 'device_id' => 3, 'button_text' => 'Fill in']);

$funnelchat->messages->send(2001, $body, ['retrySend' => true]);

foreach ($funnelchat->groups->list(['deviceId' => 4]) as $group) {
    echo $group['name'], "\n";
}

$participants = $funnelchat->groups->listParticipants(['groupUid' => '[email protected]'])->firstPage();
$metadata = $funnelchat->groups->metadata('[email protected]', ['device_id' => 4, 'group_uid' => '[email protected]']);

$number = $funnelchat->devices->create(
    ['connection' => 'qr', 'alias' => 'Store 12', 'external_reference' => 'customer-8841', 'country' => 'AR'],
    ['idempotencyKey' => 'customer-8841-number'],
)['data'];

$qr = $funnelchat->devices->qr($number['id'])['data'];
// $qr['qr_code'] is a PNG data URI: <img src="…">. Ask again after $qr['expires_in'] seconds
// (5 with a QR, 3 while the session starts, 0 once connected), or wait for device.connected.

$link = $funnelchat->connectLinks->create([
    'type' => 'meta',                                          // or 'qr'; 'meta' is off in production for now
    'allowed_connection_types' => ['coexistence', 'dedicated'], // only with 'meta'; with both, your customer chooses
    'external_reference' => 'customer-8841',
    'return_url' => 'https://app.example.com/numbers/done',    // https, up to 2048 characters
    'expires_in_minutes' => 1440,                              // 30 to 10080
], ['idempotencyKey' => 'customer-8841-link'])['data'];

sendToYourCustomer($link['url']); // the URL comes only in this answer

$link = $funnelchat->connectLinks->retrieve($link['id'])['data'];
// status: pending, completed, failed (see error_code), expired or revoked; device_id once completed

foreach ($funnelchat->connectLinks->list(['status' => 'pending']) as $open) { … } // newest first
$funnelchat->connectLinks->revoke($open['id']); // only a pending link; otherwise 409 link_not_pending

foreach ($funnelchat->devices->list(['external_reference' => 'customer-8841']) as $number) { … }
$funnelchat->devices->update(41, ['external_reference' => 'customer-9000']);
$funnelchat->devices->delete(41);

$event = $funnelchat->webhooks->constructEvent($body, $signature, $secret);
if ($event['type'] === 'device.connected') {
    markConnected($event['data']['device']['external_reference'] ?? null, $event['data']['device']['id']);
}

use App\Jobs\ProcessFunnelchatEvent;
use Funnelchat\Exception\WebhookVerificationException;
use Funnelchat\Webhook;
use Illuminate\Http\Request;

// routes/api.php: the `api` group does not ask for the CSRF token, which a webhook cannot send.
Route::post('/hooks/funnelchat', function (Request $request) {
    try {
        $event = Webhook::constructEvent(
            $request->getContent(),                                  // the raw body
            $request->header('X-Funnelchat-Signature'),
            config()->string('services.funnelchat.webhook_secret'),  // the full secret, with whsec_
        );
    } catch (WebhookVerificationException $exception) {
        return response()->noContent(400); // $exception->reason says why
    }

    ProcessFunnelchatEvent::dispatch($event); // process it later; deduplicate by $event['id']

    return response()->noContent(200);        // answer fast (under 10 s)
});

use Funnelchat\Exception\WebhookVerificationException;
use Funnelchat\Webhook;

$rawBody = file_get_contents('php://input');
try {
    $event = Webhook::constructEvent($rawBody, $_SERVER['HTTP_X_FUNNELCHAT_SIGNATURE'] ?? null, getenv('FUNNELCHAT_WEBHOOK_SECRET') ?: null);
} catch (WebhookVerificationException $exception) {
    http_response_code(400);
    exit;
}
http_response_code(200);
// … $event['type'], $event['data']

/**
 * @phpstan-import-type MessageReceivedEvent from \Funnelchat\Generated\WebhookEvents
 */
final class FunnelchatEvents
{
    /** @param array{type: string} $event */
    public function handle(array $event): void
    {
        switch ($event['type']) {
            case 'message.received':
                /** @var MessageReceivedEvent $event */
                echo $event['data']['contact']['phone'], ': ', $event['data']['message']['text'];
                break;
            default:
                // A type your code does not know yet: not an error.
        }
    }
}

$subscription = $funnelchat->webhooks->create([
    'url' => 'https://your-server.example/hooks/funnelchat',
    'events' => ['message.received', 'message.status_changed'],
    'description' => 'My integration',
]);
// Store $subscription['id'] and $subscription['secret']: the secret is shown only once.

// Every item of every page (a generator: it requests each page when it needs it).
foreach ($funnelchat->contacts->list(['perPage' => 100, 'tag_mode' => 'any', 'tag_ids' => [12]]) as $contact) {
    echo $contact['id'], "\n";
}

// Page by page:
$page = $funnelchat->tags->list(['perPage' => 50])->firstPage();
print_r($page->data);
while ($page->hasNextPage()) {
    $page = $page->getNextPage();
}

// Or with a generator of pages:
foreach ($funnelchat->tags->list()->iterPages() as $page) {
    echo count($page), " tags on this page\n";
}

use Funnelchat\Exception\ApiException;
use Funnelchat\Exception\RateLimitException;

try {
    $funnelchat->contacts->retrieve(2001);
} catch (RateLimitException $exception) {
    echo "Wait {$exception->retryAfter} s\n";
} catch (ApiException $exception) {
    echo $exception->status, ' ', $exception->errorCode, ' ', $exception->getMessage(), ' (', $exception->requestId, ")\n";
}

use Funnelchat\ResponseInfo;

$result = $funnelchat->messages->send(2001, $body);
$logger->info('sent', ['message_id' => $result['message']['id'], 'request_id' => $funnelchat->lastResponse()?->requestId]);

$funnelchat->contacts->list([], ['onResponse' => fn(ResponseInfo $r) => $logger->debug('page', ['request_id' => $r->requestId])]);

$funnelchat->tags->list([], ['maxRetries' => 0, 'timeout' => 5, 'headers' => ['X-My-Trace' => 'abc']]);

$contact = $funnelchat->request('GET', '/api/v1/contacts/{contact}', ['path' => ['contact' => 2001]]);

$stats = $funnelchat->request('GET', '/api/v1/broadcasts/{broadcast}/statistics', ['path' => ['broadcast' => 77]]);

$result = $funnelchat->request('POST', '/api/v1/something-new', ['body' => ['a' => 1]]);

$funnelchat = new \Funnelchat\Funnelchat(apiKey: '1|fc_live_sandbox', baseUrl: 'http://127.0.0.1:4010');
bash
composer