PHP code example of beaconbox / beaconbox-php

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

    

beaconbox / beaconbox-php example snippets


use BeaconBox\BeaconBoxClient;
use BeaconBox\Enum\MessageKind;
use BeaconBox\Enum\OrderStatus;
use BeaconBox\Model\MessagePush;

$client = new BeaconBoxClient(getenv('BEACONBOX_API_KEY'));

$result = $client->messages->push(new MessagePush(
    recipientEmail: '[email protected]',
    subject: 'Your order has shipped',
    body: 'Tracking XY123456789EE. Estimated delivery Thursday.',
    kind: MessageKind::Updateable,
    reference: '#A-10294',
    orderStatus: OrderStatus::Shipped,
));

echo $result->id;  // 3xg39cvt8a46

use BeaconBox\Enum\Channel;
use BeaconBox\Enum\SkipReason;

$result = $client->messages->push(new MessagePush(
    recipientEmail: '[email protected]',
    subject: 'Your order has shipped',
    body: 'Tracking XY123456789EE.',
    reference: '#A-10294',
    recipientPhone: '+37255550134',
    channels: [Channel::Sms],
    orderStatus: OrderStatus::Shipped,
));

if ($result->sms?->skippedReason === SkipReason::InsufficientCredit->value) {
    // Top up, then: $client->messages->resendSms($result->id);
} elseif (\in_array($result->sms?->skippedReason, [
    SkipReason::SmsDisabled->value,    // your SMS mode is off
    SkipReason::SmsNotEnabled->value,  // BeaconBox has not switched SMS on for you yet
], true)) {
    // The email went. Naming Channel::Sms above did not, and cannot, turn SMS on.
}

if ($result->email !== null && !$result->email->sending) {
    // Reliable: no email will be sent, and skippedReason says why.
    error_log($result->email->skippedReason);  // plan_lapsed, unsubscribed, suppressed, ...
}

use BeaconBox\Enum\EmailSkipReason;

$message = $client->messages->get($result->id);

if ($message->delivery->notSent !== null) {
    // No email was ever attempted, and none will be. Stop polling for delivery.
    if ($message->delivery->notSent->reason === EmailSkipReason::PlanLapsed->value) {
        // the subscription ran out; paying resumes sending
    }
}

if ($message->delivery->failed !== null) {
    // An email was attempted and BeaconBox gave up: esp_refused, retries_exhausted
    // or outcome_unknown (the answer was lost; it may still arrive, which clears `failed`,
    // and is never resent).
    error_log($message->delivery->failed->reason);
}

$client->messages->push(
    new MessagePush(
        recipientEmail: '[email protected]',
        subject: 'Your order has shipped',
        body: 'Tracking XY123456789EE.',
    ),
    idempotencyKey: 'order-4711-shipped',
);

// Delivery status
$message = $client->messages->get('3xg39cvt8a46');
$message->delivery->opened;

// Every message, following cursors. A generator, so a year of history is not held in memory
foreach ($client->messages->each(recipientEmail: '[email protected]') as $message) { /* … */ }

// Take one back: withdrawn for the recipient, any queued nudge called off, no credit spent
$client->messages->retract('3xg39cvt8a46');

// Up to 100 pushes. Read ->failed, not the status code. A ConflictException
// (idempotency.request_in_progress) means the same batch is still running: retry it with the same key
// later. The SDK does not retry it for you, and items already sent are replayed rather than resent
$result = $client->messages->pushBatch([
    new MessagePush(recipientEmail: '[email protected]', subject: 'Shipped', body: 'Tracking XY123456789EE.'),
    new MessagePush(recipientEmail: '[email protected]', subject: 'Shipped', body: 'Tracking XY987654321EE.'),
]);
foreach ($result->failures() as $item) {
    error_log("item {$item->index} rejected: {$item->errorCode}");
}

// Contact details. Reads are masked: a leaked key must not dump a phone book
$client->recipients->sms('[email protected]')->smsConsentSource;  // push, api, admin or inbox
$client->recipients->setPhone('[email protected]', '+37255550134');
$client->recipients->clearPhone('[email protected]');

// The prepaid balance. One balance, shared by SMS and WhatsApp
$client->credits->balance()->balance;

// Keys and webhook endpoints
$client->keys->create('orders service');
$endpoint = $client->webhookEndpoints->create('https://example.com/hooks');  // empty = every event

// Send one sample ping and see what came back. Always 200, whatever your endpoint answers:
// the failure being reported belongs to the next hop, so read ->delivered, not the status.
$test = $client->webhookEndpoints->test($endpoint->id);
if (!$test->delivered) {
    error_log("{$test->statusCode} {$test->error} {$test->durationMs}ms");
}

$client->messages->push(new MessagePush(
    recipientEmail: '[email protected]',
    subject: 'Action needed on your order',
    body: 'We could not process your payment.',
    recipientPhone: '+37255550134',
    channels: [Channel::Sms],
    escalateIfUnreadAfterMinutes: 120,
));

$report = $client->recipients->erase('[email protected]');
error_log("{$report->messagesDeleted} {$report->suppressionsKept} {$report->stopsKept}");

$receipt = $client->recipients->eraseWhatsApp('[email protected]');

// The half only you can finish: erased replies whose words may already be in *your* mailboxes.
$yours = $receipt->repliesAForwardEmailMayHaveCarried;

use BeaconBox\Enum\WebhookEventType;
use BeaconBox\Exception\WebhookVerificationException;
use BeaconBox\Webhooks;

try {
    $event = Webhooks::verify(
        rawBody: file_get_contents('php://input'),   // the RAW body, byte for byte
        signatureHeader: $_SERVER['HTTP_X_BEACONBOX_SIGNATURE'] ?? '',
        secret: getenv('BEACONBOX_WEBHOOK_SECRET') ?: '',
    );
} catch (WebhookVerificationException) {
    http_response_code(400);
    return;
}

if ($event->type === WebhookEventType::MessageBounced) {
    // ...
}

use BeaconBox\BeaconBoxClient;
use BeaconBox\RetryPolicy;

$client = new BeaconBoxClient(
    apiKey: getenv('BEACONBOX_API_KEY'),
    baseUrl: 'https://api.beaconbox.eu',
    timeoutMs: 30_000,
    retryPolicy: new RetryPolicy(maxRetries: 2),
    userAgentSuffix: 'acme-shop/2.1',
);

$client = new BeaconBoxClient(
    apiKey: getenv('BEACONBOX_API_KEY'),
    logger: $monolog,
);

$psr17 = new \Nyholm\Psr7\Factory\Psr17Factory();
$client = new BeaconBoxClient(
    apiKey: getenv('BEACONBOX_API_KEY'),
    httpClient: new \GuzzleHttp\Client(),
    requestFactory: $psr17,
    streamFactory: $psr17,
);
bash
composer