From bc5999ba6fe9da281b2157a712567dc38af2a854 Mon Sep 17 00:00:00 2001 From: cn-hideyoshi <645165778@qq.com> Date: Wed, 11 Dec 2024 18:52:08 +0800 Subject: [PATCH] oa file --- weixin/base.go | 1 + weixin/oa_sdk.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/weixin/base.go b/weixin/base.go index 3a30e6c..1da7e23 100644 --- a/weixin/base.go +++ b/weixin/base.go @@ -21,6 +21,7 @@ const ( CreateOaMenu string = "https://api.weixin.qq.com/cgi-bin/menu/create" QueryOaMenu string = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info" DeleteOaMenu string = "https://api.weixin.qq.com/cgi-bin/menu/delete" + UploadOaMedia string = "https://api.weixin.qq.com/cgi-bin/media/upload" ) const ( diff --git a/weixin/oa_sdk.go b/weixin/oa_sdk.go index 6e9e43d..5551c45 100644 --- a/weixin/oa_sdk.go +++ b/weixin/oa_sdk.go @@ -6,7 +6,9 @@ import ( "fmt" "github.com/tidwall/gjson" "io" + "mime/multipart" "net/http" + "time" ) type OaSdk struct { @@ -98,6 +100,39 @@ func (o *OaSdk) GetUserInfoByOpenid(openid string) (*UserInfo, error) { return user, nil } +func (o *OaSdk) UploadFileByByte(file []byte, ext string) (string, string, error) { + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + formFile, err := writer.CreateFormFile("file", fmt.Sprintf("%d%s", time.Now().Unix(), ext)) + if err != nil { + return "", "", err + } + _, err = formFile.Write(file) + if err != nil { + return "", "", err + } + err = writer.Close() + if err != nil { + return "", "", err + } + res, err := http.Post(UploadOaMedia, writer.FormDataContentType(), body) + if err != nil { + return "", "", err + } + resBody, err := io.ReadAll(res.Body) + if err != nil { + return "", "", err + } + g := gjson.ParseBytes(resBody) + errCode := g.Get("errcode").Int() + if errCode != 0 { + return "", "", fmt.Errorf("%d:%s", errCode, g.Get("errmsg").String()) + } + fileType := g.Get("type").String() + fileId := g.Get("media_id").String() + return fileType, fileId, nil +} + func (o *OaSdk) CreateMenu(buttons []*OaMenuButton) error { accessToken, err := o.getAccessToken() if err != nil {