企业微信Webhook消息发送的Golang封装

企业微信Webhook消息发送的Golang封装

演示网站:gofly.v1kf.com

下面是将这个curl请求封装成Golang方法的实现:

package wechatwork

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

// WebhookMessage 定义企业微信webhook消息结构
type WebhookMessage struct {
	MsgType string `json:"msgtype"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
}

// SendWebhookMessage 发送企业微信webhook消息
func SendWebhookMessage(webhookKey, content string) error {
	// 构造请求URL
	webhookURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s", webhookKey)

	// 构造消息体
	message := WebhookMessage{
		MsgType: "text",
		Text: struct {
			Content string `json:"content"`
		}{
			Content: content,
		},
	}

	// 将消息体转换为JSON
	jsonData, err := json.Marshal(message)
	if err != nil {
		return fmt.Errorf("failed to marshal message: %v", err)
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", webhookURL, bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("failed to create request: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("failed to read response: %v", err)
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(body))
	}

	// 解析响应JSON
	var result struct {
		ErrCode int    `json:"errcode"`
		ErrMsg  string `json:"errmsg"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return fmt.Errorf("failed to parse response: %v", err)
	}

	// 检查错误码
	if result.ErrCode != 0 {
		return fmt.Errorf("wechat work error: %d - %s", result.ErrCode, result.ErrMsg)
	}

	return nil
}

使用方法

package main

import (
	"log"
	"yourpackage/wechatwork" // 替换为实际的包路径
)

func main() {
	webhookKey := "693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa"
	message := "hello world"

	err := wechatwork.SendWebhookMessage(webhookKey, message)
	if err != nil {
		log.Fatalf("Failed to send message: %v", err)
	}
	log.Println("Message sent successfully")
}

功能扩展

如果需要发送更复杂的消息类型(如图片、markdown等),可以扩展WebhookMessage结构体。例如:

type WebhookMessage struct {
	MsgType  string      `json:"msgtype"`
	Text     *Text       `json:"text,omitempty"`
	Markdown *Markdown   `json:"markdown,omitempty"`
	Image    *Image      `json:"image,omitempty"`
	News     *News       `json:"news,omitempty"`
}

type Text struct {
	Content             string   `json:"content"`
	MentionedList       []string `json:"mentioned_list,omitempty"`
	MentionedMobileList []string `json:"mentioned_mobile_list,omitempty"`
}

type Markdown struct {
	Content string `json:"content"`
}

type Image struct {
	Base64 string `json:"base64"`
	Md5    string `json:"md5"`
}

type News struct {
	Articles []Article `json:"articles"`
}

type Article struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	URL         string `json:"url"`
	PicURL      string `json:"picurl"`
}

然后可以创建不同的构造方法来创建不同类型的消息。

posted @ 2025-06-22 09:16  唯一客服系统开发笔记  阅读(52)  评论(0)    收藏  举报