package service import ( "encoding/json" "fmt" "log" "accounting-app/internal/config" "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi" ) // SmsService handles SMS notifications type SmsService struct { client *dysmsapi.Client signName string templateCode string enabled bool } // NewSmsService creates a new SmsService instance func NewSmsService(cfg *config.Config) *SmsService { if cfg.AliyunAccessKeyID == "" || cfg.AliyunAccessKeySecret == "" { log.Println("Aliyun SMS configuration missing, SMS service disabled") return &SmsService{enabled: false} } client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", cfg.AliyunAccessKeyID, cfg.AliyunAccessKeySecret) if err != nil { log.Printf("Failed to initialize Aliyun SMS client: %v", err) return &SmsService{enabled: false} } return &SmsService{ client: client, signName: cfg.AliyunSignName, templateCode: cfg.AliyunTemplateCode, enabled: true, } } // SendAllocationNotification sends an SMS notification for auto allocation func (s *SmsService) SendAllocationNotification(phoneNumber string, totalAmount float64, ruleName string) error { if !s.enabled || phoneNumber == "" { return nil } request := dysmsapi.CreateSendSmsRequest() request.Scheme = "https" request.PhoneNumbers = phoneNumber request.SignName = s.signName request.TemplateCode = s.templateCode // Template params: {"amount": "1000", "rule": "Salary Allocation"} // You might need to adjust parameters based on your actual Aliyun template params := map[string]string{ "amount": fmt.Sprintf("%.2f", totalAmount), "rule": ruleName, } paramBytes, _ := json.Marshal(params) request.TemplateParam = string(paramBytes) response, err := s.client.SendSms(request) if err != nil { return fmt.Errorf("failed to send SMS: %w", err) } if response.Code != "OK" { return fmt.Errorf("aliyun SMS error: %s - %s", response.Code, response.Message) } log.Printf("SMS sent successfully to %s", phoneNumber) return nil }