File size: 8,859 Bytes
6b5ca20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main

import (
	"crypto/tls"
	"embed"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
	_ "time/tzdata"
)

// 请求参数结构体
type RequestParams struct {
	Title      string `json:"title" form:"title"`
	Content    string `json:"content" form:"content"`
	AppID      string `json:"appid" form:"appid"`
	Secret     string `json:"secret" form:"secret"`
	UserID     string `json:"userid" form:"userid"`
	TemplateID string `json:"template_id" form:"template_id"`
	BaseURL    string `json:"base_url" form:"base_url"`
	Timezone   string `json:"tz" form:"tz"`
}

// 全局变量用于存储命令行参数
var (
	cliTitle      string
	cliContent    string
	cliAppID      string
	cliSecret     string
	cliUserID     string
	cliTemplateID string
	cliBaseURL    string
	startPort     string
	cliTimezone   string
)

// 微信AccessToken响应
type AccessTokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

// 微信模板消息请求
type TemplateMessageRequest struct {
	ToUser     string                 `json:"touser"`
	TemplateID string                 `json:"template_id"`
	URL        string                 `json:"url"`
	Data       map[string]interface{} `json:"data"`
}

// 微信API响应
type WechatAPIResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

func main() {
	// 定义命令行参数
	flag.StringVar(&cliTitle, "title", "", "消息标题")
	flag.StringVar(&cliContent, "content", "", "消息内容")
	flag.StringVar(&cliAppID, "appid", "", "AppID")
	flag.StringVar(&cliSecret, "secret", "", "AppSecret")
	flag.StringVar(&cliUserID, "userid", "", "openid")
	flag.StringVar(&cliTemplateID, "template_id", "", "模板ID")
	flag.StringVar(&cliBaseURL, "base_url", "", "跳转url")
	flag.StringVar(&cliTimezone, "tz", "Asia/Shanghai", "时区,默认东八区")
	flag.StringVar(&startPort, "port", "", "端口")

	// 解析命令行参数
	flag.Parse()

	// 设置路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, `go-wxpush is running...✅`)
	})
	http.HandleFunc("/wxsend", handleWxSend)
	http.HandleFunc("/detail", handleDetail)

	// 启动服务器
	//fmt.Println("Server is running on port 5566...")
	port := "5566"
	if startPort != "" {
		port = startPort
	}
	fmt.Println("Server is running on: " + "http://127.0.0.1:" + port)

	err := http.ListenAndServe(":"+port, nil)

	if err != nil {
		fmt.Printf("Error starting server: %v\n", err)
	}

}

// 嵌入静态HTML文件
//
//go:embed msg_detail.html
var htmlContent embed.FS

// 处理详情页面请求
func handleDetail(w http.ResponseWriter, r *http.Request) {
	// 从嵌入的资源中读取HTML内容
	htmlData, err := htmlContent.ReadFile("msg_detail.html")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, `{"error": "Failed to read embedded HTML file: %v"}`, err)
		return
	}

	// 设置响应头
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	// 返回HTML内容
	w.Write(htmlData)
}

func handleWxSend(w http.ResponseWriter, r *http.Request) {

	// 解析参数
	var params RequestParams

	// 根据请求方法解析参数
	if r.Method == "POST" {
		// 解析JSON请求体
		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&params)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			fmt.Fprintf(w, `{"error": "Invalid JSON format: %v"}`, err)
			return
		}
	} else if r.Method == "GET" {
		// 解析GET查询参数
		params.Title = r.URL.Query().Get("title")
		params.Content = r.URL.Query().Get("content")
		params.AppID = r.URL.Query().Get("appid")
		params.Secret = r.URL.Query().Get("secret")
		params.UserID = r.URL.Query().Get("userid")
		params.TemplateID = r.URL.Query().Get("template_id")
		params.BaseURL = r.URL.Query().Get("base_url")
		params.Timezone = r.URL.Query().Get("tz")
	} else {
		w.WriteHeader(http.StatusMethodNotAllowed)
		fmt.Fprintf(w, `{"error": "Method not allowed"}`)
		return
	}

	// 只有当GET/POST参数为空时,才使用命令行参数
	if params.Title == "" && cliTitle != "" {
		params.Title = cliTitle
	}
	if params.Content == "" && cliContent != "" {
		params.Content = cliContent
	}
	if params.AppID == "" && cliAppID != "" {
		params.AppID = cliAppID
	}
	if params.Secret == "" && cliSecret != "" {
		params.Secret = cliSecret
	}
	if params.UserID == "" && cliUserID != "" {
		params.UserID = cliUserID
	}
	if params.TemplateID == "" && cliTemplateID != "" {
		params.TemplateID = cliTemplateID
	}
	if params.BaseURL == "" && cliBaseURL != "" {
		params.BaseURL = cliBaseURL
	}
	if params.Timezone == "" && cliTimezone != "" {
		params.Timezone = cliTimezone
	}

	// 验证必要参数
	if params.AppID == "" || params.Secret == "" || params.UserID == "" || params.TemplateID == "" {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, `{"error": "Missing required parameters"}`)
		return
	}
	if params.BaseURL == "" {
		params.BaseURL = "https://push.hzz.cool"
	}
	if params.Content == "" {
		params.Content = "测试内容"
	}
	if params.Title == "" {
		params.Title = "测试标题"
	}

	// 获取AccessToken
	token, err := getAccessToken(params.AppID, params.Secret)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, `{"error": "Failed to get access token: %v"}`, err)
		return
	}

	//log.Println(token)
	// 发送模板消息
	resp, err := sendTemplateMessage(token, params)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, `{"error": "Failed to send template message: %v"}`, err)
		return
	}

	// 返回结果
	json.NewEncoder(w).Encode(resp)
}

// Token请求参数结构体
type TokenRequestParams struct {
	GrantType    string `json:"grant_type"`
	AppID        string `json:"appid"`
	Secret       string `json:"secret"`
	ForceRefresh bool   `json:"force_refresh"`
}

func getAccessToken(appid, secret string) (string, error) {
	// 构建请求参数
	requestParams := TokenRequestParams{
		GrantType:    "client_credential",
		AppID:        appid,
		Secret:       secret,
		ForceRefresh: false,
	}

	// 转换为JSON
	jsonData, err := json.Marshal(requestParams)
	if err != nil {
		return "", err
	}

	// 忽略证书验证
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送POST请求
	resp, err := client.Post("https://api.weixin.qq.com/cgi-bin/stable_token", "application/json", strings.NewReader(string(jsonData)))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	//log.Println(string(body))

	// 解析响应
	var tokenResp AccessTokenResponse
	err = json.Unmarshal(body, &tokenResp)
	//log.Println(tokenResp)

	if err != nil {
		return "", err
	}

	return tokenResp.AccessToken, nil
}

func sendTemplateMessage(accessToken string, params RequestParams) (WechatAPIResponse, error) {
	// 构建请求URL
	apiUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken)

	// 处理时区,默认东八区
	location, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		location, _ = time.LoadLocation("Asia/Shanghai") // 确保默认使用东八区
	}

	// 如果参数中有时区,则尝试使用该时区
	if params.Timezone != "" {
		loc, err := time.LoadLocation(params.Timezone)
		if err == nil {
			location = loc
		}
	}

	// 获取当前时间
	currentTime := time.Now().In(location)
	timeStr := currentTime.Format("2006-01-02 15:04:05")

	// 构建请求数据
	requestData := TemplateMessageRequest{
		ToUser:     params.UserID,
		TemplateID: params.TemplateID,
		URL:        params.BaseURL + `/detail?title=` + url.QueryEscape(params.Title) + `&message=` + url.QueryEscape(params.Content) + `&date=` + url.QueryEscape(timeStr),
		Data: map[string]interface{}{
			"title": map[string]string{
				"value": params.Title,
			},
			"content": map[string]string{
				"value": params.Content,
			},
		},
	}

	// 转换为JSON
	jsonData, err := json.Marshal(requestData)
	if err != nil {
		return WechatAPIResponse{}, err
	}

	// 忽略证书验证
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送POST请求
	resp, err := client.Post(apiUrl, "application/json", strings.NewReader(string(jsonData)))
	if err != nil {
		return WechatAPIResponse{}, err
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return WechatAPIResponse{}, err
	}

	// 解析响应
	var apiResp WechatAPIResponse
	err = json.Unmarshal(body, &apiResp)
	if err != nil {
		return WechatAPIResponse{}, err
	}

	return apiResp, nil
}