zk 2 年 前
コミット
327defe024

+ 33 - 8
server/api/v1/system/sys_user.go

@@ -57,20 +57,45 @@ func (b *BaseApi) LoginWx(c *gin.Context) {
 	}
 	global.GVA_LOG.Info("小程序登录", zap.Any("res", res))
 	global.GVA_REDIS.Set(context.Background(), "wxssk:"+res.OpenID, res.SessionKey, 0)
-	if err, user := userService.FindUserByOpenId(res.OpenID); err != nil {
-		response.CodeWithDetailed(1, res, "未注册", c)
-		return
-	} else {
+	// 根据unionid查询
+	if err, user := userService.GetUserInfoByUnionId(res.UnionID); err == nil {
+		if user.OpenId == "" {
+			user.OpenId = res.OpenID
+			userService.SetUserInfo(user)
+		}
+		if user.Username == "" {
+			response.CodeWithDetailed(1, res, "未注册", c)
+			return
+		}
 		if user.AuthorityId == "100" {
 			response.CodeMessage(2, "请等待审核", c)
 			return
 		}
-		if user.UnionId == "" {
-			user.UnionId = res.UnionID
-			userService.SetUserInfo(*user)
+		b.tokenNext(c, user)
+	} else {
+		//unionid未找到 根据openid查询
+		if err, user := userService.FindUserByOpenId(res.OpenID); err != nil {
+			response.CodeWithDetailed(1, res, "未注册", c)
+			return
+		} else {
+			if user.UnionId == "" {
+				user.UnionId = res.UnionID
+				userService.SetUserInfo(*user)
+			}
+			if user.Username == "" {
+				response.CodeWithDetailed(1, res, "未注册", c)
+				return
+			}
+			if user.AuthorityId == "100" {
+				response.CodeMessage(2, "请等待审核", c)
+				return
+			}
+			b.tokenNext(c, *user)
 		}
-		b.tokenNext(c, *user)
 	}
+
+	return
+
 }
 
 func (b *BaseApi) RegisterWx(c *gin.Context) {

+ 40 - 2
server/api/v1/system/wechat.go

@@ -7,11 +7,42 @@ import (
 	"github.com/gin-gonic/gin"
 	"github.com/silenceper/wechat/v2/officialaccount/message"
 	"go.uber.org/zap"
+	"net/http"
+	"net/url"
 )
 
 type WechatApi struct {
 }
 
+func (b *WechatApi) Auth(c *gin.Context) {
+	code := c.Query("code")
+	state := c.Query("state")
+	global.GVA_LOG.Info("用户授权", zap.Any("code", code), zap.Any("state", state))
+	if acc, err := global.GVA_WECHAT.GetOauth().GetUserAccessToken(code); err != nil {
+		global.GVA_LOG.Error("用户授权异常", zap.Any("err", err))
+		c.String(http.StatusOK, "用户授权异常,请尝试重新点击授权链接")
+	} else {
+		if userInfo, err := global.GVA_WECHAT.GetOauth().GetUserInfo(acc.AccessToken, acc.OpenID, "zh_CN"); err != nil {
+			global.GVA_LOG.Error("用户获取用户信息异常", zap.Any("err", err))
+			c.String(http.StatusOK, "获取用户信息异常,请尝试重新点击授权链接")
+		} else {
+			global.GVA_LOG.Info("用户获取授权信息", zap.Any("res", userInfo))
+			if err, userSys := userService.GetUserInfoByUnionId(userInfo.Unionid); err != nil {
+				authorityId := "100"
+				user := &system.SysUser{NickName: userInfo.Nickname, HeaderImg: userInfo.HeadImgURL, WechatId: userInfo.OpenID, UnionId: userInfo.Unionid, Password: utils.RandomString(10), AuthorityId: authorityId, Authorities: nil}
+				userService.Register(*user)
+			} else {
+				//已有用户,更新信息
+				userSys.NickName = userInfo.Nickname
+				userSys.HeaderImg = userInfo.HeadImgURL
+				userSys.WechatId = userInfo.OpenID
+				userService.SetUserInfo(userSys)
+			}
+			c.String(http.StatusOK, "您已成功授权《经开创城进行时》!")
+		}
+	}
+}
+
 func (b *WechatApi) Req(c *gin.Context) {
 	// 传入request和responseWriter
 	server := global.GVA_WECHAT.GetServer(c.Request, c.Writer)
@@ -27,7 +58,7 @@ func (b *WechatApi) Req(c *gin.Context) {
 					if err, sysUser := userService.GetUserInfoByUnionId(user.UnionID); err != nil {
 						//不存在则新增用户
 						authorityId := "100"
-						user := &system.SysUser{Username: user.OpenID, WechatId: user.OpenID, UnionId: user.UnionID, NickName: user.UnionID, Password: utils.RandomString(10), AuthorityId: authorityId, Authorities: nil}
+						user := &system.SysUser{WechatId: user.OpenID, UnionId: user.UnionID, Password: utils.RandomString(10), AuthorityId: authorityId, Authorities: nil}
 						userService.Register(*user)
 					} else {
 						//已存在小程序用户更新user 微信id到表
@@ -40,7 +71,14 @@ func (b *WechatApi) Req(c *gin.Context) {
 			} else {
 				global.GVA_LOG.Info("用户已存在", zap.Any("err", err), zap.Any("sysUser", sysUser))
 			}
-			return nil
+			text := message.NewText("【经开创城进行时】感谢您的关注!授权请点击此链接:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx66e0fbb5a735bcc4&redirect_uri=" + url.QueryEscape(
+				global.GVA_CONFIG.Wxxcx.AuthUrl+"/wechat/auth") + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect")
+			return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
+		}
+		if msg.Content == "授权" {
+			text := message.NewText("授权请点击此链接:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx66e0fbb5a735bcc4&redirect_uri=" + url.QueryEscape(
+				global.GVA_CONFIG.Wxxcx.AuthUrl+"/wechat/auth") + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect")
+			return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
 		}
 		global.GVA_LOG.Info("用户消息", zap.Any("openId", msg.FromUserName), zap.Any("msg", msg))
 		text := message.NewText(msg.Content)

+ 1 - 0
server/config.yaml

@@ -89,6 +89,7 @@ wxxcx:
   secret: fdf155c29d4f6bfb104efdfcd9e99a52
   wxid: wx66e0fbb5a735bcc4
   wxkey: 6d9a776f8f7a485db4b1813be8c6891e
+  authUrl: https://work.zk1006.com/api
 zap:
   level: info
   format: json

+ 5 - 4
server/config/wxxcx.go

@@ -1,8 +1,9 @@
 package config
 
 type Wxxcx struct {
-	Appid  string `mapstructure:"appid" json:"appid" yaml:"appid"`
-	Secret string `mapstructure:"secret" json:"secret" yaml:"secret"`
-	Wxid   string `mapstructure:"wxid" json:"wxid" yaml:"wxid"`
-	Wxkey  string `mapstructure:"wxkey" json:"wxkey" yaml:"wxkey"`
+	Appid   string `mapstructure:"appid" json:"appid" yaml:"appid"`
+	Secret  string `mapstructure:"secret" json:"secret" yaml:"secret"`
+	Wxid    string `mapstructure:"wxid" json:"wxid" yaml:"wxid"`
+	Wxkey   string `mapstructure:"wxkey" json:"wxkey" yaml:"wxkey"`
+	AuthUrl string `mapstructure:"authUrl" json:"authUrl" yaml:"authUrl"`
 }

+ 5 - 0
server/model/system/request/sys_user.go

@@ -35,6 +35,11 @@ type LoginWx struct {
 	Code string `json:"code"` // 微信效验码
 }
 
+type AuthWx struct {
+	Code  string `json:"code"`  // 微信效验码
+	State string `json:"state"` // 微信效验码
+}
+
 // Modify password structure
 type ChangePasswordStruct struct {
 	Username    string `json:"username"`    // 用户名

+ 1 - 0
server/router/system/wechat.go

@@ -13,5 +13,6 @@ func (s *WechatRouter) InitWechatRouter(Router *gin.RouterGroup) {
 	var wechatApi = v1.ApiGroupApp.SystemApiGroup.WechatApi
 	{
 		wechatRouter.Any("serve", wechatApi.Req)
+		wechatRouter.Any("auth", wechatApi.Auth)
 	}
 }

+ 4 - 2
server/service/system/sys_user.go

@@ -23,8 +23,10 @@ type UserService struct {
 
 func (userService *UserService) Register(u system.SysUser) (err error, userInter system.SysUser) {
 	var user system.SysUser
-	if !errors.Is(global.GVA_DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
-		return errors.New("用户名已注册"), userInter
+	if u.Username != "" {
+		if !errors.Is(global.GVA_DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
+			return errors.New("用户名已注册"), userInter
+		}
 	}
 	// 否则 附加uuid 密码md5简单加密 注册
 	u.Password = utils.MD5V([]byte(u.Password))