SDK Node.js
SDK Node.js in TypeScript, con build ESM e CommonJS: SMS, contatti, liste, sender ID ed email SMTP.
Runtime
Node.js 18+
Pacchetto
@messageglobe/sdk
npm · in arrivo
Dipendenze
Nessuna: il client REST usa la fetch nativa; nodemailer 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 Express, Nest, Next.js o uno script. 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
SMTP
invio (HTML + testo, allegati)
Installazione
Aggiungi l'SDK al progetto
npm install @messageglobe/sdkIl pacchetto non è ancora pubblicato su npm: installalo direttamente da GitHub.
npm install github:Message-Globe/messageglobe-nodejsAvvio 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.
import { MessageGlobe } from '@messageglobe/sdk'; const mg = new MessageGlobe({ // Copia il tuo token dalla dashboard sviluppatori. // Un solo token abilita tutte le funzioni REST. apiToken: 'XX|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', smtp: { host: 'smtp.messageglobe.com', port: 587, fromAddress: '[email protected]', fromName: 'YourApp', username: 'smtp-user', password: 'smtp-password', encryption: 'tls', },}); // Invia un SMSconst response = await mg.sms.send({ to: '393612345678', from: 'YourName', message: 'This is a test message', gateway: 'HQ',});console.log(response.messageId); // Crea un contattoconst contact = await mg.contacts.create('list_uid_example', { phone: '393310000000' });console.log(contact.uid); // Invia una emailawait mg.email.send({ to: { email: '[email protected]', name: 'Jane Doe' }, subject: 'Welcome', html: '<h1>Hi Jane</h1>', text: 'Hi Jane',});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.
import { SmsClient } from '@messageglobe/sdk'; const client = new SmsClient({ apiToken: 'XX|your-api-token' }); // Lingua delle risposte API: "en" oppure "it".const italian = new SmsClient({ apiToken: 'XX|your-api-token', acceptLanguage: 'it' }); // CommonJS è supportato allo stesso modo:// const { MessageGlobe } = require('@messageglobe/sdk');Gateway HQ gateway: 'HQ'
Sender ID personalizzato e report di consegna. Il campo mittente è obbligatorio.
Gateway LQ gateway: 'LQ'
Nessun mittente personalizzato e nessun report di consegna.
const response = await client.send({ to: '393612345678', // un numero, "n1,n2" oppure un array from: 'YourName', // sender ID, max 11 caratteri se alfanumerico message: 'Hello world', gateway: 'HQ', dlrCallbackUrl: 'https://yourapp.com/webhooks/dlr', // opzionale, solo HQ}); const [result] = response.results;console.log(result.messageId); // "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"console.log(result.status); // "Sent"console.log(result.cost); // 0.06Il 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.
await client.send({ to: '393612345678', from: 'YourName', message: 'Привет 😀', type: 'auto', // diventa unicode automaticamente}); // Il rilevamento è esportato anche da solo:import { detectSmsType } from '@messageglobe/sdk'; detectSmsType('Hello world'); // 'plain'detectSmsType('Привет 😀'); // 'unicode'const response = await client.send({ to: ['393612345678', '880172145789'], // oppure "393612345678,880172145789" from: 'YourName', message: 'Hello everyone',}); for (const result of response.results) { console.log(result.recipient, '=>', result.messageId);}const result = await client.status('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'); console.log(result.status); // es. "Delivered"console.log(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.
{ "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.
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.
import { ContactsClient } from '@messageglobe/sdk'; const client = new ContactsClient({ apiToken: 'XX|your-api-token' }); // Almeno uno tra phone ed email è obbligatorio.const contact = await client.create('list_uid_example', { phone: '393310000000', firstName: 'Jane', lastName: 'Doe',}); console.log(contact.uid); // "contact_uid_example"console.log(contact.status); // "subscribe" // Elimina indicando la lista e l'uid del contatto.await 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.
import { GroupsClient } from '@messageglobe/sdk'; const client = new GroupsClient({ apiToken: 'XX|your-api-token' }); const group = await client.create('Newsletter subscribers');const uid = group.uid; await client.show(uid);await client.update(uid, 'VIP subscribers');await client.delete(uid); // Elenca tutte le liste (dati grezzi, paginati)const page = await client.list();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.
import { SendersClient } from '@messageglobe/sdk'; const client = new SendersClient({ apiToken: 'XX|your-api-token' }); // Elenca tutti i sender IDfor (const sender of await client.list()) { console.log(sender.senderId, '=>', sender.status); // "active" / "pending"} // Cerca un sender ID per nomeconst sender = await client.show('YourName'); // Creane uno nuovo: tutti i campi sono obbligatori, 3-11 caratteri.await client.create({ 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 nomeawait client.delete('YourName');In Italia gli alias alfanumerici seguono il codice di condotta AGCOM: i nuovi sender ID vengono inviati per approvazione.
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.
import { EmailClient } from '@messageglobe/sdk'; const client = new EmailClient({ host: 'smtp.messageglobe.com', port: 587, fromAddress: '[email protected]', fromName: 'YourApp', username: 'smtp-user', password: 'smtp-password', encryption: 'tls',}); await client.send({ to: { email: '[email protected]', name: '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.', attachments: [ { filename: 'report.pdf', path: '/path/to/report.pdf' }, { filename: 'data.csv', content: csvString, contentType: 'text/csv' }, ],}); // Rilascia il pool di connessioni allo spegnimento.await client.close();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.
import { EmailClient, messageGlobeSmtp } from '@messageglobe/sdk'; const client = new EmailClient( messageGlobeSmtp({ username: '[email protected]', // username di accesso a MessageGlobe apiToken: 'XX|your-api-token', // API token, usato come password SMTP fromAddress: '[email protected]', fromName: 'YourApp', }),);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.
import { ApiError, MessageGlobeError, ValidationError } from '@messageglobe/sdk'; try { await client.send(sms);} catch (error) { if (error instanceof ValidationError) { // Validazione lato client fallita } else if (error instanceof ApiError) { // L'API ha restituito un errore console.log(error.message); // "Invalid params" console.log(error.apiErrorCode); // 200 console.log(error.httpStatusCode); // 422 console.log(error.errors); } else if (error instanceof MessageGlobeError) { // Qualsiasi altro errore dell'SDK } else { throw error; }}| Tipo | Quando viene sollevato |
|---|---|
| ConfigurationError | Configurazione mancante o non valida. |
| ValidationError | Un messaggio o un contatto non supera la validazione lato client. |
| ApiError | Un endpoint REST (SMS, Contatti, Liste, Sender ID) restituisce un errore. |
| TransportError | Errore di rete, timeout o risposta non decodificabile. |
| EmailError | La consegna SMTP fallisce. |
Tipo base comune a tutti gli errori: MessageGlobeError
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.
import { SmsClient, type HttpClient } from '@messageglobe/sdk'; const httpClient: HttpClient = { async request({ method, url, headers, body, signal }) { const response = await fetch(url, { method, headers, body, signal }); return { statusCode: response.status, body: await response.text(), headers: Object.fromEntries(response.headers), }; },}; const client = new SmsClient({ apiToken: 'XX|your-api-token', httpClient });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.