From 45b0bfde330001a182e05a2ddcafb11f336e530b Mon Sep 17 00:00:00 2001 From: cn-hideyoshi <645165778@qq.com> Date: Tue, 10 Dec 2024 19:19:12 +0800 Subject: [PATCH] oa menu --- weixin/base.go | 16 ++++++++++++++++ weixin/oa_sdk.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/weixin/base.go b/weixin/base.go index f12cfde..de1cfb7 100644 --- a/weixin/base.go +++ b/weixin/base.go @@ -18,6 +18,14 @@ const ( code2UserinfoUrl string = "https://api.weixin.qq.com/sns/userinfo" oaQrCodeCreateUrl string = "https://api.weixin.qq.com/cgi-bin/qrcode/create" userInfoByOpenid string = "https://api.weixin.qq.com/cgi-bin/user/info" + 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" +) + +const ( + OaMenuTypeClick = "click" + OaMenuTypeView = "view" ) type UserInfo struct { @@ -40,6 +48,14 @@ type BaseSdk struct { lock sync.Mutex } +type OaMenuButton struct { + Type string `json:"type"` + Name string `json:"name"` + Key string `json:"key,omitempty"` + Url string `json:"url,omitempty"` + SubButton []*OaMenuButton `json:"sub_button"` +} + func (o *BaseSdk) getAccessToken() (string, error) { o.lock.Lock() defer o.lock.Unlock() diff --git a/weixin/oa_sdk.go b/weixin/oa_sdk.go index dbbe0f1..6e9e43d 100644 --- a/weixin/oa_sdk.go +++ b/weixin/oa_sdk.go @@ -97,3 +97,52 @@ func (o *OaSdk) GetUserInfoByOpenid(openid string) (*UserInfo, error) { user.Openid = openid return user, nil } + +func (o *OaSdk) CreateMenu(buttons []*OaMenuButton) error { + accessToken, err := o.getAccessToken() + if err != nil { + return err + } + + bodyMp := make(map[string]interface{}) + bodyMp["button"] = buttons + bodyBytes, _ := json.Marshal(bodyMp) + + url := fmt.Sprintf("%s?access_token=%s", CreateOaMenu, accessToken) + res, err := http.Post(url, "application/json", bytes.NewBuffer(bodyBytes)) + if err != nil { + return err + } + all, err := io.ReadAll(res.Body) + if err != nil { + return err + } + g := gjson.ParseBytes(all) + errCode := g.Get("errcode").Int() + if errCode != 0 { + return fmt.Errorf("%d:%s", errCode, g.Get("errmsg").String()) + } + return nil +} + +func (o *OaSdk) DeleteMenu() error { + accessToken, err := o.getAccessToken() + if err != nil { + return err + } + url := fmt.Sprintf("%s?access_token=%s", DeleteOaMenu, accessToken) + res, err := http.Get(url) + if err != nil { + return err + } + all, err := io.ReadAll(res.Body) + if err != nil { + return err + } + g := gjson.ParseBytes(all) + errCode := g.Get("errcode").Int() + if errCode != 0 { + return fmt.Errorf("%d:%s", errCode, g.Get("errmsg").String()) + } + return nil +}