beego.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/mp/oauth"
  9. "github.com/yaotian/gowechat/wxcontext"
  10. )
  11. var appURL = "http://localhost:8001"
  12. var config = wxcontext.Config{
  13. AppID: "your app id",
  14. AppSecret: "your app secret",
  15. Token: "your token",
  16. EncodingAESKey: "your encoding aes key",
  17. }
  18. func hello(ctx *context.Context) {
  19. //配置微信参数
  20. wc := gowechat.NewWechat(config)
  21. fmt.Println("wechat:", *wc)
  22. //微信平台mp
  23. mp, err := wc.MpMgr()
  24. if err != nil {
  25. return
  26. }
  27. // 传入request和responseWriter
  28. msgHandler := mp.GetMsgHandler(ctx.Request, ctx.ResponseWriter)
  29. //设置接收消息的处理方法
  30. msgHandler.SetHandleMessageFunc(func(msg message.MixMessage) *message.Reply {
  31. //回复消息:演示回复用户发送的消息
  32. text := message.NewText(msg.Content)
  33. return &message.Reply{message.MsgTypeText, text}
  34. })
  35. //处理消息接收以及回复
  36. err = msgHandler.Handle()
  37. if err != nil {
  38. fmt.Println(err)
  39. }
  40. }
  41. //wxOAuth 微信公众平台,网页授权
  42. func wxOAuth(ctx *context.Context) {
  43. //配置微信参数
  44. wc := gowechat.NewWechat(config)
  45. //微信公众平台
  46. mp, err := wc.MpMgr()
  47. if err != nil {
  48. return
  49. }
  50. oauthHandler := mp.GetPageOAuthHandler(ctx.Request, ctx.ResponseWriter, appURL+"/oauth")
  51. oauthHandler.SetFuncCheckOpenIDExisting(func(openID string) bool {
  52. //看自己的系统中是否已经存在此openID的用户
  53. //如果已经存在, 调用自己的Login 方法,设置cookie等,return true
  54. //如果还不存在,return false, handler会自动去取用户信息
  55. return true
  56. })
  57. oauthHandler.SetFuncAfterGetUserInfo(func(user oauth.UserInfo) bool {
  58. //已获得用户信息,这里用信息做注册使用
  59. //调用自己的Login方法,设置cookie等
  60. return false
  61. })
  62. oauthHandler.Handle()
  63. }
  64. func main() {
  65. beego.Any("/", hello)
  66. beego.Any("/oauth", wxOAuth) //需要网页授权的页面url /oauth?target=url
  67. beego.Run(":8001")
  68. }