微信登录
()
| 148 | |
| 149 | // 微信登录 |
| 150 | func (this *CommonController) LoginByWechat() { |
| 151 | form := &WechatForm{} |
| 152 | err := this.ParseForm(form) |
| 153 | if err != nil { |
| 154 | this.Response(http.StatusBadRequest, err.Error()) |
| 155 | } |
| 156 | appId, secret := beego.AppConfig.String("appId"), beego.AppConfig.String("appSecret") |
| 157 | if form.Code == "" || form.UserInfo == "" { |
| 158 | this.Response(http.StatusBadRequest, messageBadRequest) |
| 159 | } |
| 160 | sess, err := oauth.GetWechatSessKey(appId, secret, form.Code) |
| 161 | if err != nil { |
| 162 | this.Response(http.StatusBadRequest, err.Error()) |
| 163 | } |
| 164 | if sess.ErrMsg != "" { |
| 165 | this.Response(http.StatusBadRequest, sess.ErrMsg) |
| 166 | } |
| 167 | m := models.NewWechat() |
| 168 | user, err := m.GetUserByOpenid(sess.OpenId) |
| 169 | if user.MemberId > 0 { // 之前已经绑定过注册账号,直接登录成功 |
| 170 | member, _ := models.NewMember().Find(user.MemberId) |
| 171 | this.login(*member) |
| 172 | } |
| 173 | |
| 174 | wechatUser := &oauth.WechatUser{} |
| 175 | if err = json.Unmarshal([]byte(form.UserInfo), wechatUser); err != nil { |
| 176 | this.Response(http.StatusBadRequest, err.Error()) |
| 177 | } |
| 178 | m = &models.Wechat{Openid: sess.OpenId, AvatarURL: wechatUser.AvatarURL, Nickname: wechatUser.NickName, SessKey: sess.SessionKey, Unionid: sess.UnionId} |
| 179 | if err = m.Insert(); err != nil { |
| 180 | this.Response(http.StatusBadRequest, err.Error()) |
| 181 | } |
| 182 | this.Response(http.StatusUnauthorized, "未绑定账号,请先绑定账号", map[string]string{"sess": sess.SessionKey}) |
| 183 | } |
| 184 | |
| 185 | // 【OK】 |
| 186 | func (this *CommonController) login(member models.Member) { |
nothing calls this directly
no test coverage detected