申請公眾號
1、進入公眾號申請平台,選擇企業微信,按照步驟填寫信息,注冊完畢后登陸企業微信,點擊應用管理,選擇創建應用

2、所有圈起來的都是必填項,

3、創建完成后,會自動跳轉到當前所創建應用的管理界面,AgentID和Secret需要記錄下來,額外還要記錄企業ID(點擊我的企業下面有企業ID)

4、上面步驟企業微信號全部都已經完成了,接下來要進行腳本編寫
腳本代碼
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
)
// 企業微信報警
var (
h bool
user string
msg string
)
func init(){
flag.BoolVar(&h, "h", false, "this help")
flag.StringVar(&user, "user", "You want to send a message to that enterprise WeChat user or group", "")
flag.StringVar(&msg, "msg", "", "The content of the message you want to send")
}
type wc struct {
agentId int
companyId string
secretId string
wc_url string
}
func newWc(agentId int,companyId,secretId,wc_url string) *wc {
wl := &wc{
agentId: agentId,
companyId: companyId,
secretId: secretId,
wc_url: wc_url,
}
return wl
}
func (w *wc) getToken()interface{}{
client := &http.Client{}
url := fmt.Sprintf("%s?corpid=%s&corpsecret=%s",w.wc_url,w.companyId,w.secretId)
data,err := http.NewRequest("GET",url,nil)
if err != nil{
panic("獲取token失敗")
}
resp,err := client.Do(data)
body,err := ioutil.ReadAll(resp.Body)
// 處理獲取到的token
var jsonObj interface{}
err = json.Unmarshal(body, &jsonObj)
if err != nil {
panic("轉換json格式失敗")
}
token := jsonObj.(map[string]interface{})["access_token"]
return token
}
func (w *wc) sendMsg(to_user,msg string){
token := w.getToken()
msgsend_url :="https://qyapi.weixin.qq.com/cgi-bin/message/send"
url := fmt.Sprintf("%s?access_token=%v",msgsend_url,token)
fmt.Println("獲取到token",token)
// 攜帶token並發送消息至對應的企業微信
data := fmt.Sprintf(`{
"touser":"%v",
"msgtype":"text",
"agentid":%v,
"text":{
"content": "%v"
}
}`, to_user,w.agentId,msg)
var jsonStr = []byte(data)
req,err := http.NewRequest("POST",url,bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
if err != nil{
panic("發送消息失敗")
}
client := &http.Client{}
resp, err := client.Do(req)
body,err := ioutil.ReadAll(resp.Body)
var jsonObj interface{}
err = json.Unmarshal(body, &jsonObj)
if err != nil {
panic("轉換json格式失敗")
}
fmt.Println(string(body))
ok := jsonObj.(map[string]interface{})["errmsg"]
code := jsonObj.(map[string]interface{})["errcode"]
//fmt.Printf("%T,%T",ok,code)
if ok == "ok" && code == float64(0) {
fmt.Println("消息發送成功")
}else {
fmt.Println("消息發送失敗")
}
}
func main(){
flag.Parse()
if user == "" || msg == ""{
fmt.Println("參數不能為空")
os.Exit(1)
}
agentId := 12312312
companyId := "xxx"
secretId := "xxxx"
wx_url := "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
p := newWc(agentId,companyId,secretId,wx_url)
p.sendMsg(user,msg)
}
使用腳本
1.先編譯
go build
2.再使用
./腳本名 -user 發送給那個用戶 -msg 發送什么消息
