Prima di iniziare
Le credenziali per le API si creano sulla piattaforma di invio, nella pagina Account. Bastano pochi minuti:
- Ti servono un account SMSMarket e del credito SMS.
- Accedi alla piattaforma di invio e apri Account, con l'icona a forma di ingranaggio in alto a destra.
- Consigliato: nella sezione Tokens premi Aggiungi nuovo token, dai un nome al token (uno per ogni applicazione) e copialo. Insieme al token ti serve la tua
user_key: è il tuo numero account API, un numero che trovi nei tuoi dati della tua area clienti. - In alternativa imposta una password API nella sezione API Password con Cambio password. È diversa dalla password di accesso al sito e alla piattaforma: se cambi la password di accesso, le API continuano a funzionare.
- Facoltativo: in Filtro IP consentiti puoi indicare gli indirizzi IP autorizzati. Se aggiungi degli IP e accendi il filtro (ON), solo quegli indirizzi possono chiamare le API; dagli altri ricevi
Accesso non consentito.
Dopo ogni modifica premi SALVA in fondo alla pagina Account, altrimenti non viene registrata.
Sicurezza
- Usa solo connessioni HTTPS.
- Tieni token e password API sul tuo server: mai nel codice di una pagina web o di un'app installata sui telefoni.
- Crea un token per ogni applicazione: così puoi revocarne uno senza fermare le altre.
- Se un token finisce nelle mani sbagliate, eliminalo dalla sezione Tokens e creane uno nuovo.
Tipi di messaggio
SMSMarket vende due tipi di SMS. Nelle API li indichi con il campo message_type, usando solo questi due valori:
N- SMS con notifica di consegna
LL- SMS senza notifica (low cost)
Lunghezza dei messaggi
- Un SMS contiene fino a 160 caratteri standard (GSM). I messaggi più lunghi vengono divisi in più parti e ogni parte consuma un credito.
- Con
"encoding": "ucs2", necessario per emoji e alfabeti non latini, il limite scende a 70 caratteri per parte. - I messaggi senza notifica (LL) possono essere limitati a 160 caratteri.
- La lunghezza massima totale è di 1000 caratteri (gsm) o 450 (ucs2).
Numeri di telefono
Scrivi sempre i numeri in formato internazionale, con il prefisso del paese: +393471234567.
API REST (consigliata)
Tutte le chiamate partono da questo indirizzo base:
https://sms.smsmarket.it/API/v1.0/REST/
1. Autenticazione
Ogni chiamata porta due intestazioni: la tua user_key e un token oppure una chiave di sessione.
Token (consigliato)
Invia user_key con il tuo numero account API e Access_token con il token creato in Account → Tokens. Non serve nessuna chiamata di accesso.
user_key: 12345678
Access_token: IL_TUO_TOKEN
Se manca user_key la piattaforma risponde con HTTP 400.
Sessione (alternativa)
GET
https://sms.smsmarket.it/API/v1.0/REST/login
Ti autentichi in HTTP Basic con la tua email e la password API, non con la password di accesso. La risposta è un testo nel formato USER_KEY;SESSION_KEY: nelle chiamate successive invia le intestazioni user_key e Session_key. Con credenziali errate ricevi HTTP 404.
# Log in with your email and API password (not the login password):
# export SMSMARKET_EMAIL="TUA_EMAIL"
# export SMSMARKET_API_PASSWORD="TUA_PASSWORD_API"
# The response is "USER_KEY;SESSION_KEY".
AUTH=$(curl -sS --fail-with-body \
-u "$SMSMARKET_EMAIL:$SMSMARKET_API_PASSWORD" \
"https://sms.smsmarket.it/API/v1.0/REST/login")
USER_KEY=${AUTH%%;*}
SESSION_KEY=${AUTH#*;}
# Then send these headers on every call
curl -sS --fail-with-body "https://sms.smsmarket.it/API/v1.0/REST/status?typeAliases=true" \
-H "user_key: $USER_KEY" \
-H "Session_key: $SESSION_KEY"
Scrivi i nomi delle intestazioni esattamente così, con maiuscole e trattino basso: alcune librerie HTTP li riscrivono. In Perl, ad esempio, vanno preceduti da :.
2. Inviare un SMS
POST
https://sms.smsmarket.it/API/v1.0/REST/sms
Il corpo della richiesta è in JSON, con Content-Type: application/json. Questi sono i campi:
-
message_typestringa · obbligatorio - Tipo di messaggio:
"N"(con notifica di consegna) o"LL"(senza notifica). -
messagestringa · obbligatorio - Il testo del messaggio.
-
recipientarray di stringhe · obbligatorio - I numeri dei destinatari, in formato internazionale.
-
senderstringa · facoltativo - Il mittente personalizzato, fino a 11 caratteri alfanumerici. Se il tipo di messaggio non permette un mittente personalizzato, lascialo vuoto: con gli SMS senza notifica (LL) potrebbe non essere disponibile.
-
scheduled_delivery_timestringa · facoltativo - Data e ora dell'invio programmato, nel formato
yyyyMMddHHmmssoppureyyyy-MM-dd HH:mm. -
order_idstringa · facoltativo - Un tuo riferimento per l'invio: fino a 32 caratteri tra lettere, numeri, trattino basso, punto e trattino.
-
returnCreditsbooleano · facoltativo - Con
truela risposta aggiungeused_credits, il credito consumato in euro. -
encodingstringa · facoltativo "gsm"(predefinito) oppure"ucs2", necessario per emoji e alfabeti non latini.
Se l'invio va a buon fine ricevi HTTP 201 con questa risposta:
{"result": "OK", "order_id": "6DD2A87ABF71485A8AFD29BA55FCFD83", "total_sent": 1, "used_credits": 0.07, "internal_order_id": "64007bd4-5625-42c2-b58b-06327e3a4a10"}
In caso di errore:
- 400 dati non validi: i dettagli sono nel corpo della risposta;
- 401 chiavi mancanti o non valide;
- 404 user key non trovata.
Esempio: accesso e invio di un SMS
cURL
#!/usr/bin/env bash
# Credentials from environment variables:
# export SMSMARKET_USER_KEY="12345678" # your API account number
# export SMSMARKET_TOKEN="..." # Account → Tokens on the platform
set -euo pipefail
BASE_URL="https://sms.smsmarket.it/API/v1.0/REST/"
# Send an SMS (HTTP 201 on success; on error curl prints the body and exits)
curl -sS --fail-with-body -X POST "${BASE_URL}sms" \
-H "Content-Type: application/json; charset=utf-8" \
-H "user_key: $SMSMARKET_USER_KEY" \
-H "Access_token: $SMSMARKET_TOKEN" \
--data-binary @- <<'JSON'
{
"message_type": "N",
"message": "Ciao! Il tuo appuntamento è confermato per domani alle 10:00.",
"recipient": ["+393471234567"],
"sender": "MioNegozio"
}
JSON
echo
PHP
<?php
// PHP 8.1+ with the curl extension.
// Run: SMSMARKET_USER_KEY="12345678" SMSMARKET_TOKEN="..." php send.php
const BASE_URL = 'https://sms.smsmarket.it/API/v1.0/REST/';
$userKey = getenv('SMSMARKET_USER_KEY');
$token = getenv('SMSMARKET_TOKEN');
if (!$userKey || !$token) {
fwrite(STDERR, "Set SMSMARKET_USER_KEY and SMSMARKET_TOKEN.\n");
exit(1);
}
$body = json_encode([
'message_type' => 'N',
'message' => 'Ciao! Il tuo appuntamento è confermato per domani alle 10:00.',
'recipient' => ['+393471234567'],
'sender' => 'MioNegozio',
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$ch = curl_init(BASE_URL . 'sms');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json; charset=utf-8',
'user_key: ' . $userKey,
'Access_token: ' . $token,
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
if ($response === false) {
fwrite(STDERR, 'Connection error: ' . curl_error($ch) . "\n");
exit(1);
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 201) {
fwrite(STDERR, "Send failed (HTTP $status): $response\n");
exit(1);
}
$result = json_decode($response, true, flags: JSON_THROW_ON_ERROR);
echo "Sent: order_id {$result['order_id']}, total_sent {$result['total_sent']}\n";
Python
# Python 3.8+ with requests (pip install requests).
# Run: SMSMARKET_USER_KEY="12345678" SMSMARKET_TOKEN="..." python send.py
import os
import sys
import requests
BASE_URL = "https://sms.smsmarket.it/API/v1.0/REST/"
headers = {
"user_key": os.environ["SMSMARKET_USER_KEY"],
"Access_token": os.environ["SMSMARKET_TOKEN"],
}
# Send an SMS (json= encodes the body as UTF-8 JSON)
r = requests.post(
BASE_URL + "sms",
headers=headers,
json={
"message_type": "N",
"message": "Ciao! Il tuo appuntamento è confermato per domani alle 10:00.",
"recipient": ["+393471234567"],
"sender": "MioNegozio",
},
timeout=30,
)
if r.status_code != 201:
sys.exit(f"Send failed (HTTP {r.status_code}): {r.text}")
result = r.json()
print(f"Sent: order_id {result['order_id']}, total_sent {result['total_sent']}")
Node.js
// Node.js 18+ (global fetch), ES module: save as send.mjs
// Run: SMSMARKET_USER_KEY="12345678" SMSMARKET_TOKEN="..." node send.mjs
const BASE_URL = "https://sms.smsmarket.it/API/v1.0/REST/";
const userKey = process.env.SMSMARKET_USER_KEY;
const token = process.env.SMSMARKET_TOKEN;
if (!userKey || !token) {
console.error("Set SMSMARKET_USER_KEY and SMSMARKET_TOKEN.");
process.exit(1);
}
// Send an SMS
const res = await fetch(BASE_URL + "sms", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
user_key: userKey,
Access_token: token,
},
body: JSON.stringify({
message_type: "N",
message: "Ciao! Il tuo appuntamento è confermato per domani alle 10:00.",
recipient: ["+393471234567"],
sender: "MioNegozio",
}),
});
const body = await res.text();
if (res.status !== 201) {
console.error(`Send failed (HTTP ${res.status}): ${body}`);
process.exit(1);
}
const result = JSON.parse(body);
console.log(`Sent: order_id ${result.order_id}, total_sent ${result.total_sent}`);
C#
// .NET 6+ console app (Program.cs, top-level statements).
// Set the environment variables SMSMARKET_USER_KEY (your API account number)
// and SMSMARKET_TOKEN (Account → Tokens on the platform).
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
const string BaseUrl = "https://sms.smsmarket.it/API/v1.0/REST/";
var userKey = Environment.GetEnvironmentVariable("SMSMARKET_USER_KEY");
var token = Environment.GetEnvironmentVariable("SMSMARKET_TOKEN");
if (string.IsNullOrEmpty(userKey) || string.IsNullOrEmpty(token))
{
Console.Error.WriteLine("Set SMSMARKET_USER_KEY and SMSMARKET_TOKEN.");
return 1;
}
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
http.DefaultRequestHeaders.Add("user_key", userKey);
http.DefaultRequestHeaders.Add("Access_token", token);
// Send an SMS (PostAsJsonAsync sends UTF-8 JSON)
using var response = await http.PostAsJsonAsync("sms", new
{
message_type = "N",
message = "Ciao! Il tuo appuntamento è confermato per domani alle 10:00.",
recipient = new[] { "+393471234567" },
sender = "MioNegozio",
});
var body = await response.Content.ReadAsStringAsync();
if (response.StatusCode != HttpStatusCode.Created)
{
Console.Error.WriteLine($"Send failed (HTTP {(int)response.StatusCode}): {body}");
return 1;
}
using var result = JsonDocument.Parse(body);
Console.WriteLine($"Sent: order_id {result.RootElement.GetProperty("order_id")}, " +
$"total_sent {result.RootElement.GetProperty("total_sent")}");
return 0;
Java
// Java 11+ (java.net.http). Save as SendSms.java (UTF-8) and run: java SendSms.java
// Set the environment variables SMSMARKET_USER_KEY (your API account number)
// and SMSMARKET_TOKEN (Account → Tokens on the platform).
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class SendSms {
private static final String BASE_URL = "https://sms.smsmarket.it/API/v1.0/REST/";
public static void main(String[] args) throws Exception {
String userKey = System.getenv("SMSMARKET_USER_KEY");
String token = System.getenv("SMSMARKET_TOKEN");
if (userKey == null || token == null) {
System.err.println("Set SMSMARKET_USER_KEY and SMSMARKET_TOKEN.");
System.exit(1);
}
// HTTP/1.1 keeps the header names exactly as written (user_key, Access_token).
HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
// The JDK has no JSON library: in a real project use Jackson or Gson.
String json = "{"
+ "\"message_type\": \"N\","
+ "\"message\": \"Ciao! Il tuo appuntamento è confermato per domani alle 10:00.\","
+ "\"recipient\": [\"+393471234567\"],"
+ "\"sender\": \"MioNegozio\""
+ "}";
// Send an SMS
HttpRequest send = HttpRequest.newBuilder(URI.create(BASE_URL + "sms"))
.header("Content-Type", "application/json; charset=utf-8")
.header("user_key", userKey)
.header("Access_token", token)
.POST(HttpRequest.BodyPublishers.ofString(json, StandardCharsets.UTF_8))
.build();
HttpResponse<String> response = http.send(send, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 201) {
System.err.println("Send failed (HTTP " + response.statusCode() + "): " + response.body());
System.exit(1);
}
System.out.println("Sent: " + response.body());
}
}
Il programma invia un SMS con notifica di consegna usando il token. Le credenziali arrivano dalle variabili d'ambiente SMSMARKET_USER_KEY (il tuo numero account API) e SMSMARKET_TOKEN.
3. Stato della consegna
GET
https://sms.smsmarket.it/API/v1.0/REST/sms/{order_id}
Al posto di {order_id} metti l'identificativo restituito dall'invio. La risposta riporta lo stato di ogni destinatario:
{
"recipient_number": 1,
"result": "OK",
"recipients": [
{
"status": "DLVRD",
"message": "Text message",
"destination": "+393471234567",
"delivery_date": "20261204175609"
}
]
}
Valori di status
- WAITING
- In attesa
- SENT
- Inviato all'operatore
- WAIT4DLVR
- In attesa di conferma di consegna
- DLVRD
- Consegnato
- SCHEDULED
- Programmato
- ERROR
- Errore
- TIMEOUT
- Scaduto senza conferma
- UNKNRCPT
- Numero non valido
- UNKNPFX
- Prefisso sconosciuto
- INVALIDDST
- Destinatario non valido
- BLACKLISTED
- Numero in blacklist
- TOOM4USER, TOOM4NUM
- Troppi SMS in poco tempo
- INVALIDCONTENTS
- Contenuto non valido
- KO
- Rifiutato dall'operatore
- DEMO
- Inviato in modalità demo
La conferma di consegna è disponibile solo per gli SMS con notifica (N).
4. Credito residuo
GET
https://sms.smsmarket.it/API/v1.0/REST/status?typeAliases=true
In sms trovi, per ogni tipo, quanti SMS hai ancora a disposizione (quantity). Per i pacchetti SMSMarket guarda i tipi N e LL: la risposta elenca anche il tipo L (qualità media), che SMSMarket non vende e per te resta sempre a zero.
{
"money": null,
"sms": [
{
"type": "N",
"quantity": 0
},
{
"type": "L",
"quantity": 0
},
{
"type": "LL",
"quantity": 200
}
],
"email": null
}
Esempio: stato della consegna e credito
cURL
#!/usr/bin/env bash
# Usage: ./status.sh ORDER_ID
# Credentials from environment variables:
# export SMSMARKET_USER_KEY="12345678" # your API account number
# export SMSMARKET_TOKEN="..." # Account → Tokens on the platform
set -euo pipefail
BASE_URL="https://sms.smsmarket.it/API/v1.0/REST/"
ORDER_ID="$1"
# 1. Delivery status of a sending
curl -sS --fail-with-body "${BASE_URL}sms/${ORDER_ID}" \
-H "user_key: $SMSMARKET_USER_KEY" \
-H "Access_token: $SMSMARKET_TOKEN"
echo
# 2. Remaining credit, as SMS available per type
curl -sS --fail-with-body "${BASE_URL}status?typeAliases=true" \
-H "user_key: $SMSMARKET_USER_KEY" \
-H "Access_token: $SMSMARKET_TOKEN"
echo
PHP
<?php
// PHP 8.1+ with the curl extension.
// Run: SMSMARKET_USER_KEY="12345678" SMSMARKET_TOKEN="..." php status.php ORDER_ID
const BASE_URL = 'https://sms.smsmarket.it/API/v1.0/REST/';
/** Authenticated GET request: returns the decoded JSON, or exits on error. */
function smsmarket_get(string $path): array
{
$ch = curl_init(BASE_URL . $path);
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => [
'user_key: ' . getenv('SMSMARKET_USER_KEY'),
'Access_token: ' . getenv('SMSMARKET_TOKEN'),
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$body = curl_exec($ch);
if ($body === false) {
fwrite(STDERR, 'Connection error: ' . curl_error($ch) . "\n");
exit(1);
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
fwrite(STDERR, "GET $path failed (HTTP $status): $body\n");
exit(1);
}
return json_decode($body, true, flags: JSON_THROW_ON_ERROR);
}
if (!isset($argv[1])) {
fwrite(STDERR, "Usage: php status.php ORDER_ID\n");
exit(1);
}
// 1. Delivery status of a sending
foreach (smsmarket_get('sms/' . rawurlencode($argv[1]))['recipients'] as $recipient) {
echo "{$recipient['destination']}: {$recipient['status']}\n";
}
// 2. Remaining credit, as SMS available per type
foreach (smsmarket_get('status?typeAliases=true')['sms'] as $credit) {
echo "{$credit['type']}: {$credit['quantity']} SMS\n";
}
Python
# Python 3.8+ with requests (pip install requests).
# Run: SMSMARKET_USER_KEY="12345678" SMSMARKET_TOKEN="..." python status.py ORDER_ID
import os
import sys
import requests
BASE_URL = "https://sms.smsmarket.it/API/v1.0/REST/"
HEADERS = {
"user_key": os.environ["SMSMARKET_USER_KEY"],
"Access_token": os.environ["SMSMARKET_TOKEN"],
}
def get(path):
r = requests.get(BASE_URL + path, headers=HEADERS, timeout=30)
if r.status_code != 200:
sys.exit(f"GET {path} failed (HTTP {r.status_code}): {r.text}")
return r.json()
if len(sys.argv) != 2:
sys.exit("Usage: python status.py ORDER_ID")
# 1. Delivery status of a sending
for recipient in get("sms/" + sys.argv[1])["recipients"]:
print(f"{recipient['destination']}: {recipient['status']}")
# 2. Remaining credit, as SMS available per type
for credit in get("status?typeAliases=true")["sms"]:
print(f"{credit['type']}: {credit['quantity']} SMS")
Node.js
// Node.js 18+ (global fetch), ES module: save as status.mjs
// Run: SMSMARKET_USER_KEY="12345678" SMSMARKET_TOKEN="..." node status.mjs ORDER_ID
const BASE_URL = "https://sms.smsmarket.it/API/v1.0/REST/";
const HEADERS = {
user_key: process.env.SMSMARKET_USER_KEY,
Access_token: process.env.SMSMARKET_TOKEN,
};
async function get(path) {
const res = await fetch(BASE_URL + path, { headers: HEADERS });
const body = await res.text();
if (res.status !== 200) {
console.error(`GET ${path} failed (HTTP ${res.status}): ${body}`);
process.exit(1);
}
return JSON.parse(body);
}
const orderId = process.argv[2];
if (!orderId) {
console.error("Usage: node status.mjs ORDER_ID");
process.exit(1);
}
// 1. Delivery status of a sending
const report = await get(`sms/${encodeURIComponent(orderId)}`);
for (const recipient of report.recipients) {
console.log(`${recipient.destination}: ${recipient.status}`);
}
// 2. Remaining credit, as SMS available per type
const credit = await get("status?typeAliases=true");
for (const { type, quantity } of credit.sms) {
console.log(`${type}: ${quantity} SMS`);
}
C#
// .NET 6+ console app (Program.cs, top-level statements). Run: dotnet run -- ORDER_ID
// Set the environment variables SMSMARKET_USER_KEY (your API account number)
// and SMSMARKET_TOKEN (Account → Tokens on the platform).
using System;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
const string BaseUrl = "https://sms.smsmarket.it/API/v1.0/REST/";
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: dotnet run -- ORDER_ID");
return 1;
}
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
http.DefaultRequestHeaders.Add("user_key", Environment.GetEnvironmentVariable("SMSMARKET_USER_KEY"));
http.DefaultRequestHeaders.Add("Access_token", Environment.GetEnvironmentVariable("SMSMARKET_TOKEN"));
async Task<JsonDocument?> Get(string path)
{
using var response = await http.GetAsync(path);
var body = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK) return JsonDocument.Parse(body);
Console.Error.WriteLine($"GET {path} failed (HTTP {(int)response.StatusCode}): {body}");
return null;
}
// 1. Delivery status of a sending
using var report = await Get($"sms/{Uri.EscapeDataString(args[0])}");
if (report is null) return 1;
foreach (var recipient in report.RootElement.GetProperty("recipients").EnumerateArray())
{
Console.WriteLine($"{recipient.GetProperty("destination")}: {recipient.GetProperty("status")}");
}
// 2. Remaining credit, as SMS available per type
using var credit = await Get("status?typeAliases=true");
if (credit is null) return 1;
foreach (var sms in credit.RootElement.GetProperty("sms").EnumerateArray())
{
Console.WriteLine($"{sms.GetProperty("type")}: {sms.GetProperty("quantity")} SMS");
}
return 0;
Java
// Java 11+ (java.net.http). Save as SmsStatus.java and run: java SmsStatus.java ORDER_ID
// Set the environment variables SMSMARKET_USER_KEY (your API account number)
// and SMSMARKET_TOKEN (Account → Tokens on the platform).
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class SmsStatus {
private static final String BASE_URL = "https://sms.smsmarket.it/API/v1.0/REST/";
// HTTP/1.1 keeps the header names exactly as written (user_key, Access_token).
private static final HttpClient HTTP = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
private static String get(String path) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE_URL + path))
.header("user_key", System.getenv("SMSMARKET_USER_KEY"))
.header("Access_token", System.getenv("SMSMARKET_TOKEN"))
.GET()
.build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
System.err.println("GET " + path + " failed (HTTP " + response.statusCode() + "): " + response.body());
System.exit(1);
}
return response.body();
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java SmsStatus.java ORDER_ID");
System.exit(1);
}
// 1. Delivery status of a sending (JSON; parse it with Jackson or Gson)
System.out.println(get("sms/" + URLEncoder.encode(args[0], StandardCharsets.UTF_8)));
// 2. Remaining credit, as SMS available per type
System.out.println(get("status?typeAliases=true"));
}
}
Questo esempio legge lo stato di un invio (passa l'identificativo come argomento) e poi il credito residuo.
5. Notifiche di consegna (webhook)
Invece di chiedere lo stato, puoi farti avvisare. In Account → Delivery receipts imposta l'indirizzo del tuo server nel campo Settings Url Notifica Stato Invio SMS e scegli il metodo GET o POST; poi premi SALVA.
Quando un SMS raggiunge lo stato finale, la piattaforma chiama il tuo indirizzo con questi campi:
delivery_date- Data e ora di consegna, nel formato
yyyyMMddHHmmss. order_id- L'identificativo dell'invio.
status- Lo stato, con gli stessi valori dello stato della consegna.
recipient- Il numero del destinatario in formato internazionale, codificato per l'URL (
%2Bal posto di+).
Esempio di corpo inviato con POST:
delivery_date=20261204175609&order_id=6DD2A87ABF71485A8AFD29BA55FCFD83&status=DLVRD&recipient=%2B393471234567
Il tuo indirizzo deve rispondere con HTTP 200. Un esempio minimo in PHP:
<?php
// delivery.php: the address you set in Account → Delivery receipts.
// The platform sends delivery_date, order_id, status and recipient (GET or POST).
$data = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
$orderId = $data['order_id'] ?? '';
$recipient = $data['recipient'] ?? ''; // already decoded, e.g. +393471234567
$status = $data['status'] ?? ''; // DLVRD, ERROR, UNKNRCPT, ...
$deliveryDate = $data['delivery_date'] ?? ''; // yyyyMMddHHmmss
// Save the status in your database; here we just write it to the log.
error_log("SMS $orderId to $recipient: $status at $deliveryDate");
http_response_code(200);
La conferma di consegna arriva solo per gli SMS con notifica (N).
API HTTP semplice (compatibilità)
È l'interfaccia del vecchio SMSMarket ed è ancora attiva. Usala solo se hai già un software che la utilizza: per i nuovi progetti scegli l'API REST.
Usa sempre HTTPS e preferisci il metodo POST, con i parametri inviati come modulo (application/x-www-form-urlencoded).
Come credenziali usa l'email del tuo account e la password API impostata in Account → API Password, non la password di accesso.
Invio di un SMS
POST
https://sms.smsmarket.it/sms/send.php
user- L'email del tuo account.
pass- La tua password API (Account → API Password), non la password di accesso.
rcpt- Il numero del destinatario, in formato internazionale.
data- Il testo del messaggio, fino a 160 caratteri.
sender- Il mittente: fino a 11 caratteri alfanumerici oppure un numero in formato internazionale.
qtynper gli SMS con notifica,llper quelli senza notifica.return_id- Facoltativo: con
return_id=1la risposta contiene anche l'identificativo dell'invio.
Risposta: OK seguito dal credito scalato, oppure KO seguito dall'errore.
Invio a più destinatari
POST
https://sms.smsmarket.it/sms/batch.php
Stessi parametri, ma in rcpt metti più numeri separati da virgola. Risposta: OK oppure KO seguito dall'errore.
Credito residuo
POST
https://sms.smsmarket.it/sms/credit.php
Parametri user e pass, più type facoltativo:
creditcredito in euro (predefinito);lqsSMS senza notifica disponibili;hqsSMS con notifica disponibili.
Risposta: OK seguito dal valore.
Errori più comuni
KO Accesso non consentito: credenziali errate, oppure utente o indirizzo IP non abilitato.KO Parametro <nome> non impostatoKO Parametro <nome> non validoKO Credito insufficienteKO Impossibile accodare il/i messaggio/i
Esempio: invio di un SMS
cURL
#!/usr/bin/env bash
# Credentials from environment variables:
# export SMSMARKET_EMAIL="TUA_EMAIL"
# export SMSMARKET_API_PASSWORD="TUA_PASSWORD_API" # Account → API Password, not the login password
set -euo pipefail
RESPONSE=$(curl -sS https://sms.smsmarket.it/sms/send.php \
--data-urlencode "user=$SMSMARKET_EMAIL" \
--data-urlencode "pass=$SMSMARKET_API_PASSWORD" \
--data-urlencode "rcpt=+393471234567" \
--data-urlencode "data=Ciao! Il tuo appuntamento è confermato per domani alle 10:00." \
--data-urlencode "sender=MioNegozio" \
--data-urlencode "qty=n")
# The response starts with "OK" or "KO"
case "$RESPONSE" in
OK*) echo "Sent: $RESPONSE" ;;
*) echo "Error: $RESPONSE" >&2; exit 1 ;;
esac
PHP
<?php
// PHP 8+ with the curl extension.
// Run: SMSMARKET_EMAIL="TUA_EMAIL" SMSMARKET_API_PASSWORD="TUA_PASSWORD_API" php send.php
$ch = curl_init('https://sms.smsmarket.it/sms/send.php');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'user' => getenv('SMSMARKET_EMAIL'),
'pass' => getenv('SMSMARKET_API_PASSWORD'),
'rcpt' => '+393471234567',
'data' => 'Ciao! Il tuo appuntamento è confermato per domani alle 10:00.',
'sender' => 'MioNegozio',
'qty' => 'n',
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
if ($response === false) {
fwrite(STDERR, 'Connection error: ' . curl_error($ch) . "\n");
exit(1);
}
$response = trim($response);
// The response starts with "OK" or "KO"
if (!str_starts_with($response, 'OK')) {
fwrite(STDERR, "Error: $response\n");
exit(1);
}
echo "Sent: $response\n";
Serve aiuto con l'integrazione?
Scrivici via email: assistenza diretta, senza centralini né ticket.
La piattaforma offre anche funzioni avanzate, come rubriche dei contatti e campagne: se ti servono via API, scrivici e ti mandiamo le istruzioni.