package ca import ( "crypto/hmac" "crypto/sha1" "encoding/hex" "encoding/json" "errors" "hospital-admin-api/config" "io" "net/http" "net/url" "sort" "strings" ) type Response struct { ResultCode int `json:"result_code"` ResultMsg string `json:"result_msg"` Body interface{} `json:"body"` Success bool `json:"success"` } // GenerateSignature 生成签名 func GenerateSignature(paramMap map[string]interface{}) string { keys := make([]string, 0, len(paramMap)) for k := range paramMap { if k == "pdfFile" { continue } keys = append(keys, k) } sort.Strings(keys) var toSign string for _, k := range keys { v, ok := paramMap[k].(string) if !ok { return "" } toSign += v + "&" } toSign = strings.TrimSuffix(toSign, "&") // Step 3: Calculate HMAC-SHA1 and convert to hex format h := hmac.New(sha1.New, []byte(config.C.CaOnline.CaOnlineAppSecret)) h.Write([]byte(toSign)) signature := hex.EncodeToString(h.Sum(nil)) return signature } // 统一请求 func postRequest(requestUrl string, formData url.Values, signature string) (map[string]interface{}, error) { payload := strings.NewReader(formData.Encode()) // 创建 POST 请求 req, err := http.NewRequest("POST", requestUrl, payload) if err != nil { return nil, err } // 设置请求头 req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("app_id", config.C.CaOnline.CaOnlineAppId) req.Header.Add("signature", signature) // 创建 HTTP 请求客户端 client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) if resp.StatusCode != 200 { return nil, errors.New("ca请求失败") } // 读取响应内容 respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var response Response err = json.Unmarshal([]byte(respBody), &response) if err != nil { // json解析失败 return nil, err } if response.ResultCode != 0 { if response.ResultMsg != "" { return nil, errors.New(response.ResultMsg) } else { return nil, errors.New("请求ca失败") } } body := make(map[string]interface{}) if response.Body != nil || response.Body != "" { bodyMap, ok := response.Body.(map[string]interface{}) if ok { body = bodyMap } } if len(body) == 0 { return nil, nil } return body, nil }