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