package controllers import ( "encoding/json" "sws_xcx/enums" "sws_xcx/models" "sws_xcx/service" "github.com/astaxie/beego" "github.com/medivhzhan/weapp/v3/auth" ) type LoginApiController struct { BaseApiController } // @Title WxXcxLogin // @Description 微信小程序登录 // @Param body body models.WxXcxLoginReq true "小程序登录code" // @Success 200 {object} models.WxXcxLoginResp // @Failure 500 error // @router /login [post] func (c *LoginApiController) WxXcxLogin() { dataBody := models.WxXcxLoginReq{} if err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody); err != nil || dataBody.Code == "" { c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong) return } wxcli := service.GetWxSdk().NewAuth() resp, err := wxcli.Code2Session(&auth.Code2SessionRequest{JsCode: dataBody.Code, GrantType: "authorization_code", Appid: beego.AppConfig.String("appid"), Secret: beego.AppConfig.String("appsecret")}) if err != nil { c.ServeDynamicFailJsonSend(err.Error()) return } if resp.ErrCode != 0 { c.ServeDynamicFailJsonSend(resp.ErrMSG) return } s := service.NewXcxUserService() u, err := s.GetOrCreate(resp.Openid, resp.Unionid) if err != nil { c.ServeDynamicFailJsonSend(err.Error()) return } u.SessionKey = resp.SessionKey t, err := c.BaseApiController.login(*u) if err != nil { c.ServeDynamicFailJsonSend(err.Error()) return } c.ServeSuccessJSON(models.WxXcxLoginResp{OpenId: u.OpenId, PatientId: u.PatientId, UserOrgId: u.UserOrgId, Token: t}) } // @Title LoginByOpenId // @Description 微信小程序登录 // @Param body body models.WxXcxLoginReq true "小程序登录openid" // @Success 200 {object} models.WxXcxLoginResp // @Failure 500 error // @router /loginbyopenid [post] func (c *LoginApiController) LoginByOpenId() { dataBody := models.WxXcxLoginReq{} if err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody); err != nil || dataBody.Code == "" { c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong) return } s := service.NewXcxUserService() u, err := s.GetByOpenId(dataBody.Code) if err != nil { c.ServeDynamicFailJsonSend(err.Error()) return } t, err := c.BaseApiController.login(*u) if err != nil { c.ServeDynamicFailJsonSend(err.Error()) return } c.ServeSuccessJSON(models.WxXcxLoginResp{OpenId: u.OpenId, PatientId: u.PatientId, UserOrgId: u.UserOrgId, Token: t}) }