Skip to content

Commit

Permalink
🐛签名标准化
Browse files Browse the repository at this point in the history
🎨 使用logrus日志包
  • Loading branch information
T-Manson committed Mar 1, 2021
1 parent 86ab6ab commit bc00ff2
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 43 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@
.idea

# vscode
.vscode
.vscode

go.sum
20 changes: 10 additions & 10 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"

"github.com/T-Manson/meituan-sdk-go/meituan"
"github.com/sirupsen/logrus"
)

const (
Expand All @@ -35,16 +35,16 @@ func main() {
// 通过out参数返回
poiMgetResponse := &meituan.ListMapResponse{}
if err := poiMgetRequest.CallRemote(poiMgetResponse); err != nil {
fmt.Println("[Error][MeiTuan]CallRemote ", poiMget, err.Error())
logrus.Errorln("[MeiTuan]CallRemote ", poiMget, err.Error())
} else {
fmt.Println(poiMgetResponse.Json())
logrus.Debugln(poiMgetResponse.Json())
}

// 通过return结果返回
if reps, err := poiMgetRequest.CallListMapRemote(); err != nil {
fmt.Println("[Error][MeiTuan]CallRemote ", poiMget, err.Error())
logrus.Errorln("[MeiTuan]CallRemote ", poiMget, err.Error())
} else {
fmt.Println(reps.Json())
logrus.Debugln(reps.Json())
}

// POST poi/online 门店设置为上线状态
Expand All @@ -56,9 +56,9 @@ func main() {

poiOnlineResponse := &meituan.Response{}
if err := poiOnlineRequest.CallRemote(poiOnlineResponse); err != nil {
fmt.Println("[Error][MeiTuan]CallRemote ", poiOnline, err.Error())
logrus.Errorln("[MeiTuan]CallRemote ", poiOnline, err.Error())
} else {
fmt.Println(poiOnlineResponse.Json())
logrus.Debugln(poiOnlineResponse.Json())
}

// 模拟一个美团请求过程
Expand All @@ -82,16 +82,16 @@ func main() {

// 2. 解析美团请求体
if err := meiTuanRequest.ParseRequestParams(body); err != nil {
fmt.Println("[Error][MeiTuan]ParseRequestParams ", err.Error())
logrus.Errorln("[MeiTuan]ParseRequestParams ", err.Error())
}

// 3. 验签
checkResult := meiTuanRequest.CheckPushSign()
fmt.Println("[Info][MeiTuan]CheckPushSign result: ", checkResult)
logrus.Infoln("[MeiTuan]CheckPushSign result: ", checkResult)

// 4. Do something after CheckPushSign Success
if checkResult {
jsonBytes, _ := json.Marshal(meiTuanRequest)
fmt.Println("[Info][MeiTuan]Request info: ", string(jsonBytes))
logrus.Infoln("[MeiTuan]Request info: ", string(jsonBytes))
}
}
58 changes: 31 additions & 27 deletions meituan/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"net/url"
"strconv"
"strings"

"github.com/sirupsen/logrus"
)

// 美团POST请求正文类型
Expand Down Expand Up @@ -59,7 +61,7 @@ func (req Request) CheckPushSign() bool {
if req.Sig == "" {
return false
}
sign, _, _ := req.makeSign()
sign, _ := req.makeSign()
return req.Sig == sign
}

Expand All @@ -70,7 +72,7 @@ func (req Request) GetDataValue(key string) string {
return ""
}

func (req *Request) AddData(key string, value string) {
func (req *Request) AddData(key, value string) {
if req.Data == nil {
req.Data = make(map[string]string)
}
Expand All @@ -91,7 +93,7 @@ func (req *Request) ParseRequestParams(reqBody string) error {
// Why decode twice? see: http://developer.waimai.meituan.com/home/guide/6
var unescapeValuesStr string
if unescapeValuesStr, err = url.QueryUnescape(reqBody); err != nil {
fmt.Println("[Error]ParseRequestParams QueryUnescape1 ", err.Error())
logrus.Errorln("ParseRequestParams QueryUnescape1 ", err.Error())
return err
}

Expand All @@ -104,28 +106,28 @@ func (req *Request) ParseRequestParams(reqBody string) error {
}

if timestamp, ok = req.Data["timestamp"]; !ok {
errMsg := "[Error]ParseRequestParams timestamp can not be empty"
fmt.Println(errMsg)
errMsg := "ParseRequestParams timestamp can not be empty"
logrus.Errorln(errMsg)
return fmt.Errorf(errMsg)
}
delete(req.Data, "timestamp")

if appId, ok = req.Data["app_id"]; !ok {
errMsg := "[Error]ParseRequestParams app_id can not be empty"
fmt.Println(errMsg)
errMsg := "ParseRequestParams app_id can not be empty"
logrus.Errorln(errMsg)
return fmt.Errorf(errMsg)
}
delete(req.Data, "app_id")

if sig, ok = req.Data["sig"]; !ok {
errMsg := "[Error]ParseRequestParams sig can not be empty"
fmt.Println(errMsg)
errMsg := "ParseRequestParams sig can not be empty"
logrus.Errorln(errMsg)
return fmt.Errorf(errMsg)
}
delete(req.Data, "sig")

if req.Timestamp, err = strconv.ParseInt(timestamp, 10, 64); err != nil {
fmt.Println("[Error]ParseRequestParams ParseInt ", err.Error())
logrus.Errorln("ParseRequestParams ParseInt ", err.Error())
return err
}
req.AppId = appId
Expand All @@ -134,19 +136,18 @@ func (req *Request) ParseRequestParams(reqBody string) error {
return nil
}

func (req *Request) getFinalRequestUrl() (finalRequestUrl string, applicationParamStr string) {
func (req *Request) getFinalRequestUrl() (finalRequestUrl, applicationParamStr string) {
req.Timestamp = MakeTimestamp()
req.AppId = commonConfig.appId

var signValuesStr string
req.Sig, signValuesStr, applicationParamStr = req.makeSign()
req.Sig, applicationParamStr = req.makeSign()

var finalRequestUrlValuesStr string
switch req.HttpMethod {
case http.MethodPost:
finalRequestUrlValuesStr = fmt.Sprintf("%s?app_id=%s&timestamp=%v", req.RequestUrl, req.AppId, req.Timestamp)
default:
finalRequestUrlValuesStr = strings.Replace(signValuesStr, commonConfig.consumerSecret, "", -1)
finalRequestUrlValuesStr = applicationParamStr
}
finalRequestUrl = fmt.Sprintf("%s&sig=%s", finalRequestUrlValuesStr, req.Sig)
return
Expand All @@ -171,18 +172,19 @@ func (req *Request) getFinalRequestUrl() (finalRequestUrl string, applicationPar
// timestamp: request timestamp
//
// secret: secret
func (req *Request) makeSign() (sign string, signValuesStr string, applicationParamStr string) {
func (req *Request) makeSign() (sign, getUrl string) {
if req.RequestUrl == "" || req.AppId == "" || req.Timestamp == 0 {
return "", "", ""
return "", ""
}

signValuesStr, applicationParamStr = getSignValuesStr(req)
fmt.Println("[Info][]makeSign sigValuesStr is: ", signValuesStr)
var signValuesStr string
signValuesStr, getUrl = getSignValuesStr(req)
logrus.Infoln("makeSign sigValuesStr is: ", signValuesStr)
md5Tool := md5.New()
md5Tool.Write([]byte(signValuesStr))
md5Bytes := md5Tool.Sum(nil)
sign = hex.EncodeToString(md5Bytes)
fmt.Println("[Info][]makeSign sign is: ", sign)
logrus.Infoln("makeSign sign is: ", sign)
return
}

Expand Down Expand Up @@ -218,36 +220,38 @@ func callApi(req Request) (*http.Response, error) {

client := http.Client{}

fmt.Println("[Info][]callApi requestUrl ", req.RequestUrl)
logrus.Infoln("callApi requestUrl ", req.RequestUrl)
finalRequestUrl, applicationParamStr = req.getFinalRequestUrl()
fmt.Println("[Info][]callApi finalRequestUrl ", finalRequestUrl)
logrus.Infoln("callApi finalRequestUrl ", finalRequestUrl)

// 美团Api请求方式仅有Post、Get两种模式
switch req.HttpMethod {
case http.MethodPost:
fmt.Println("[Info][]callApi POST data: ", applicationParamStr)
logrus.Infoln("callApi POST data: ", applicationParamStr)
response, err = client.Post(finalRequestUrl, HTTP_POST_CONTENT_TYPE,
strings.NewReader(applicationParamStr))
default:
response, err = client.Get(finalRequestUrl)
}

if err != nil {
fmt.Println("[Error][]callApi ", req.RequestUrl, err.Error())
logrus.Errorln("callApi ", req.RequestUrl, err.Error())
return nil, err
}

return response, nil
}

// getSignValuesStr 返回:签名使用的字符串、应用参数form格式字符串
func getSignValuesStr(req *Request) (signValuesStr string, applicationParamStr string) {
func getSignValuesStr(req *Request) (signValuesStr, getUrl string) {
values := req.parseDataToHttpUrlValues()
applicationParamStr = values.Encode()

values.Add("timestamp", strconv.FormatInt(req.Timestamp, 10))
values.Add("app_id", req.AppId)
valuesStr, _ := url.QueryUnescape(values.Encode())
applicationParamStr := values.Encode()

getUrl = fmt.Sprintf("%s?%s", req.RequestUrl, applicationParamStr)

valuesStr, _ := url.QueryUnescape(applicationParamStr)
signValuesStr = fmt.Sprintf("%s?%s%s", req.RequestUrl, valuesStr, commonConfig.consumerSecret)
return
}
12 changes: 7 additions & 5 deletions meituan/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"io/ioutil"
"net/http"
"strings"

"github.com/sirupsen/logrus"
)

// BaseResponse 基础响应
Expand Down Expand Up @@ -94,20 +96,20 @@ func ParseResponse(resp *http.Response, outResp BaseResponse) error {

if resp.StatusCode == http.StatusOK {
if result, err = checkResponseBody(resp.Body); err != nil {
fmt.Println("[Error][]GetResponse checkResponseBody ", err.Error())
logrus.Errorln("GetResponse checkResponseBody ", err.Error())
_ = outResp.Parse(result)
return err
} else {
fmt.Println("[Info][]GetResponse Response ", string(result))
logrus.Infoln("GetResponse Response ", string(result))
return outResp.Parse(result)
}
} else {
result, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("[Error][]GetResponse code: %v body: %s", resp.StatusCode, string(result))
return fmt.Errorf("GetResponse code: %v body: %s", resp.StatusCode, string(result))
}
}

fmt.Println("[Info][]GetResponse Response is empty")
logrus.Infoln("GetResponse Response is empty")
return nil
}

Expand All @@ -123,7 +125,7 @@ func checkResponseBody(body io.ReadCloser) (result []byte, err error) {
if err = meiTuanResponse.Parse(result); err == nil {
// 美团响应data为ng时,为处理失败
if strings.ToLower(meiTuanResponse.Data) == "ng" {
err = fmt.Errorf("[Error][]checkResponseBody response.data equels ng. error:%+v", meiTuanResponse.Error)
err = fmt.Errorf("checkResponseBody response.data equels ng. error:%+v", meiTuanResponse.Error)
return
}
}
Expand Down

0 comments on commit bc00ff2

Please sign in to comment.