xingzai 2 vuotta sitten
vanhempi
commit
e175857901

+ 4 - 3
controllers/article.go

@@ -101,7 +101,8 @@ func (this *ArticleController) Detail() {
 			} else {
 				articlePermissionPermissionName = detail.CategoryName
 			}
-
+			fmt.Println(articlePermissionPermissionName)
+			fmt.Println(companyPermission)
 			var hasPersion bool
 			slice := strings.Split(articlePermissionPermissionName, ",")
 			for _, v := range slice {
@@ -194,9 +195,9 @@ func (this *ArticleController) Detail() {
 		}
 	} else { //潜在客户
 		if applyCount > 0 {
-			hasPermission = 5
-		} else {
 			hasPermission = 6
+		} else {
+			hasPermission = 5
 		}
 	}
 Loop:

+ 17 - 11
controllers/base_auth.go

@@ -64,19 +64,25 @@ func (this *BaseAuthController) Prepare() {
 				this.StopRun()
 				return
 			}
-			wxUser, err := models.GetWxUserItemByMobile(session.Mobile)
-			if err != nil && err.Error() != utils.ErrNoRow() {
-				this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取信息失败 " + strconv.Itoa(session.UserId)}, false, false)
-				this.StopRun()
-				return
-			}
+			//如果用户的手机号为空,则不展示
+			if session.Mobile == "" {
+				nilWxUser := new(models.WxUserItem)
+				this.User = nilWxUser
+			} else {
+				wxUser, err := models.GetWxUserItemByMobile(session.Mobile)
+				if err != nil && err.Error() != utils.ErrNoRow() {
+					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取信息失败 " + strconv.Itoa(session.UserId)}, false, false)
+					this.StopRun()
+					return
+				}
 
-			if wxUser == nil {
-				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
-				this.StopRun()
-				return
+				if wxUser == nil {
+					this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
+					this.StopRun()
+					return
+				}
+				this.User = wxUser
 			}
-			this.User = wxUser
 		} else {
 			this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
 			this.StopRun()

+ 2 - 1
controllers/user.go

@@ -67,7 +67,8 @@ func (this *UserCommonController) Login() {
 		br.Msg = "验证码错误,请重新输入"
 		return
 	}
-	user, err := models.GetWxUserItemByMobile(mobile)
+	user, err := services.BindWxUser(mobile, "86")
+	//user, err := models.GetWxUserItemByMobile(mobile)
 	if err != nil {
 		br.Msg = "登录失败"
 		br.ErrMsg = "获取用户信息失败,GetUserDetailByMobile Err:" + err.Error()

+ 170 - 0
controllers/wechat.go

@@ -1,5 +1,15 @@
 package controllers
 
+import (
+	"encoding/json"
+	"fmt"
+	"hongze/hongze_clpt/models"
+	"hongze/hongze_clpt/services"
+	"hongze/hongze_clpt/utils"
+	"strconv"
+	"time"
+)
+
 type WechatController struct {
 	BaseAuthController
 }
@@ -7,3 +17,163 @@ type WechatController struct {
 type WechatCommonController struct {
 	BaseCommonController
 }
+
+// @Title 微信登录小助手接口
+// @Description 微信登录小助手接口
+// @Param   Code   query   string  true       "微信唯一编码code"
+// @Success 200 {object}  models.UserDetailByUserLogin
+// @router /login [get]
+func (this *WechatCommonController) WechatLoginByxzs() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	code := this.GetString("Code")
+	if code == "" {
+		br.Msg = "参数错误"
+		br.ErrMsg = "Code 为空"
+		return
+	}
+	var token string
+	item, err := services.WxGetUserOpenIdByCodeXzs(code)
+	if err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
+		return
+	}
+	if item.Errcode != 0 {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
+		return
+	}
+	openId := item.Openid
+	if openId == "" {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取openid失败,openid:" + item.Openid
+		return
+	}
+	//openId := "oN0jD1QwcA2uRD0BC4mH5zJMo0eg"
+	resp := new(models.UserDetailByUserLogin)
+	accessToken, err := services.GetWxAccessTokenByXzs()
+	if err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取access_token失败,err:" + err.Error()
+		return
+	}
+	if accessToken == "" {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "access_token 为空,"
+		return
+	}
+	wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
+	if err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
+		return
+	}
+	fmt.Println(wxUserInfo)
+	if wxUserInfo.Errcode != 0 {
+		userInfoJson, _ := json.Marshal(wxUserInfo)
+		br.Msg = "登录失败"
+		br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
+		return
+	}
+	unionId := wxUserInfo.Unionid
+	if unionId == "" {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取unionid失败,unionid:" + wxUserInfo.Unionid
+		return
+	}
+	total, err := models.GetCygxUserRecordCount(openId)
+	if err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "查询数量失败,Err:" + err.Error()
+		return
+	}
+	items := new(models.CygxUserRecord)
+	items.OpenId = openId
+	items.UnionId = unionId
+	items.NickName = wxUserInfo.Nickname
+	items.Sex = wxUserInfo.Sex
+	items.Province = wxUserInfo.Province
+	items.City = wxUserInfo.City
+	items.Country = wxUserInfo.Country
+	items.Headimgurl = wxUserInfo.Headimgurl
+	items.CreateTime = time.Now()
+	if total == 0 {
+		_, err = models.AddCygxUserRecord(items)
+		if err != nil {
+			br.Msg = "获取用户信息失败"
+			br.ErrMsg = "添加openid失败,Err:" + err.Error()
+			return
+		}
+	}
+	timeUnix := time.Now().Unix()
+	timeUnixStr := strconv.FormatInt(timeUnix, 10)
+
+	user, err := models.GetWxUserItemByUserUnionId(unionId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取本地用户信息失败,Err:" + err.Error()
+		return
+	}
+	totalItem, err := models.GetTokenByOpenId(openId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "查询数量失败,Err:" + err.Error()
+		return
+	}
+	if totalItem == nil {
+		token := utils.MD5(unionId) + utils.MD5(timeUnixStr)
+		itemsSession := new(models.CygxClptSession)
+		itemsSession.UnionId = unionId
+		itemsSession.OpenId = openId
+		itemsSession.Mobile = user.Mobile
+		itemsSession.AccessToken = token
+		itemsSession.CreatedTime = time.Now()
+		itemsSession.LastUpdatedTime = time.Now()
+		itemsSession.ExpireTime = time.Now().AddDate(0, 3, 0)
+		if user != nil {
+			itemsSession.UserId = user.UserId
+		}
+		err = models.AddCygxClptSession(itemsSession)
+		if err != nil {
+			br.Msg = "获取用户信息失败"
+			br.ErrMsg = "添加Token失败,Err:" + err.Error()
+			return
+		}
+	} else {
+		token = totalItem.AccessToken
+	}
+	if user == nil {
+		resp.HasPermission = 3
+	} else {
+		permissionStr, err := models.GetCompanyPermission(user.CompanyId)
+		if err != nil {
+			br.Msg = "获取信息失败"
+			br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
+			return
+		}
+		if permissionStr != "" {
+			resp.Permission = permissionStr
+			resp.Mobile = user.Mobile
+			resp.RealName = user.RealName
+			resp.CompanyName = user.CompanyName
+			resp.HasPermission = 1
+		} else {
+			resp.Mobile = user.Mobile
+			resp.RealName = user.RealName
+			resp.HasPermission = 2
+		}
+		resp.Headimgurl = user.HeadimgurlRecord
+	}
+	if resp.Headimgurl == "" {
+		resp.Headimgurl = utils.DefaultHeadimgurl
+	}
+	resp.Token = token
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}

+ 5 - 3
models/session.go

@@ -20,6 +20,8 @@ type CygxClptSession struct {
 	ExpireTime      time.Time
 	CreatedTime     time.Time
 	LastUpdatedTime time.Time
+	OpenId          string `description:"用户openid,最大长度:32"`
+	UnionId         string `description:"用户unionid,最大长度:64"`
 }
 
 //添加用户session信息
@@ -45,9 +47,9 @@ func GetUnionidByToken(token string) (item *CygxClptSession, err error) {
 }
 
 //根据用户openid获取token
-func GetTokenByOpenId(openId string) (item *CygxClptSession, err error) {
-	sql := `SELECT * FROM cygx_xzs_session WHERE open_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+func GetTokenByOpenId(mobile string) (item *CygxClptSession, err error) {
+	sql := `SELECT * FROM cygx_clpt_session WHERE mobile=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
 	o := orm.NewOrm()
-	err = o.Raw(sql, openId).QueryRow(&item)
+	err = o.Raw(sql, mobile).QueryRow(&item)
 	return
 }

+ 9 - 1
models/user.go

@@ -191,7 +191,7 @@ type UserDetailByUserLogin struct {
 	RealName      string `description:"用户实际名称"`
 	CompanyName   string `description:"公司名称"`
 	Permission    string `description:"拥有权限分类,多个用英文逗号分隔"`
-	HasPermission int    `description:"1:有该行业权限,正常展示,2:无权限,非潜在客户,3:未在小程序授权用户信息 等"`
+	HasPermission int    `description:"1:有该行业权限,正常展示,2:无权限,非潜在客户,3:潜在客户"`
 	Token         string `description:"Token"`
 }
 
@@ -224,3 +224,11 @@ func GetCompanyPermissionId(companyId int) (permissionId string, err error) {
 	err = o.Raw(sql, companyId).QueryRow(&permissionId)
 	return
 }
+
+//用户绑定手机号时同时绑定外呼手机号
+func BindUserOutboundMobile(mobile, countryCode string, userId int) (err error) {
+	o := orm.NewOrm()
+	sql := `UPDATE wx_user SET outbound_mobile=? ,outbound_country_code = ?, country_code= ? WHERE user_id=? `
+	_, err = o.Raw(sql, mobile, countryCode, countryCode, userId).Exec()
+	return
+}

+ 23 - 0
models/user_record.go

@@ -78,3 +78,26 @@ func GetWxOpenIdByMobileList(mobile string) (items []*OpenIdList, err error) {
 	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
 	return
 }
+
+//获取该用户第一个的 三方信息(微信头像信息)
+func GetUserThirdRecordByUserId(userId int) (item *UserRecord, err error) {
+	sql := `SELECT * FROM user_record WHERE user_id = ? order by user_record_id asc`
+	err = orm.NewOrm().Raw(sql, userId).QueryRow(&item)
+	return
+}
+
+//根据openid绑定用户关系
+func BindUserRecordByOpenid(userId int, openId, bindAccount string) (err error) {
+	o := orm.NewOrm()
+	msql := " UPDATE user_record SET user_id = ?,bind_account=? WHERE open_id = ? "
+	_, err = o.Raw(msql, userId, bindAccount, openId).Exec()
+	return
+}
+
+//修改用户微信信息
+func ModifyUserRecordByDetail(openId, unionId, nickName, headimgUrl, city, province, country string, sex, userId int) (err error) {
+	o := orm.NewOrm()
+	sql := `UPDATE user_record SET union_id=?, nick_name=?,headimgurl=?,sex=?,city=?,province=?,country=? WHERE user_id=? and open_id=? `
+	_, err = o.Raw(sql, unionId, nickName, headimgUrl, sex, city, province, country, userId, openId).Exec()
+	return
+}

+ 23 - 0
models/wx_user.go

@@ -168,3 +168,26 @@ func GetWxUserItemByUserMobile(mobile string) (item *WxUserItem, err error) {
 	err = orm.NewOrm().Raw(sql, mobile).QueryRow(&item)
 	return
 }
+
+//GetUserCountByMobile 获取数量
+func GetUserCountByMobile(mobile string) (count int, err error) {
+	o := orm.NewOrm()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM wx_user WHERE mobile = ? `
+	err = o.Raw(sqlCount, mobile).QueryRow(&count)
+	return
+}
+
+//添加用户信息
+func AddWxUser(item *WxUser) (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(item)
+	return
+}
+
+//变更联系人是否已注册状态
+func ModifyWxUserRegisterStatus(userId int) (err error) {
+	o := orm.NewOrm()
+	sql := `UPDATE wx_user SET is_register=?,source=3,register_time=NOW() WHERE user_id = ? `
+	_, err = o.Raw(sql, 1, userId).Exec()
+	return
+}

+ 9 - 0
routers/commentsRouter.go

@@ -133,4 +133,13 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hongze_clpt/controllers:WechatCommonController"] = append(beego.GlobalControllerRouter["hongze/hongze_clpt/controllers:WechatCommonController"],
+        beego.ControllerComments{
+            Method: "WechatLoginByxzs",
+            Router: `/login`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
 }

+ 90 - 0
services/user.go

@@ -5,6 +5,7 @@ import (
 	"hongze/hongze_clpt/models"
 	"hongze/hongze_clpt/utils"
 	"strings"
+	"time"
 )
 
 var ERR_NO_USER_RECORD = errors.New("用户关系没有入库")
@@ -105,3 +106,92 @@ func GetUserType(companyId int) (userType int, permissionStrnew string, err erro
 	permissionStrnew = permissionStr
 	return
 }
+
+//用户绑定
+func BindWxUser(mobile, countryCode string) (wxUser *models.WxUserItem, err error) {
+	if mobile == "" {
+		err = errors.New("手机号或邮箱必填一个")
+		return
+	}
+	//var bindAccount string
+	//根据手机号获取用户信息
+	if mobile != "" {
+		tmpWxUser, wxUserErr := models.GetWxUserItemByMobile(mobile)
+		if wxUserErr != nil && wxUserErr.Error() != utils.ErrNoRow() {
+			err = wxUserErr
+			return
+		}
+		wxUser = tmpWxUser
+		//bindAccount = mobile
+	}
+
+	//查询openid的第三方(微信)信息
+	//userRecord, err := models.GetUserRecordByOpenId(openid)
+	//if err != nil {
+	//	return
+	//}
+
+	var userId int
+	//如果查询出来的用户是nil,那么需要新增用户
+	if wxUser == nil {
+		user := &models.WxUser{
+			CompanyId:        1,
+			CreatedTime:      time.Now(),
+			FirstLogin:       1,
+			Enabled:          1,
+			RegisterPlatform: 4,
+			RegisterTime:     time.Now(),
+			Mobile:           mobile,
+			//Email:               email,
+			IsRegister:          1,
+			Source:              3,
+			CountryCode:         countryCode,
+			OutboundMobile:      mobile,
+			OutboundCountryCode: countryCode,
+		}
+		tmpUserId, addUserErr := models.AddWxUser(user)
+		if addUserErr != nil {
+			err = addUserErr
+			return
+		}
+		user.UserId = int(tmpUserId)
+		userId = int(tmpUserId)
+		wxUser, err = models.GetWxUserItemByUserId(userId)
+	} else {
+		userId = wxUser.UserId
+		err = models.BindUserOutboundMobile(mobile, countryCode, userId)
+		if err != nil {
+			return
+		}
+		if wxUser.IsRegister == 0 {
+			models.ModifyWxUserRegisterStatus(userId)
+		}
+	}
+
+	//如果存在该手机号/邮箱,那么需要校验
+	//if userRecord.UserId > 0 && userRecord.UserId != userId {
+	//	err = errors.New("用户已绑定,不允许重复绑定")
+	//	return
+	//}
+
+	//err = models.BindUserRecordByOpenid(userId, openid, bindAccount)
+	//if err != nil {
+	//	return
+	//}
+	//userRecord.UserId = userId
+
+	//如果当前该第三方用户信息的昵称为空串的话,那么需要去查询该用户的第一个绑定信息的数据作为来源做数据修复
+	//if userRecord.NickName == "" {
+	//	oldUserRecord, err := models.GetUserThirdRecordByUserId(userId)
+	//	if err == nil && oldUserRecord != nil {
+	//		//如果该用户绑定的第一条数据的头像信息不为空串,那么就去做新数据的修复
+	//		if oldUserRecord.NickName != "" {
+	//			_ = models.ModifyUserRecordByDetail(userRecord.OpenId, userRecord.UnionId, oldUserRecord.NickName, oldUserRecord.Headimgurl, oldUserRecord.City, oldUserRecord.Province, oldUserRecord.Country, oldUserRecord.Sex, userId)
+	//		}
+	//	}
+	//}
+
+	//格式化用户数据
+	//formatWxUserAndUserRecord(wxUser, userRecord)
+	return
+}