Files
baseapi/platformapi/uuptapi/uuptapi.go
richboo111 73a597fddb 1
2023-01-04 18:32:59 +08:00

104 lines
2.8 KiB
Go

package uuptapi
import (
"crypto/md5"
"encoding/json"
"fmt"
"git.rosy.net.cn/baseapi/platformapi"
"git.rosy.net.cn/baseapi/utils"
"math/rand"
"net/http"
"sort"
"strings"
"time"
)
const (
ReturnSuccess = "ok"
ReturnFail = "fail"
signKey = "sign"
secretKey = "secret"
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
)
func (a *API) MakeUURequestHead() map[string]interface{} {
requestParam := make(map[string]interface{}, 5)
requestParam["sign"] = a.sign
requestParam["timestamp"] = a.timestamp
requestParam["nonce_str"] = a.noncestr
requestParam["openid"] = a.openid
requestParam["appid"] = a.appid
return requestParam
}
func New(appID, appKey, openID string) *API {
if appID == "" {
return nil
}
return &API{
appid: appID,
appKey: appKey,
openid: openID,
}
}
func (a *API) signParam(params map[string]interface{}) (sign string) {
keyValues := make([]string, 0)
for k, v := range params {
if k != signKey {
if temp := fmt.Sprint(v); temp != "" {
keyValues = append(keyValues, k+"="+temp)
}
}
}
sort.Sort(sort.StringSlice(keyValues)) //字典升序
sign = strings.Join(keyValues, "&")
sign += "&key=" + a.appKey //末尾拼接密钥
sign = strings.ToUpper(sign) //大写
return fmt.Sprintf("%X", md5.Sum([]byte(sign)))
}
func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
bizParams["timestamp"] = utils.Int64ToStr(time.Now().Unix() * 1000)
bizParams["sign"] = a.signParam(bizParams)
//序列化
data, err := json.Marshal(bizParams)
if err != nil {
return nil, err
}
//完整请求url
fullPath := utils.GenerateGetURL(baseUrl, actionApi, nil)
//发送请求
sendUrl := func() *http.Request {
var request *http.Request
if method == RequestPost {
request, _ = http.NewRequest(http.MethodPost, fullPath, strings.NewReader(string(data)))
} else {
request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
}
return request
}
//数据解析
dataMarshal := func(response *http.Response, bodyStr string, jsonResp map[string]interface{}) (errMsg string, err error) {
if jsonResp == nil {
return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
}
if jsonResp["return_code"] != ReturnSuccess {
errMsg = platformapi.ErrLevelGeneralFail
err = utils.NewErrorCode(jsonResp["return_msg"].(string), utils.Int64ToStr(utils.MustInterface2Int64(jsonResp["return_code"])))
}
retVal = jsonResp
return errMsg, err
}
err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
return retVal, err
}
//以下为辅助函数
func randStr() string {
b := make([]byte, 16)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}