login_api_controllor.go 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "sws_xcx/enums"
  5. "sws_xcx/models"
  6. "sws_xcx/service"
  7. "github.com/astaxie/beego"
  8. "github.com/medivhzhan/weapp/v3/auth"
  9. )
  10. type LoginApiController struct {
  11. BaseApiController
  12. }
  13. // @Title WxXcxLogin
  14. // @Description 微信小程序登录
  15. // @Param body body models.WxXcxLoginReq true "小程序登录code"
  16. // @Success 200 {object} models.WxXcxLoginResp
  17. // @Failure 500 error
  18. // @router /login [post]
  19. func (c *LoginApiController) WxXcxLogin() {
  20. dataBody := models.WxXcxLoginReq{}
  21. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody); err != nil || dataBody.Code == "" {
  22. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
  23. return
  24. }
  25. wxcli := service.GetWxSdk().NewAuth()
  26. resp, err := wxcli.Code2Session(&auth.Code2SessionRequest{JsCode: dataBody.Code, GrantType: "authorization_code",
  27. Appid: beego.AppConfig.String("appid"),
  28. Secret: beego.AppConfig.String("appsecret")})
  29. if err != nil {
  30. c.ServeDynamicFailJsonSend(err.Error())
  31. return
  32. }
  33. if resp.ErrCode != 0 {
  34. c.ServeDynamicFailJsonSend(resp.ErrMSG)
  35. return
  36. }
  37. s := service.NewXcxUserService()
  38. u, err := s.GetOrCreate(resp.Openid, resp.Unionid)
  39. if err != nil {
  40. c.ServeDynamicFailJsonSend(err.Error())
  41. return
  42. }
  43. u.SessionKey = resp.SessionKey
  44. t, err := c.BaseApiController.login(*u)
  45. if err != nil {
  46. c.ServeDynamicFailJsonSend(err.Error())
  47. return
  48. }
  49. c.ServeSuccessJSON(models.WxXcxLoginResp{OpenId: u.OpenId, PatientId: u.PatientId, UserOrgId: u.UserOrgId, Token: t})
  50. }
  51. // @Title LoginByOpenId
  52. // @Description 微信小程序登录
  53. // @Param body body models.WxXcxLoginReq true "小程序登录openid"
  54. // @Success 200 {object} models.WxXcxLoginResp
  55. // @Failure 500 error
  56. // @router /loginbyopenid [post]
  57. func (c *LoginApiController) LoginByOpenId() {
  58. dataBody := models.WxXcxLoginReq{}
  59. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody); err != nil || dataBody.Code == "" {
  60. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
  61. return
  62. }
  63. s := service.NewXcxUserService()
  64. u, err := s.GetByOpenId(dataBody.Code)
  65. if err != nil {
  66. c.ServeDynamicFailJsonSend(err.Error())
  67. return
  68. }
  69. t, err := c.BaseApiController.login(*u)
  70. if err != nil {
  71. c.ServeDynamicFailJsonSend(err.Error())
  72. return
  73. }
  74. c.ServeSuccessJSON(models.WxXcxLoginResp{OpenId: u.OpenId, PatientId: u.PatientId, UserOrgId: u.UserOrgId, Token: t})
  75. }