package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
const (
corpid = "企业代号"
agentId = "1000004"
corpsecret = "企业密钥"
)
func httpGetJson(url string) (map[string]interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var data map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, err
}
return data, nil
}
func httpPostJson(url string, data map[string]interface{}) (map[string]interface{}, error) {
xxx, err := json.Marshal(data)
if err != nil {
return nil, err
}
resp, err := http.Post(url, "application/json", bytes.NewReader(xxx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var data2 map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, err
}
return data2, nil
}
func main() {
url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpid, corpsecret)
data, err := httpGetJson(url)
if err != nil {
fmt.Println(err)
return
}
errcode := data["errcode"].(float64)
if errcode != 0 {
fmt.Println("errcode: ", errcode)
return
}
access_token := data["access_token"]
req := map[string]interface{}{
"touser": "@all",
"msgtype": "text",
"agentid": agentId,
"text": map[string]interface{}{
"content": "hello",
},
}
url = fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", access_token)
data, err = httpPostJson(url, req)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("ok")
}