Files
sigmasms/flash_call.go
2025-12-03 19:45:24 +03:00

106 lines
2.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package sigmasms
import (
"crypto/rand"
"fmt"
"log"
"time"
"github.com/google/uuid"
)
/*
{
"recipient": "+79999999999",
"type": "flashcall",
"payload": {
"sender": "Имя отправителя",
"text": "1234"
}
}
*/
type FlashCallRequest struct {
Recepient string `json:"recipient"`
Type string `json:"type"`
Payload Payload `json:"payload"`
}
type FlashCallResponse struct {
ID uuid.UUID `json:"id"`
Price float64 `json:"price"`
Recepient string `json:"recipient"`
Status string `json:"status"`
Error string `json:"error"`
}
// GenerateRandomDigits генерирует строку из четырёх случайных цифр.
func GenerateFreshcCallCode() (string, error) {
var b [2]byte
_, err := rand.Read(b[:])
if err != nil {
return "", err
}
// Превращаем 2 байта в число
num := int(b[0])<<8 | int(b[1])
// Ограничиваем диапазон 09999
num = num % 10000
// Возвращаем строку с ведущими нулями
return fmt.Sprintf("%04d", num), nil
}
func FlashCall(apiKey, phone, sender string, code string) (*FlashCallResponse, error) {
req := FlashCallRequest{
Recepient: phone,
Type: "flashcall",
Payload: Payload{
Sender: sender,
Text: code,
},
}
var resp FlashCallResponse
err := requestPost("https://user.sigmasms.ru/api/sendings", apiKey, &req, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
func FlashCallWait(apiKey, phone, sender string, code string) (transactionID uuid.UUID, err error) {
var resp *FlashCallResponse
if resp, err = FlashCall(apiKey, phone, sender, code); err != nil {
log.Println(err)
return
} else {
if resp.Status == "failed" {
err = fmt.Errorf("flashcall send error: %s", resp.Error)
return
}
transactionID = resp.ID
var sResp *StatusResponse
mainLoop:
for resp.Status == "pending" {
time.Sleep(time.Millisecond * 100)
sResp, err = RequestStatus(resp.ID, apiKey)
if err != nil {
return
}
resp.Status = sResp.State.Status
switch resp.Status {
case "pending", "sent":
continue mainLoop
case "seen", "delivered":
return
default:
err = fmt.Errorf("sms status: %s", sResp.State.Status)
}
}
}
return
}