2023-07-07 17:58:38 +08:00

95 lines
1.9 KiB
Go

package tencentIm
import (
"bytes"
"encoding/json"
"errors"
"hospital-admin-api/config"
"io"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
)
// GetUserSign 获取签名
func GetUserSign(userId string) (string, error) {
if userId == "" {
userId = "administrator"
}
ImAppID := config.C.Im.ImAppID
ImSecret := config.C.Im.ImSecret
sign, err := GenUserSig(ImAppID, ImSecret, userId, 86400*180)
if err != nil || sign == "" {
return "", errors.New("签名获取失败")
}
return sign, err
}
// 获取请求链接
func getRequestUrlParams(userId string) (bool, string) {
// 获取签名
// 获取签名
sign, err := GetUserSign(userId)
if err != nil {
return false, err.Error()
}
rand.Seed(time.Now().UnixNano())
params := url.Values{}
params.Set("sdkappid", strconv.Itoa(config.C.Im.ImAppID))
params.Set("identifier", "administrator")
params.Set("usersig", sign)
params.Set("random", strconv.Itoa(rand.Intn(4294967296)))
params.Set("contenttype", "json")
queryString := params.Encode()
return true, queryString
}
// 统一请求
func postRequest(url string, requestBody []byte) (map[string]interface{}, error) {
responseMap := make(map[string]interface{})
// 发起 POST 请求
resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(string(body)), &responseMap)
if err != nil {
// json解析失败
return nil, err
}
if responseMap == nil {
return nil, errors.New("请求im失败")
}
if errorCode, ok := responseMap["ErrorCode"]; ok {
if errorCode != 0 {
if errorInfo, ok := responseMap["ErrorInfo"].(string); ok {
return nil, errors.New(errorInfo)
} else {
return nil, errors.New("请求im失败")
}
}
}
return responseMap, nil
}