Browse Source

扫码登陆

ziwen 2 years ago
parent
commit
8e59956667
5 changed files with 247 additions and 0 deletions
  1. 175 0
      controller/pc/pc.go
  2. 31 0
      models/response/pc/wechat.go
  3. 1 0
      routers/pc.go
  4. 3 0
      services/pc/wechat.go
  5. 37 0
      services/wechat/wechat.go

+ 175 - 0
controller/pc/pc.go

@@ -1,6 +1,8 @@
 package pc
 
 import (
+	"errors"
+	"fmt"
 	"github.com/gin-gonic/gin"
 	"hongze/hongze_yb/controller/response"
 	pcModels "hongze/hongze_yb/models/response/pc"
@@ -8,13 +10,17 @@ import (
 	"hongze/hongze_yb/models/tables/rddp/classify"
 	"hongze/hongze_yb/models/tables/rddp/report"
 	"hongze/hongze_yb/models/tables/rddp/report_chapter"
+	"hongze/hongze_yb/models/tables/rddp/session"
+	"hongze/hongze_yb/models/tables/wx_user_log"
 	"hongze/hongze_yb/models/tables/yb_activity"
 	"hongze/hongze_yb/models/tables/yb_pc_suncode"
 	"hongze/hongze_yb/services"
 	"hongze/hongze_yb/services/pc"
 	userService "hongze/hongze_yb/services/user"
+	"hongze/hongze_yb/services/wechat"
 	"hongze/hongze_yb/utils"
 	"strconv"
+	"time"
 )
 
 // LatestNews 研报首页最新资讯
@@ -328,3 +334,172 @@ func GetSunCode(c *gin.Context) {
 	response.OkData("查询成功", sunCodeUrl, c)
 	return
 }
+
+// @Title pc端微信登录接口
+// @Description pc端微信登录接口
+// @Param   Code   query   string  true       "微信唯一编码code"
+// @Success 200 {object} models.WxLoginResp
+// @router /pc/login [get]
+func WechatLogin(c *gin.Context) {
+	var resp pcModels.LoginResp
+	var token string
+	var userId int
+	var isBind bool
+	code := c.DefaultQuery("Code", "")
+	if code == "" {
+		response.Fail("code参数错误", c)
+		return
+	}
+	item, err := wechat.PcWxGetUserOpenIdByCode(code)
+	if err != nil {
+		response.Fail(err.Error(), c)
+		return
+	}
+	fmt.Println("token:",item.AccessToken)
+	fmt.Println("token:",item.Errmsg)
+	fmt.Println("token:",item.Errcode)
+	if item.Errcode != 0 {
+		response.Fail(err.Error(), c)
+		return
+	}
+
+	openId := item.Openid
+	//wxUserInfo, err := wx_app.GetSession(code)
+	//if err != nil {
+	//	response.Fail("获取失败,Err:"+err.Error(), c)
+	//	return
+	//}
+
+	//获取用户信息
+	wxPcUserInfo, err := wechat.PcWxGetUserInfo(openId, item.AccessToken)
+	if err != nil {
+		response.Fail(err.Error(), c)
+		return
+	}
+	if wxPcUserInfo.Errcode != 0 {
+		response.Fail(err.Error(), c)
+		return
+	}
+
+	unionId := item.Unionid
+	//sessionKey := wxUserInfo.SessionKey
+	//
+	//fmt.Println("wxUserInfo.OpenID:",wxUserInfo.OpenID)
+	//fmt.Println("wxUserInfo.UnionID:",wxUserInfo.UnionID)
+	fmt.Println("item.Openid:",item.Openid)
+	fmt.Println("item.Unionid:",item.Unionid)
+	//needUpdateSessionKey := true //是否更新sessionKey
+
+QUERY_WX_USER:
+	wxUser, wxUserErr := userService.GetWxUserItemByOpenId(openId)
+	if wxUserErr == userService.ERR_NO_USER_RECORD { //没有用户openid记录
+		_, recordErr := userService.AddUserRecord(openId, unionId, "", "", "", "", "", "", "", 3, 0, 0)
+		//如果插入失败,那么直接将错误信息返回
+		if recordErr != nil {
+			err = recordErr
+			return
+		}
+		//needUpdateSessionKey = false //因为是新增用户微信信息,所以不需要更新sessionKey的数据了
+
+		//插入成功后,需要重新查询该用户,并进入下面的逻辑
+		goto QUERY_WX_USER
+	} else if wxUserErr == userService.ERR_USER_NOT_BIND {
+		// 未绑定则去查询unionId是否已经绑定了用户(其他平台,不区分平台),有相应的手机号邮箱信息则自动绑定
+		platformUser, platformErr := userService.GetFirstWxUserItemByUnionId(unionId)
+		if platformErr == nil {
+			// 当公众号用户存在时
+			if platformUser.Mobile != "" || platformUser.Email != "" {
+				// 有手机号或邮箱则绑定信息则自动绑定并新增wx_user
+				countryCode := 0
+				if platformUser.CountryCode != "" {
+					countryCode, _ = strconv.Atoi(platformUser.CountryCode)
+				}
+				tempToken, tempUser, tempErr, errMsg := userService.BindWxUser(openId, platformUser.Mobile, platformUser.Email, "", 3, countryCode, 1)
+				if tempErr != nil {
+					err = errors.New("自动绑定公众号用户失败,Err:" + tempErr.Error() + ", errMsg:" + errMsg)
+					return
+				}
+				token = tempToken
+				userId = int(tempUser.UserID)
+				isBind = true
+				return
+			}
+		}
+	} else if wxUserErr != nil {
+		err = wxUserErr
+		return
+	}
+
+	//更新微信用户的sessionKey
+	//if needUpdateSessionKey {
+	//	_ = user_record.ModifySessionKeyByOpenid(openId, sessionKey)
+	//}
+
+	// 如果已经登录注册绑定的情况下/或者首次登录且为弘则研究公众号用户
+	if wxUserErr == nil {
+		userId = int(wxUser.UserID)
+
+		// 如果账户有绑定了手机号或者邮箱,那么标记为已绑定
+		if wxUser.Mobile != "" || wxUser.Email != "" {
+			isBind = true
+		}
+	}
+
+	//获取登录token
+	tokenItem, tokenErr := session.GetTokenByOpenId(openId)
+	if tokenErr != nil && tokenErr != utils.ErrNoRow {
+		err = errors.New("登录失败,获取token失败:" + tokenErr.Error())
+		return
+	}
+	fmt.Println("AccessToken:",item.AccessToken)
+	fmt.Println("tokenItem:",tokenItem.AccessToken)
+	if tokenErr != nil && tokenErr == utils.ErrNoRow {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(openId) + utils.MD5(timeUnixStr)
+		fmt.Println("token:",tokenItem.AccessToken)
+		//新增session
+		{
+			sessionItem := &session.Session{
+				OpenID:          openId,
+				UserID:          int64(userId),
+				CreatedTime:     time.Now(),
+				LastUpdatedTime: time.Now(),
+				ExpireTime:      time.Now().AddDate(0, 3, 0),
+				AccessToken:     token,
+			}
+			sessionErr := sessionItem.Create()
+			if err != nil {
+				err = errors.New("登录失败,新增用户session信息失败:" + sessionErr.Error())
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+		//如果联系人编号不为空,且联系人编号与session里面的联系人编号不一致的时候,需要做session变更
+		//if userId > 0 && tokenItem.UserID != int64(userId) {
+		//	_ = tokenItem.UpdateSession(int64(userId), time.Now().AddDate(0, 1, 0))
+		//}
+
+		//if userId > 0 {
+		//}
+		_ = tokenItem.UpdateSession(int64(userId), time.Now().AddDate(0, 1, 0))
+	}
+
+	//新增登录日志
+	{
+		loginLog := &wx_user_log.WxUserLog{
+			UserID:     userId,
+			OpenID:     openId,
+			UnionID:    unionId,
+			CreateTime: time.Now(),
+			Handle:     "yb_login",
+			Remark:     token,
+		}
+		go loginLog.Create()
+	}
+	resp.IsBind = isBind
+	resp.Token = token
+	response.OkData("查询成功", resp, c)
+	return
+}

+ 31 - 0
models/response/pc/wechat.go

@@ -0,0 +1,31 @@
+package pc
+
+type WxAccessToken struct {
+	AccessToken  string `json:"access_token"`
+	ExpiresIn    int    `json:"expires_in"`
+	RefreshToken string `json:"refresh_token"`
+	Openid       string `json:"openid"`
+	Unionid      string `json:"unionid"`
+	Scope        string `json:"scope"`
+	Errcode      int    `json:"errcode"`
+	Errmsg       string `json:"errmsg"`
+}
+
+type WxUserInfo struct {
+	Openid     string `json:"openid"`
+	Nickname   string `json:"nickname"`
+	Sex        int    `json:"sex"`
+	Language   string `json:"language"`
+	City       string `json:"city"`
+	Province   string `json:"province"`
+	Country    string `json:"country"`
+	Headimgurl string `json:"headimgurl"`
+	Unionid    string `json:"unionid"`
+	Errcode    int    `json:"errcode"`
+	Errmsg     string `json:"errmsg"`
+}
+
+type LoginResp struct {
+	Token  string `json:"authorization"`
+	IsBind bool   `json:"is_bind"`
+}

+ 1 - 0
routers/pc.go

@@ -17,4 +17,5 @@ func InitPc(r *gin.Engine)  {
 	rGroup.GET("/classify", pc.ClassifyFirstList)
 	rGroup.GET("/comment", pc.CustomerComment)
 	rGroup.POST("/getSunCode", pc.GetSunCode)
+	rGroup.GET("/login", pc.WechatLogin)
 }

+ 3 - 0
services/pc/wechat.go

@@ -0,0 +1,3 @@
+package pc
+
+

+ 37 - 0
services/wechat/wechat.go

@@ -1,7 +1,10 @@
 package wechat
 
 import (
+	"encoding/json"
+	"errors"
 	"fmt"
+	"github.com/rdlucklib/rdluck_tools/http"
 	"github.com/silenceper/wechat/v2"
 	"github.com/silenceper/wechat/v2/cache"
 	"github.com/silenceper/wechat/v2/credential"
@@ -10,6 +13,7 @@ import (
 	"github.com/silenceper/wechat/v2/officialaccount/js"
 	"github.com/silenceper/wechat/v2/officialaccount/user"
 	"hongze/hongze_yb/global"
+	"hongze/hongze_yb/models/response/pc"
 	"hongze/hongze_yb/models/tables/wx_token"
 	"time"
 )
@@ -33,6 +37,8 @@ var (
 	WxCrmAppId                            string //随手办公小程序APPID
 	WxPublicIdXzs                         string //查研观向小助手公众号
 	WxPublicSecretXzs                     string //查研观向小助手公众号
+	PcWxAppId                             string //pc版AppId
+	PcWxAppSecret                         string //pc版AppSecret
 )
 
 func initConf() {
@@ -50,6 +56,8 @@ func initConf() {
 		WxMsgTemplateIdActivityChangeApply = "CB7bOl7f3viMG4s1uhRo7WM0Jbx3WvodKuIZ8A_z8fM"
 
 		WxMsgTemplateIdAskByUser = `qfNuops-sKrfIkbA7U97A7gSrX03mUpoEpJksRUdloo`
+		PcWxAppId = "wxcba9a7ec590ee2d5"
+		PcWxAppSecret = "aa58d257e2521d768cbf1bf89989769d"
 	} else {
 		WxAppId = "wx4a844c734d8c8e56"
 		WxAppSecret = "26c586e7ccb3c575433f0f37797b3eeb"
@@ -63,6 +71,8 @@ func initConf() {
 		//销售跨部门领取客户通知
 		TemplateIdByCompanyReceive = "A5fV-XWBcu-LIj_W-tBiOJ-D39a9WDd9GOB0WGbpoBg"
 		TemplateCompanyApplyRedirectUrl = "https://ficc.hzinsights.com/approval/approval/list"
+		PcWxAppId = "wx4da95782cfc8c5eb"
+		PcWxAppSecret = "8f82ebf2ba3aa06ce44541726385df64"
 	}
 }
 
@@ -139,3 +149,30 @@ func getTokenFromServer(appid, wxSecret string) (accessToken string, expires int
 	accessToken = resAccessToken.AccessToken
 	return
 }
+
+func PcWxGetUserOpenIdByCode(code string) (item *pc.WxAccessToken, err error) {
+	if code == "" {
+		err = errors.New("code is empty")
+		return nil, err
+	}
+	initConf() //初始化参数
+	requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
+	requestUrl = fmt.Sprintf(requestUrl, PcWxAppId, PcWxAppSecret, code)
+	result, err := http.Get(requestUrl)
+	if err != nil {
+		return nil, err
+	}
+	err = json.Unmarshal(result, &item)
+	return
+}
+
+func PcWxGetUserInfo(openId, accessToken string) (item *pc.WxUserInfo, err error) {
+	requestUrl := `https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s`
+	requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
+	result, err := http.Get(requestUrl)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(result, &item)
+	return
+}