SDK

SDK PHP

SDK PHP leggero e senza dipendenze da framework: SMS, contatti, liste, sender ID ed email SMTP.

Runtime

PHP 7.4+

Pacchetto

messageglobe/sdk

Packagist

Dipendenze

Estensioni ext-curl ed ext-json; PHPMailer per l'email (installato automaticamente).

Licenza

MIT

Codice sorgente aperto su GitHub

L'SDK non ha dipendenze da framework e si integra senza attriti in Laravel, Symfony, WordPress o PHP puro. Un solo API token — quello della dashboard sviluppatori — autorizza tutte le funzioni REST: SMS, contatti, liste e sender ID. L'email si configura a parte via SMTP.

Funzionalità

Cinque moduli, una sola integrazione

SMS

REST API v3

invio, stato di consegna

Gestione contatti

REST API v3

creazione, eliminazione

Liste (gruppi)

REST API v3

creazione, lettura, aggiornamento, eliminazione, elenco

Sender ID

REST API v3

elenco, dettaglio, creazione, eliminazione

Email

SMTP

invio (HTML + testo, allegati)

Installazione

Aggiungi l'SDK al progetto

Shell
composer require messageglobe/sdk
Vedi il pacchetto su Packagist

Avvio rapido

Dal token al primo invio

Usa la facade unificata oppure ogni client singolarmente. Il token si copia dalla dashboard sviluppatori e vale per tutte le funzioni REST.

PHP
use MessageGlobe\MessageGlobe;use MessageGlobe\Sms\SmsMessage;use MessageGlobe\Contacts\ContactRequest;use MessageGlobe\Email\EmailMessage; $mg = MessageGlobe::create([    // Copia il tuo token dalla dashboard sviluppatori.    // Un solo token abilita tutte le funzioni REST.    'api_token' => 'XX|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',    'smtp' => [        'host'         => 'smtp.messageglobe.com',        'port'         => 587,        'from_address' => '[email protected]',        'from_name'    => 'YourApp',        'username'     => 'smtp-user',        'password'     => 'smtp-password',        'encryption'   => 'tls',    ],]); // Invia un SMS$response = $mg->sms()->send(    (new SmsMessage())        ->to('393612345678')        ->from('YourName')        ->message('This is a test message')        ->highQuality());echo $response->messageId(); // Crea un contatto$contact = $mg->contacts()->create('list_uid_example', (new ContactRequest())->phone('393310000000'));echo $contact->uid(); // Invia una email$mg->email()->send(    (new EmailMessage())        ->to('[email protected]', 'Jane Doe')        ->subject('Welcome')        ->html('<h1>Hi Jane</h1>')        ->text('Hi Jane'));
Ottieni il tuo API token

SMS

Invio, gateway e report di consegna

La stessa configurazione è condivisa da ogni client REST. Puoi impostare la lingua delle risposte dell'API su italiano o inglese.

PHP
use MessageGlobe\ApiConfig;use MessageGlobe\Sms\SmsClient; $client = new SmsClient(new ApiConfig('XX|your-api-token')); // Lingua delle risposte API: "en" oppure "it".$client = new SmsClient(new ApiConfig('XX|your-api-token', ApiConfig::DEFAULT_BASE_URL, ApiConfig::LANGUAGE_IT));

Gateway HQ ->highQuality()

Sender ID personalizzato e report di consegna. Il campo mittente è obbligatorio.

Gateway LQ ->lowQuality()

Nessun mittente personalizzato e nessun report di consegna.

Invio di un messaggio
use MessageGlobe\Sms\SmsMessage; $response = $client->send(    (new SmsMessage())        ->to('393612345678')        // un numero, oppure più chiamate ->to()        ->from('YourName')          // sender ID, max 11 caratteri se alfanumerico        ->message('Hello world')        ->highQuality()        ->dlrCallbackUrl('https://yourapp.com/webhooks/dlr') // opzionale, solo HQ); $result = $response->first();echo $result->messageId();   // "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"echo $result->status();      // "Sent"echo $result->cost();        // 0.06

Il tipo di messaggio (plain o unicode) è impostato su plain. Lascia che sia l'SDK a dedurlo dal contenuto: i testi con caratteri non‑GSM (emoji, cirillico, …) partono come unicode.

Tipo automatico
(new SmsMessage())    ->to('393612345678')    ->from('YourName')    ->messageAutoType('Привет 😀');   // diventa unicode automaticamente
Destinatari multipli
$response = $client->send(    (new SmsMessage())        ->to('393612345678,880172145789')  // oppure concatena più ->to()        ->from('YourName')        ->message('Hello everyone')        ->highQuality()); foreach ($response->all() as $result) {    echo $result->recipient(), ' => ', $result->messageId(), PHP_EOL;}
Verifica dello stato
$result = $client->status('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'); echo $result->status();      // es. "Delivered"echo $result->updatedAt();

Con il gateway HQ e una callback DLR, MessageGlobe invia in POST un payload JSON al tuo endpoint a ogni aggiornamento di consegna.

Payload webhook DLR
{    "message_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",    "recipient": "393612345678",    "sender_id": "YourName",    "status_code": 1,    "status": "Delivered",    "updated_at": "2024-06-28T11:41:51.000000Z"}

Valori di status_code: 1 Delivered, 2 Failed, 8 Sent.

Scopri le API Messaggi

Gestione contatti

Anagrafiche dentro le tue liste

I contatti vivono all'interno di una lista identificata dal suo group id. Si usa lo stesso API token degli SMS.

PHP
use MessageGlobe\ApiConfig;use MessageGlobe\Contacts\ContactsClient;use MessageGlobe\Contacts\ContactRequest; $client = new ContactsClient(new ApiConfig('XX|your-api-token')); // Almeno uno tra phone ed email è obbligatorio.$contact = $client->create('list_uid_example', (new ContactRequest())    ->phone('393310000000')    ->firstName('Jane')    ->lastName('Doe')); echo $contact->uid();       // "contact_uid_example"echo $contact->status();    // "subscribe" // Elimina indicando la lista e l'uid del contatto.$client->delete('list_uid_example', 'contact_uid_example');

Liste (gruppi)

Il contenitore dei contatti

Una lista — o gruppo — è il contenitore a cui appartengono i contatti: il suo uid è il group id usato dal client Contatti.

PHP
use MessageGlobe\ApiConfig;use MessageGlobe\Contacts\GroupsClient; $client = new GroupsClient(new ApiConfig('XX|your-api-token')); $group = $client->create('Newsletter subscribers');$uid   = $group->uid(); $group = $client->show($uid);$group = $client->update($uid, 'VIP subscribers'); $client->delete($uid); // Elenca tutte le liste (dati grezzi, paginati)$page = $client->all();

Sender ID

Gestisci i mittenti del tuo account

I sender ID sono i mittenti personalizzati usati dal gateway HQ. Puoi elencarli, consultarli, richiederne di nuovi ed eliminarli via API.

PHP
use MessageGlobe\ApiConfig;use MessageGlobe\Senders\SendersClient;use MessageGlobe\Senders\SenderIdRequest; $client = new SendersClient(new ApiConfig('XX|your-api-token')); // Elenca tutti i sender IDforeach ($client->all() as $sender) {    echo $sender->senderId(), ' => ', $sender->status(), PHP_EOL; // "active" / "pending"} // Cerca un sender ID per nome$sender = $client->show('YourName'); // Creane uno nuovo: tutti i campi sono obbligatori, 3-11 caratteri.$sender = $client->create((new SenderIdRequest())    ->senderId('YourName')    ->company('Your Company')    ->taxCode('ABCDEF12G34H567I')    ->vatCode('01234567890')    ->address('Via Roma 1')    ->city('Rome')    ->province('RM')    ->country('IT')    ->emailAddress('[email protected]')    ->phone('391234567890')    ->pecAddress('[email protected]')); // Elimina per nome$client->delete('YourName');

In Italia gli alias alfanumerici seguono il codice di condotta AGCOM: i nuovi sender ID vengono inviati per approvazione.

Leggi il codice di condotta AGCOM

Email

Email transazionali via SMTP

Invia email HTML e testo con allegati, CC, BCC e reply‑to. Le opzioni di cifratura sono TLS (STARTTLS), SSL (SMTPS) oppure nessuna.

PHP
use MessageGlobe\Email\Attachment;use MessageGlobe\Email\EmailClient;use MessageGlobe\Email\EmailMessage;use MessageGlobe\Email\SmtpConfig; $client = new EmailClient(new SmtpConfig(    'smtp.messageglobe.com',    587,    '[email protected]',    'YourApp',    'smtp-user',    'smtp-password',    SmtpConfig::ENCRYPTION_TLS)); $client->send(    (new EmailMessage())        ->to('[email protected]', 'Jane Doe')        ->cc('[email protected]')        ->replyTo('[email protected]')        ->subject('Your report')        ->html('<h1>Report ready</h1><p>See attachment.</p>')        ->text('Report ready. See attachment.')        ->attach(Attachment::fromPath('/path/to/report.pdf'))        ->attach(Attachment::fromContent($csvString, 'data.csv', 'text/csv')));

MessageGlobe espone un server SMTP su dashboard.messageglobe.com:465 (SSL): lo username è il tuo login e la password è l'API token. Esiste un preset dedicato.

Preset SMTP MessageGlobe
$config = SmtpConfig::forMessageGlobe(    '[email protected]',   // username di accesso a MessageGlobe    'XX|your-api-token',   // API token, usato come password SMTP    '[email protected]',    'YourApp'); $client = new EmailClient($config);
Scopri le API Email

Gestione errori

Un solo tipo base da intercettare

Ogni errore sollevato dall'SDK deriva da un tipo comune: puoi gestirli tutti in un unico punto, oppure distinguere caso per caso.

PHP
use MessageGlobe\Exception\ApiException;use MessageGlobe\Exception\ValidationException;use MessageGlobe\Exception\MessageGlobeExceptionInterface; try {    $client->send($sms);} catch (ValidationException $e) {    // Validazione lato client fallita} catch (ApiException $e) {    // L'API ha restituito un errore    echo $e->getMessage();       // "Invalid params"    echo $e->apiErrorCode();     // 200    echo $e->httpStatusCode();   // 422    print_r($e->errors());} catch (MessageGlobeExceptionInterface $e) {    // Qualsiasi altro errore dell'SDK}
TipoQuando viene sollevato
ConfigurationExceptionConfigurazione mancante o non valida.
ValidationExceptionUn messaggio o un contatto non supera la validazione lato client.
ApiExceptionUn endpoint REST (SMS, Contatti, Liste, Sender ID) restituisce un errore.
TransportExceptionErrore di rete, timeout o risposta non decodificabile.
EmailExceptionLa consegna SMTP fallisce.

Tipo base comune a tutti gli errori: MessageGlobeExceptionInterface

Client HTTP

Usa il tuo stack di rete

Ogni client REST usa un trasporto predefinito senza dipendenze. Puoi sostituirlo con il tuo — comodo per i test, per aggiungere retry o per riusare lo stack HTTP dell'applicazione.

PHP
// Implementa MessageGlobe\Http\HttpClientInterface per usare il tuo stack HTTP.$client = new SmsClient($config, new MyHttpClient());$groups = new GroupsClient($config, new MyHttpClient());

Altri SDK

Stessa API, altri linguaggi

Gli SDK ufficiali sono allineati per funzionalità: cambia il linguaggio, non il flusso di lavoro.

Pronto a integrare?

Apri un account, genera il tuo API token e invia il primo messaggio in pochi minuti.

Supporto MessageGlobe

Compila il modulo e ti risponderemo al più presto.

Sto verificando la disponibilità operatori…