beego.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/astaxie/beego"
  5. "github.com/astaxie/beego/context"
  6. "github.com/yaotian/gowechat"
  7. "github.com/yaotian/gowechat/mp/message"
  8. "github.com/yaotian/gowechat/wxcontext"
  9. )
  10. var appURL = "http://localhost:8001"
  11. func hello(ctx *context.Context) {
  12. //配置微信参数
  13. config := wxcontext.Config{
  14. AppID: "your app id",
  15. AppSecret: "your app secret",
  16. Token: "your token",
  17. EncodingAESKey: "your encoding aes key",
  18. }
  19. wc := gowechat.NewWechat(config)
  20. mp, err := wc.MpMgr()
  21. if err != nil {
  22. return
  23. }
  24. // 传入request和responseWriter
  25. msgHandler := mp.GetMsgHandler(ctx.Request, ctx.ResponseWriter)
  26. fmt.Println("msgHandler:", msgHandler)
  27. //设置接收消息的处理方法
  28. msgHandler.SetHandleMessageFunc(func(msg message.MixMessage) *message.Reply {
  29. //回复消息:演示回复用户发送的消息
  30. text := message.NewText(msg.Content)
  31. return &message.Reply{message.MsgTypeText, text}
  32. })
  33. //处理消息接收以及回复
  34. err = msgHandler.Handle()
  35. if err != nil {
  36. fmt.Println(err)
  37. return
  38. }
  39. }
  40. //wxOAuth 微信公众平台,网页授权
  41. func wxOAuth(ctx *context.Context) {
  42. //配置微信参数
  43. config := wxcontext.Config{
  44. AppID: "your app id",
  45. AppSecret: "your app secret",
  46. Token: "your token",
  47. EncodingAESKey: "your encoding aes key",
  48. }
  49. wc := gowechat.NewWechat(config)
  50. mp, err := wc.MpMgr()
  51. if err != nil {
  52. return
  53. }
  54. oauthHandler := mp.GetPageOAuthHandler(ctx.Request, ctx.ResponseWriter, appURL+"/oauth")
  55. oauthHandler.Handle()
  56. }
  57. func main() {
  58. beego.Any("/", hello)
  59. beego.Any("/oauth", wxOAuth)
  60. beego.Run(":8001")
  61. }