httplib_sms_service.go 1.4 KB
package serviceGateway

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"time"

	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/serviceGateway/reply"
)

// 调用接口 发送短信消息
type SmsService struct {
}

const (
	sendNoticeSms string = "https://sms.fjmaimaimai.com:9897/service/sendNoticeSms"
)

// SendNoticeSms 发送短信消息
// phone 手机号
// tplId 短信模板id
// tplValues 短信模板中带的参数 具体根据定义的模板参数
func (ssrv SmsService) SendNoticeSms(phone string, tplId int, tplValues map[string]string) error {
	param := map[string]interface{}{
		"phone":     phone,
		"tplId":     tplId,
		"tplValues": tplValues,
	}

	buf := bytes.NewBuffer(nil)
	jEncode := json.NewEncoder(buf)
	err := jEncode.Encode(param)
	if err != nil {
		return err
	}
	req, err := http.NewRequest(http.MethodPost, sendNoticeSms, buf)
	if err != nil {
		return err
	}
	req.Header = map[string][]string{
		"Content-Type": {"application/json"},
	}
	httpclient := http.Client{
		Timeout: 30 * time.Second,
	}

	resp, err := httpclient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	var result reply.BaseReply
	jDecoder := json.NewDecoder(resp.Body)
	err = jDecoder.Decode(&result)
	if err != nil {
		bt, _ := io.ReadAll(resp.Body)
		fmt.Println(string(bt))
		return err
	}
	if result.Code != 0 {
		return errors.New(result.Msg)
	}
	return nil

}