Explorar el Código

create custom menu

master
Patrick Peng Sun hace 8 años
padre
commit
7759b8dad8
Se han modificado 1 ficheros con 85 adiciones y 0 borrados
  1. +85
    -0
      wechatCustomMenu.go

+ 85
- 0
wechatCustomMenu.go Ver fichero

@@ -1 +1,86 @@
package main

import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)

//menu is a json definition
var menu = []byte(`
{
"button":[
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.soso.com/"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
}]
}
`)

//CreateCustomMenu bulid a menu for wechat windows
// 3 main manu max (< 4 mandarin words)
// 5 sub items max (< 7 mandarin words)
//success return nil
//error return err
func CreateCustomMenu(m []byte) error {
atoken, err := GetAccessToken()
if err != nil {
return err
}
url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", atoken)
if len(m) == 0 {
m = menu //using default menu
}
return jsonPostRequest(url, m)

}

//CreateDefaultMenu build a menu for wechat window
//
func CreateDefaultMenu() error {
var b []byte
return CreateCustomMenu(b)
}

//jsonPostRequest perform http post request with json body
// url is the url to post to
// jsonBody is the payload in http post request
func jsonPostRequest(url string, jsonBody []byte) error {
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
return err
}
req.Header.Set("X-Custom-Header", "Patrick Sun")
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)

if err != nil {
return err
}
defer resp.Body.Close()

fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))

return nil
}

Cargando…
Cancelar
Guardar