配置服务器(以本地服务器127.0.0.1:8080为例)
⑴新建项目(这里用的goframe框架)
路由:
var (Main = gcmd.Command{Name: "main",Usage: "main",Brief: "start http server",Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {s := g.Server()s.Use(ghttp.MiddlewareCORS, ghttp.MiddlewareHandlerResponse)RouterGroup := s.Group("/wechat")//验证消息是否来自微信服务器RouterGroup.GET("/check", controller.Check.Checkout)s.Run()return nil},}
)
controller:
package controllerimport (v1 "WeChatServer/api/v1""WeChatServer/internal/service""context"
)var Check = checkApi{}type checkApi struct{}func (c *checkApi) Checkout(ctx context.Context, req *v1.CheckApiReq) (res *v1.ThresholdApiRes, err error) {res, err = service.Check.Checkout(ctx, req)return
}
service:
package serviceimport (v1 "WeChatServer/api/v1""context""crypto/sha1""encoding/hex""fmt""github.com/gogf/gf/v2/frame/g""sort"
)var Check = &checkService{}type checkService struct {
}func (s *checkService) Checkout(ctx context.Context, req *v1.CheckApiReq) (res *v1.ThresholdApiRes, err error) {response := g.RequestFromCtx(ctx).Responserequest := g.RequestFromCtx(ctx).Request//解析URL参数err = request.ParseForm()if err != nil {fmt.Println("URL解析失败!")return}// tokenvar token string = "e5rerF66gdKK643"// 获取参数signature := request.FormValue("signature")timestamp := request.FormValue("timestamp")nonce := request.FormValue("nonce")echostr := request.FormValue("echostr")//将token、timestamp、nonce三个参数进行字典序排序var tempArray = []string{token, timestamp, nonce}sort.Strings(tempArray)//将三个参数字符串拼接成一个字符串进行sha1加密var sha1String string = ""for _, v := range tempArray {sha1String += v}h := sha1.New()h.Write([]byte(sha1String))sha1String = hex.EncodeToString(h.Sum([]byte("")))//获得加密后的字符串可与signature对比if sha1String == signature {response.Writefln(echostr)} else {fmt.Println("验证失败")}return nil, nil}
验证消息接口为:127.0.0.1:8080/wechat/check
2.配置微信公众号测试号
下载ngrok工具
打开工具,输入:ngrok http 8080 按enter键得到以下如图地址(目的是让微信服务器能访问到127.0.0.1:8080)注意:内网穿透工具不能关闭,关闭过后映射的地址将会失效,则需重新配置
上面框出来的地址就是微信服务器可以访问的localhost:8080
则微信验证消息接口:https://74ac-110-184-211-122.jp.ngrok.io/wechat/check
打开微信公众号测试号配置页面:微信公众平台
启动项目后,将验证消息接口:https://74ac-110-184-211-122.jp.ngrok.io/wechat/check填入URL
,token这项随便填什么都可以,然后提交,显示配置成功就没问题了
js接口我也填的127.0.0.1:8080映射的地址。测试公众号好就配好了,下面就可以通过测试公众号进行开发了
下面测试微信公众号群发消息功能
微信SDK For Golang:简介 · 微信开发sdk文档
在刚刚的项目导入
go get github.com/silenceper/wechat/v2
路由:
package cmdimport ("context""github.com/gogf/gf/v2/frame/g""github.com/gogf/gf/v2/net/ghttp""github.com/gogf/gf/v2/os/gcmd""WeChatServer/internal/controller"
)var (Main = gcmd.Command{Name: "main",Usage: "main",Brief: "start http server",Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {s := g.Server()s.Use(ghttp.MiddlewareCORS, ghttp.MiddlewareHandlerResponse)RouterGroup := s.Group("/wechat")//验证消息是否来自微信服务器RouterGroup.GET("/check", controller.Check.Checkout)//发送消息RouterGroup.GET("/send", controller.Send.Send)s.Run()return nil},}
)
controller:
package controllerimport (v1 "WeChatServer/api/v1""WeChatServer/internal/service""context"
)var Send = sendApi{}type sendApi struct{}func (c *sendApi) Send(ctx context.Context, req *v1.CheckApiReq) (res *v1.ThresholdApiRes, err error) {res, err = service.Send.Send(ctx, req)return
}
service:
package serviceimport ("WeChatServer/api/v1""context""github.com/silenceper/wechat/v2""github.com/silenceper/wechat/v2/cache""fmt"offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
)var Send = &sendService{}type sendService struct {
}func (s *sendService) Send(ctx context.Context, req *v1.CheckApiReq) (res *v1.ThresholdApiRes, err error) {redisOpts := &cache.RedisOpts{Host: "114.115.149.180:6379", // redis hostPassword: "K357ghfK5hd349jFOEWG7Fgdk9ej37gS", //redis passwordDatabase: 0, // redis dbMaxActive: 10, // 连接池最大活跃连接数MaxIdle: 10, //连接池最大空闲连接数IdleTimeout: 60, //空闲连接超时时间,单位:second}redisCache := cache.NewRedis(ctx, redisOpts)cfg := &offConfig.Config{AppID: "wxc10d5372fa9f34d0",AppSecret: "f03d54bd8f0f11ad22ef9c29c165d534",Token: "e5rerF66gdKK643",EncodingAESKey: "",Cache: redisCache,}wc := wechat.NewWechat()oa := wc.GetOfficialAccount(cfg)bd := oa.GetBroadcast()_, err = bd.SendText(nil, req.Message)fmt.Println("测试走到这里了")if err != nil {return nil, err}return nil, nil}
v1:
package v1type ThresholdApiRes struct {
}type CheckApiReq struct {Message string
}
用自己的微信关注测试公众号后,启动项目访问:127.0.0.1:8080/wechat/send
微信收到公众号发来的消息
结束了