PHP code example of mycomm / mycomm-php

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

    

mycomm / mycomm-php example snippets


use MyComm\Client;

$mycomm = new Client(getenv('MYCOMM_API_KEY'));   // mc_live_...

$message = $mycomm->messages->send(
    to: '+923001234567',
    body: 'Your code is 4821',
);

echo $message->id;                // "01923f80-5c6d-7e7f-8a90-a1b2c3d4e5f6"
echo $message->status->value;     // "queued"  (an enum case, MessageStatus::Queued)

use MyComm\Enums\MessageCategory;

$message = $mycomm->messages->send(
    to: '+923001234567',
    body: 'Sale ends tonight. Reply STOP to opt out.',
    category: MessageCategory::Marketing,
    send_after: new DateTimeImmutable('today 18:00'),
    reference_id: 'campaign-7-user-991',
    metadata: ['user_id' => 991],
);

foreach ($message->warnings as $warning) {
    logger()->notice($warning->message);
}

$preview = $mycomm->messages->send(to: '+923001234567', body: $text, dry_run: true);

$preview->segments;      // how many SMS parts the text needs
$preview->hold_reason;   // why it would wait, if it would

use MyComm\Inputs\SendBatchItem;

$batch = $mycomm->messages->sendBatch(
    messages: [
        new SendBatchItem(to: '+923001234567', body: 'Hi Ada'),
        new SendBatchItem(to: '+923331112222', body: 'Hi Grace'),
    ],
    defaults: ['category' => 'transactional'],
);

foreach ($batch->results as $result) {
    if ($result->error !== null) {
        report("Message {$result->index} was rejected: {$result->error->code}");
    }
}

use MyComm\Exceptions\InvalidArgumentException;

try {
    $mycomm->messages->send(to: $number, body: $text, expires_in: 30);
} catch (InvalidArgumentException $e) {
    echo $e->getMessage();     // expires_in must be between 60 and 604800 (got 30).
    $e->field;                 // "expires_in"
    $e->rule;                  // "OUT_OF_RANGE", named like the API's own validation codes
    $e->violations;            // every problem, not only the first
}

$result = $mycomm->verify(to: '+923001234567');     // add inboxId: '...' when the key can use several

if (! $result->ok()) {
    foreach ($result->problems() as $problem) {
        echo $problem, "\n";          // the API's own message, for example why a recipient is refused
    }
}

$page = $mycomm->contacts->list(group_id: $groupId, limit: 100);

foreach ($page as $contact) {
    // the first 100
}

foreach ($mycomm->contacts->all(group_id: $groupId) as $contact) {
    // every contact of the group
}

$mycomm->contacts->update($id, first_name: 'Ada');           // email untouched
$mycomm->contacts->update($id, first_name: 'Ada', email: null);   // email cleared

use MyComm\Enums\ErrorCode;
use MyComm\Exceptions\ApiException;
use MyComm\Exceptions\ConnectionException;
use MyComm\Exceptions\ValidationException;

try {
    $mycomm->messages->send(to: $number, body: $text, category: 'marketing');
} catch (ValidationException $e) {
    $e->fields();                 // ['to' => [['code' => 'INVALID_NUMBER', 'message' => '...']]]
} catch (ApiException $e) {
    if ($e->is(ErrorCode::RecipientOptedOut)) {
        // do not retry: the recipient unsubscribed
    }
    $e->status;                   // 422
    $e->code();                   // ErrorCode::RecipientOptedOut, or null for a code newer than this SDK
    $e->errorCode;                // "RECIPIENT_OPTED_OUT"
    $e->details;                  // ['address' => '+923001234567', ...]
    $e->requestId;                // quote this to support
    $e->docUrl();                 // the page of the error reference that explains the code
    echo $e;                      // RECIPIENT_OPTED_OUT (422): The recipient ... details: {...}  request_id: ...
} catch (ConnectionException $e) {
    // MyComm could not be reached, even after the retries
}

use MyComm\RequestOptions;

$mycomm->messages->send(
    to: $order->phone,
    body: "Order {$order->number} has shipped.",
    requestOptions: new RequestOptions(idempotencyKey: "order-shipped-{$order->id}"),
);

$message->meta()->idempotentReplayed;   // true when this was a replay

use MyComm\Exceptions\WebhookSignatureException;
use MyComm\Webhooks\Events\MessageDelivered;
use MyComm\Webhooks\Events\MessageFailed;
use MyComm\Webhooks\Events\MessageReceived;
use MyComm\Webhooks\Webhook;

$payload = file_get_contents('php://input');

try {
    $event = Webhook::constructEvent($payload, $_SERVER['HTTP_MYCOMM_SIGNATURE'] ?? null, $secret);
} catch (WebhookSignatureException) {
    http_response_code(400);
    exit;
}

match (true) {
    $event instanceof MessageDelivered => markDelivered($event->data->message->id),
    $event instanceof MessageFailed => markFailed($event->data->message->id, $event->data->message->failure?->code),
    $event instanceof MessageReceived => handleReply($event->data->message->from, $event->data->message->body),
    default => null,   // an event you do not handle, or one added to MyComm later
};

http_response_code(204);

$endpoint = $mycomm->webhookEndpoints->create(
    url: 'https://example.com/webhooks/mycomm',
    events: ['message.delivered', 'message.failed', 'message.received'],
);

$endpoint->secret;

$partner = new Client(getenv('MYCOMM_PARTNER_KEY'));

$account = $partner->partner->accounts->provision(
    external_ref: 'erp-business-20418',
    name: 'Acme Traders',
    country_iso: 'PK',
    timezone: 'Asia/Karachi',
);

$acme = $partner->forAccount($account->id);    // every call now carries MyComm-Account
$acme->messages->send(to: '+923001234567', body: 'Welcome to Acme');

$usage = $partner->partner->usage->get(from: '2026-10-01', to: '2026-10-31');

use MyComm\FileUpload;

$media = $mycomm->media->upload('/path/to/photo.jpg');
$media = $mycomm->media->upload(FileUpload::fromString($bytes, 'photo.jpg', 'image/jpeg'));

$mycomm->messages->send(to: '+923001234567', media_ids: [$media->id]);

use MyComm\Http\Request;
use MyComm\Testing\FakeResponse;
use MyComm\Testing\MyCommFake;

$fake = new MyCommFake;
$notifier = new OrderNotifier($fake->client());

$fake->respond('messages.send', ['status' => 'queued']);                 // your values over the example
$fake->respondOnce('messages.send', FakeResponse::error(422, 'RECIPIENT_OPTED_OUT'));

$notifier->orderShipped($order);

$fake->assertCalled('messages.send', fn (Request $request) => $request->json['to'] === $order->phone);
$fake->assertNotCalled('messages.sendBatch');

$mycomm = new Client(
    apiKey: getenv('MYCOMM_API_KEY'),
    baseUrl: 'https://mycomm.cogneer.tech',   // without /v1
    httpClient: $yourPsr18Client,              // optional
    maxRetries: 2,
    timeout: 30.0,                             // seconds; applies to the built-in Guzzle client
    validate: true,                            // check arguments against the API's documented rules first
);

$message->meta()->requestId;            // quote to support
$message->meta()->rateLimitRemaining;   // requests left in the window
$message->raw();                        // the JSON as MyComm sent it
bash
composer