rzh #2
|
@ -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 (
|
||||
|
|
|
@ -6,7 +6,9 @@ import (
|
|||
"fmt"
|
||||
"github.com/tidwall/gjson"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type OaSdk struct {
|
||||
|
@ -98,6 +100,60 @@ 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
|
||||
}
|
||||
token, err := o.getAccessToken()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
postType := ""
|
||||
if ext == ".jpg" || ext == ".png" || ext == ".gif" || ext == ".jpeg" {
|
||||
postType = "image"
|
||||
} else if ext == ".mp4" {
|
||||
postType = "video"
|
||||
} else if ext == ".mp3" {
|
||||
postType = "voice"
|
||||
}
|
||||
|
||||
if postType == "" {
|
||||
return "", "", fmt.Errorf("不支持的文件类型")
|
||||
}
|
||||
|
||||
res, err := http.Post(
|
||||
fmt.Sprintf("%s?access_token=%s&type=%s", UploadOaMedia, token, postType),
|
||||
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 {
|
||||
|
|
Loading…
Reference in New Issue