Overview #
This guide explains how to integrate Text.lk SMS API with C# applications to send SMS messages programmatically.
Prerequisites #
- .NET Framework 4.5+ or .NET Core 2.0+
- Text.lk API key (obtain from your Text.lk dashboard)
- HttpClient or RestSharp library
Installation #
Add the necessary NuGet package for HTTP requests:
Install-Package Microsoft.AspNet.WebApi.Client
# or
Install-Package RestSharp
Basic Implementation #
Method 1: Using HttpClient #
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class TextLkSmsService
{
private readonly string _apiKey;
private readonly string _apiUrl = "https://app.text.lk/api/v3/sms/send";
public TextLkSmsService(string apiKey)
{
_apiKey = apiKey;
}
public async Task<bool> SendSmsAsync(string recipient, string message, string senderId = "TextLKDemo")
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var payload = new
{
recipient = recipient,
sender_id = senderId,
type = "plain",
message = message
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await client.PostAsync(_apiUrl, content);
return response.IsSuccessStatusCode;
}
catch (Exception ex)
{
Console.WriteLine($"Error sending SMS: {ex.Message}");
return false;
}
}
}
}
Method 2: Using RestSharp #
using RestSharp;
using System.Threading.Tasks;
public class TextLkSmsServiceRestSharp
{
private readonly string _apiKey;
private readonly string _apiUrl = "https://app.text.lk/api/v3/sms/send";
public TextLkSmsServiceRestSharp(string apiKey)
{
_apiKey = apiKey;
}
public async Task<bool> SendSmsAsync(string recipient, string message, string senderId = "TextLKDemo")
{
var client = new RestClient(_apiUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", $"Bearer {_apiKey}");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
var requestBody = new
{
recipient,
sender_id = senderId,
type = "plain",
message
};
request.AddJsonBody(requestBody);
try
{
var response = await client.ExecuteAsync(request);
return response.IsSuccessful;
}
catch (System.Exception ex)
{
System.Console.WriteLine($"Error sending SMS: {ex.Message}");
return false;
}
}
}
Usage Example #
class Program
{
static async Task Main(string[] args)
{
const string apiKey = "YOUR_API_KEY_HERE";
var smsService = new TextLkSmsService(apiKey);
var recipient = "94710000000";
var message = "This is a test message from C#";
var senderId = "TextLKDemo";
var result = await smsService.SendSmsAsync(recipient, message, senderId);
if (result)
{
Console.WriteLine("SMS sent successfully!");
}
else
{
Console.WriteLine("Failed to send SMS.");
}
}
}
Advanced Implementation with Error Handling #
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class SmsResponse
{
public bool Success { get; set; }
public string Message { get; set; }
public string MessageId { get; set; }
}
public class AdvancedTextLkSmsService
{
private readonly string _apiKey;
private readonly HttpClient _httpClient;
public AdvancedTextLkSmsService(string apiKey)
{
_apiKey = apiKey;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
_httpClient.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<SmsResponse> SendSmsAsync(string recipient, string message, string senderId = "TextLKDemo")
{
var payload = new
{
recipient,
sender_id = senderId,
type = "plain",
message
};
var json = JsonConvert.SerializeObject(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync("https://app.text.lk/api/v3/sms/send", content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
// Parse successful response
var successResponse = JsonConvert.DeserializeObject<dynamic>(responseContent);
return new SmsResponse
{
Success = true,
Message = "SMS sent successfully",
MessageId = successResponse?.message_id?.ToString()
};
}
else
{
// Parse error response
var errorResponse = JsonConvert.DeserializeObject<dynamic>(responseContent);
return new SmsResponse
{
Success = false,
Message = errorResponse?.message?.ToString() ?? "Unknown error occurred"
};
}
}
catch (HttpRequestException ex)
{
return new SmsResponse
{
Success = false,
Message = $"Network error: {ex.Message}"
};
}
catch (Exception ex)
{
return new SmsResponse
{
Success = false,
Message = $"Unexpected error: {ex.Message}"
};
}
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
Best Practices #
- API Key Security: Store your API key in secure configuration (Azure Key Vault, environment variables, or appsettings.json with proper encryption)
- Dependency Injection: Register the SMS service as a singleton or scoped service in your DI container
- Rate Limiting: Implement retry logic with exponential backoff for rate limit errors
- Validation: Validate phone numbers and message content before sending
- Logging: Implement comprehensive logging for debugging and monitoring
Configuration Example (appsettings.json) #
{
"TextLkSettings": {
"ApiKey": "your_api_key_here",
"DefaultSenderId": "YourBrand",
"BaseUrl": "https://app.text.lk/api/v3/"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
}
Troubleshooting #
Error | Solution |
---|---|
401 Unauthorized | Verify API key is correct and properly formatted |
400 Bad Request | Check recipient number format and message content |
429 Too Many Requests | Implement rate limiting and retry logic |
Network errors | Verify internet connectivity and firewall settings |
Support #
For additional help, refer to the Text.lk API documentation or contact their support team.
This integration guide provides a solid foundation for sending SMS messages through Text.lk using C#. Adjust the implementation based on your specific application requirements and architecture.