How to send SMS via MTS Exolve and Go
One of the Moscow companies decided to expand the system functions to Golang, and the customer asked to implement SMS and other channels for customer notifications. In this article, we will analyze step by step how to send SMS using the MTS Exolve service and the popular Golang programming language.
SMS is a useful tool in customer interaction scenarios if you get their consent to notifications. Mainly about product delivery or online order status; messages about bonuses and promotions; automatic responses to customer requests; alerts about emergency situations in smart home systems when integrated with Internet of Things (IoT) devices.
Let's connect SMS notifications to the Go server and test the operation.
We buy a number for messages
First, register on exolve.ru. The platform will credit 300 welcome rubles to the new user – enough to rent a room.
When creating an application, you need to come up with a name for it: this will help you find the application in the list faster.
What are Applications
Applications are your project for working with IT and telecom functions. It allows you to perform integrations, buy and configure numbers, and so on. Each application has its own resources and settings. In the application, you can set up forwarding of incoming calls, call recording, create a callback, view call and message details.
![](https://habrastorage.org/getpro/habr/upload_files/cf9/9b4/212/cf99b42127ca5d4a785eea234d61c6d3.png)
Then the service will redirect us to the application control panel. We watch a short tutorial and confirm the phone number. After that, we go to the applications section.
Select a tab in the application menu.
![](https://habrastorage.org/getpro/habr/upload_files/a14/b96/cd0/a14b96cd002641f9cf98dda1ecaff6d0.png)
In the left sidebar we find the API keys section.
![](https://habrastorage.org/getpro/habr/upload_files/f23/744/f77/f23744f77a8db20d53ac70aa8a46edf9.png)
This key (token) is needed to send SMS. It is important to remember where it is stored to use it later.
![](https://habrastorage.org/getpro/habr/upload_files/f2c/34f/b63/f2c34fb63bf5a1fbbccda4612ac4459e.png)
To send messages you need a phone number, so go to the “Numbers” tab in the left side menu and click on the “Buy a number” button.
![](https://habrastorage.org/getpro/habr/upload_files/4ac/a79/6ad/4aca796ade505f74e88cfd5dbec9b9cb.png)
Select the desired region, category, type and click on “Find number”. Mark the number you like and click “Buy”.
![](https://habrastorage.org/getpro/habr/upload_files/5e9/e17/e5c/5e9e17e5c45eb6ab11f8390de231b6b6.png)
As a result, we will use a personal token for authorization and two phone numbers: the sender number (purchased on MTS Exolve) and the recipient number.
Create a server in Golang
The Go programming language allows you to quickly and efficiently deploy a server that can be used for a variety of tasks, including sending SMS. You can download Go from the official site.
First, create a new folder for our project, in it – the file send.go and open it in your preferred text editor, for example in VSCode.
It is necessary to create a server that will listen to a specific port and process incoming requests. In the send.go file, add the following code with comments that explain the purpose of each of its blocks:
// package main указывает, что это основной пакет программы.
// В Go «main» — это специальный пакет, откуда начинается выполнение программы.
package main
// Импортируем необходимые библиотеки для работы нашей программы.
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// SMSContent — структура для хранения информации SMS-сообщения.
type SMSContent struct {
Number string `json:"number"`
Destination string `json:"destination"`
Text string `json:"text"`
}
// main — стартовая точка нашей программы.
func main() {
// Указываем, как обрабатывать HTTP-запросы по определённому адресу.
http.HandleFunc("/my-post", processIncomingSMS)
// Сообщаем о запуске сервера и запускаем его на 8080 порту.
fmt.Println("Server listening on :8080")
// Создаём пример SMS-сообщения и отправляем его.
smsDetails := SMSContent{
Number: «ВСТАВЬТЕ НОМЕР ОТПРАВИТЕЛЯ»,
Destination: «ВСТАВЬТЕ НОМЕР ПОЛУЧАТЕЛЯ»,
Text: «ВСТАВЬТЕ ТЕКСТ СООБЩЕНИЯ»,
}
executeSMSSending(smsDetails)
// Запускаем веб-сервер, чтобы он прослушивал порт 8080.
http.ListenAndServe(":8080", nil)
}
// processIncomingSMS обрабатывает входящие SMS-запросы.
func processIncomingSMS(responseWriter http.ResponseWriter, request *http.Request) {
// Проверка на использование метода POST.
if request.Method != http.MethodPost {
http.Error(responseWriter, "Only POST is Supported", http.StatusMethodNotAllowed)
return
}
// Чтение данных из тела запроса.
requestBody, readError := io.ReadAll(request.Body)
if readError != nil {
http.Error(responseWriter, "Failed to Read Body", http.StatusInternalServerError)
return
}
// Конвертируем полученные данные в структуру SMSData.
var smsDetails SMSContent
unmarshalError := json.Unmarshal(requestBody, &smsDetails)
if unmarshalError != nil {
http.Error(responseWriter, "JSON Conversion Failed", http.StatusBadRequest)
return
}
// Выполнение отправки SMS.
executeSMSSending(smsDetails)
// Логирование информации о запросе.
fmt.Printf("SMS Request Processed: %+v\n", smsDetails)
// Подтверждение успешного приёма запроса.
responseWriter.WriteHeader(http.StatusOK)
responseWriter.Header().Set("Content-Type", "application/json")
successResponse := map[string]string{"message": "Successfully processed SMS"}
successJSON, _ := json.Marshal(successResponse)
responseWriter.Write(successJSON)
}
// executeSMSSending обращается к внешнему API для отправки SMS.
func executeSMSSending(smsData SMSContent) {
endpointURL := "https://api.exolve.ru/messaging/v1/SendSMS"
// Преобразуем данные для отправки в формате JSON.
smsJSON, marshalErr := json.Marshal(smsData)
if marshalErr != nil {
fmt.Println("Error converting SMS data to JSON:", marshalErr)
return
}
// Создание запроса к API для отправки SMS.
apiRequest, requestErr := http.NewRequest("POST", endpointURL, bytes.NewBuffer(smsJSON))
if requestErr != nil {
fmt.Println("Error creating API request:", requestErr)
return
}
// Настройка заголовков HTTP-запроса.
apiRequest.Header.Set("Content-Type", "application/json")
apiRequest.Header.Set("Authorization", «Bearer ВАШ ТОКЕН АВТОРИЗАЦИИ») // Укажите здесь ваш токен.
// Инициализация клиента для отправки запроса.
httpClient := &http.Client{}
apiResponse, apiErr := httpClient.Do(apiRequest)
if apiErr != nil {
fmt.Println("Error sending request to the API:", apiErr)
return
}
defer apiResponse.Body.Close()
// Обработка и вывод ответа от API.
responseBody, readErr := io.ReadAll(apiResponse.Body)
if readErr != nil {
fmt.Println("Error reading the response body:", readErr)
return
}
fmt.Printf("API Response: %s\n", string(responseBody))
}
This code allows you to test API Exolve to send SMS. All that remains is to add your valid token in the format “Bearer your token”, specify the sender and recipient numbers and the SMS text.
The last step is to test our server. Open a terminal (make sure you are in the directory where your send.go file is located) and enter the command go run send.go.
![](https://habrastorage.org/getpro/habr/upload_files/069/e00/c4b/069e00c4b66fa6c65c85ec82392d6654.png)
This command will launch our server, which will make a request to the MTS Exolve API with the inserted values: sender and recipient numbers and SMS text. As a result, a message from the number to which our MTS Exolve account is linked will be sent to the specified contacts.
![](https://habrastorage.org/getpro/habr/upload_files/bc5/3fa/cde/bc53facde19f2a2016d3f226ce8a78cf.jpg)
![](https://habrastorage.org/getpro/habr/upload_files/2c3/1cb/c69/2c31cbc690d163cdf042e9d48eea122f.jpg)
So, we have considered the option for SMS notifications via the MTS Exolve service. Also link You can read detailed and clear documentation.
Conclusion
Using third-party APIs to send messages is a valuable tool when developing applications. The key advantages of such services are easy setup, extensive documentation, and effective technical support. In case of difficulties, you can contact the chat and quickly get answers from specialists, which significantly simplifies problem solving and speeds up the development process.