package lib import ( "bytes" "encoding/json" "fmt" "io/ioutil" "kefu/tools" "log" "net/http" "time" ) //chatGLM新版 type GLM struct { ApiKey string PublicKey string } func NewGLM(apiKey, publicKey string) (*GLM, error) { glm := &GLM{ ApiKey: apiKey, PublicKey: publicKey, } return glm, nil } func (this *GLM) GetAccessToken() (string, error) { encrypted, err := this.RSAEncrypt(fmt.Sprintf("%d", time.Now().UnixNano()/1e6)) if err != nil { return "", err } // 构造请求体 requestBody := map[string]interface{}{ "apiKey": this.ApiKey, "encrypted": encrypted, } requestBodyBytes, err := json.Marshal(requestBody) if err != nil { return "", err } // 构造请求 url := "https://maas.aminer.cn/api/paas/passApiToken/createApiToken" log.Println(requestBody, time.Now().UnixNano()/1e6) request, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(requestBodyBytes)) if err != nil { return "", err } request.Header.Set("Content-Type", "application/json") // 发送请求 client := http.DefaultClient response, err := client.Do(request) if err != nil { return "", err } defer response.Body.Close() // 处理响应 responseBody, err := ioutil.ReadAll(response.Body) if err != nil { return "", err } return string(responseBody), nil } func (this *GLM) RSAEncrypt(content string) (string, error) { rsa := tools.NewRsa(fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", this.PublicKey), "") res, err := rsa.Encrypt([]byte(content)) newStr := tools.Base64Encode(string(res)) return newStr, err }