Vai al contenuto

Integrazione C#/.NET

Integrare l'API SMSBAT nella tua applicazione .NET è semplice utilizzando la classe "HttpClient" integrata.

Utilizzo di HttpClient (.NET Core/.NET 5+)

Ecco un esempio di invio di un messaggio in modo asincrono utilizzando "HttpClient" e "System.Text.Json" per la serializzazione.

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace SmsbatIntegration
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();

        static async Task Main(string[] args)
        {
            string url = "https://api.smsbat.com/bat/messagelist";
            string apiKey = "YOUR_API_KEY_HERE";

            // Create the payload using anonymous objects
            var payload = new
            {
                messages = new[]
                {
                    new
                    {
                        from = "ALPHANAME",
                        to = "380501234567",
                        text = "Hello from C# and .NET!",
                        type = "sms"
                    }
                }
            };

            // Serialize the payload to JSON
            string jsonPayload = JsonSerializer.Serialize(payload);
            var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

            // Set the Authorization Header
            client.DefaultRequestHeaders.Add("X-Authorization-Key", apiKey);

            try
            {
                // Send the POST request
                HttpResponseMessage response = await client.PostAsync(url, content);

                // Read the response content
                string responseBody = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"Status Code: {(int)response.StatusCode}");
                Console.WriteLine($"Response: {responseBody}");
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request exception: {e.Message}");
            }
        }
    }
}

Utilizzo di RestSharp

Se il tuo progetto utilizza già RestSharp, puoi utilizzarlo per semplificare la struttura della richiesta.

Installa il pacchetto NuGet:

dotnet add package RestSharp

CODICE_BLOCCO_2