Browse Source

新增微信登录

rdluck 4 years ago
parent
commit
73a9393cde
12 changed files with 359 additions and 57 deletions
  1. 131 0
      controllers/wechat.go
  2. 0 0
      doc/doc.txt
  3. 1 1
      lastupdate.tmp
  4. 1 1
      models/db.go
  5. 48 0
      models/session.go
  6. 5 0
      models/wechat.go
  7. 103 0
      models/wx_user.go
  8. 31 0
      models/wx_user_code.go
  9. 25 0
      models/wx_user_log.go
  10. 6 0
      routers/router.go
  11. 6 25
      utils/config.go
  12. 2 30
      utils/constants.go

+ 131 - 0
controllers/wechat.go

@@ -1,7 +1,12 @@
 package controllers
 
 import (
+	"encoding/json"
 	"hongze/hongze_cygx/models"
+	"hongze/hongze_cygx/utils"
+	"strconv"
+	"github.com/medivhzhan/weapp/v2"
+	"time"
 )
 
 type WechatController struct {
@@ -23,10 +28,136 @@ func (this *WechatCommonController) WechatLogin() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
+	var req models.WxLoginReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.Code == "" {
+		br.Msg = "参数错误"
+		br.ErrMsg = "Code 为空"
+		return
+	}
+	wxInfo, err := weapp.Login(utils.WxAppId, utils.WxAppSecret, req.Code)
+	if err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
+		return
+	}
+	if err = wxInfo.GetResponseError(); err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取用户信息失败,code:" + strconv.Itoa(wxInfo.ErrCode) + ",msg:" + wxInfo.ErrMSG
+		return
+	}
+	firstLogin := 1
+	userId := 0
+	if wxInfo.OpenID != "" {
+		wxUser, err := models.GetWxUserItemByOpenId(wxInfo.UnionID)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			br.Msg = "获取用户信息失败"
+			br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
+			return
+		}
+		if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+			user := new(models.WxUser)
+			user.OpenId = wxInfo.OpenID
+			user.CompanyId = 1
+			user.CreatedTime = time.Now()
+			user.UnionId = wxInfo.UnionID
+			user.Unionid = wxInfo.UnionID
+			user.FirstLogin = 1
+			user.Enabled = 1
+			user.RegisterPlatform = 1
+			user.RegisterTime = time.Now()
+			newId, err := models.AddWxUser(user)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增联系人失败,Eerr:" + err.Error()
+				return
+			}
+			userId = int(newId)
+		} else {
+			firstLogin = wxUser.FirstLogin
+			userId = wxUser.UserId
+		}
+	} else {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取unionId失败,unionId:" + wxInfo.UnionID
+		return
+	}
 
+	var token string
+	tokenItem, err := models.GetTokenByUid(userId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+		return
+	}
+
+	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.OpenId = wxInfo.OpenID
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 3, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+	}
+	{
+		newItem, _ := models.GetWxUserItemByUserId(userId)
+		if newItem.Mobile == "" && newItem.Email == "" {
+			firstLogin = 1
+		}
+	}
+
+	//新增登录日志
+	{
+		loginLog := new(models.WxUserLog)
+		loginLog.UserId = userId
+		loginLog.OpenId = wxInfo.OpenID
+		loginLog.UnionId = wxInfo.UnionID
+		loginLog.CreateTime = time.Now()
+		loginLog.Handle = "wechat_login_cygx"
+		loginLog.Remark = token
+		go models.AddWxUserLog(loginLog)
+	}
+
+	{
+		codeLog := new(models.WxUserCode)
+		codeLog.WxCode = req.Code
+		codeLog.UserId = userId
+		codeLog.Code = 0
+		codeLog.FirstLogin = firstLogin
+		codeLog.Authorization = token
+		codeLog.UserPermission = 1
+		codeLog.CreateTime = time.Now()
+		models.AddWxUserCode(codeLog)
+	}
+
+	resp := new(models.WxLoginResp)
+	resp.UserId = userId
+	resp.FirstLogin = firstLogin
+	resp.Authorization = token
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "登录成功"
+	br.Data = resp
 	//登录日志
 	//{
 	//	returnResult, err := json.Marshal(br)

+ 0 - 0
doc/doc.txt


+ 1 - 1
lastupdate.tmp

@@ -1 +1 @@
-{"E:\\code\\go\\src\\hongze\\hongze_cygx\\controllers":1611814712717539900}
+{"E:\\code\\go\\src\\hongze\\hongze_cygx\\controllers":1611828436481460900}

+ 1 - 1
models/db.go

@@ -20,6 +20,6 @@ func init() {
 
 	//注册对象
 	orm.RegisterModel(
-
+		new(WxUser),
 	)
 }

+ 48 - 0
models/session.go

@@ -0,0 +1,48 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type Session struct {
+	SessionId       int `orm:"column(session_id);pk"`
+	UserId          int
+	OpenId          string
+	AccessToken     string
+	ExpireTime      time.Time
+	CreatedTime     time.Time
+	LastUpdatedTime time.Time
+}
+
+func GetSessionByToken(token string) (item *Session, err error) {
+	sql := `SELECT * FROM session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	err = o.Raw(sql, token).QueryRow(&item)
+	return
+}
+
+func GetSessionCountByToken(token string) (count int, err error) {
+	sql := `SELECT COUNT(1) AS count FROM session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	err = o.Raw(sql, token).QueryRow(&count)
+	return
+}
+
+//添加用户session信息
+func AddSession(item *Session) (err error) {
+	o := orm.NewOrm()
+	o.Using("rddp")
+	_, err = o.Insert(item)
+	return
+}
+
+func GetTokenByUid(uid int) (item *Session, err error) {
+	sql := `SELECT * FROM session WHERE user_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	err = o.Raw(sql, uid).QueryRow(&item)
+	return
+}

+ 5 - 0
models/wechat.go

@@ -0,0 +1,5 @@
+package models
+
+type WxLoginReq struct {
+	Code string `description:"微信code"`
+}

+ 103 - 0
models/wx_user.go

@@ -0,0 +1,103 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type WxUser struct {
+	UserId           int       `orm:"column(user_id);pk"`
+	OpenId           string    `description:"open_id"`
+	UnionId          string    `description:"union_id"`
+	Subscribe        string    `description:"是否关注"`
+	CompanyId        int       `description:"客户id"`
+	NickName         string    `description:"用户昵称"`
+	RealName         string    `description:"用户实际名称"`
+	UserCode         string    `description:"用户编码"`
+	Mobile           string    `description:"手机号码"`
+	BindAccount      string    `description:"绑定时的账号"`
+	WxCode           string    `description:"微信号"`
+	Profession       string    `description:"职业"`
+	Email            string    `description:"邮箱"`
+	Telephone        string    `description:"座机"`
+	Sex              int       `description:"普通用户性别,1为男性,2为女性"`
+	Province         string    `description:"普通用户个人资料填写的省份"`
+	City             string    `description:"普通用户个人资料填写的城市"`
+	Country          string    `description:"国家,如中国为CN"`
+	SubscribeTime    int       `description:"关注时间"`
+	Remark           string    `description:"备注"`
+	Headimgurl       string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
+	Privilege        string    `description:"用户特权信息,json数组,如微信沃卡用户为(chinaunicom)"`
+	Unionid          string    `description:"用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。"`
+	FirstLogin       int       `description:"是否第一次登陆"`
+	Enabled          int       `description:"是否可用"`
+	CreatedTime      time.Time `description:"创建时间"`
+	LastUpdatedTime  time.Time `description:"最新一次修改时间"`
+	Seller           string    `description:"销售员"`
+	Note             string    `description:"客户备份信息"`
+	IsNote           int       `description:"是否备注过信息"`
+	FromType         string    `description:"report' COMMENT 'report:研报,teleconference:电话会"`
+	ApplyMethod      int       `description:"0:未申请,1:已付费客户申请试用,2:非客户申请试用"`
+	RegisterTime     time.Time `description:"注册时间"`
+	RegisterPlatform int       `description:"注册平台,1:微信端,2:PC网页端"`
+	IsFreeLogin      bool      `description:"是否免登陆,true:免登陆,false:非免登陆"`
+	LoginTime        time.Time `description:"最近一次登录时间"`
+}
+
+//添加用户信息
+func AddWxUser(item *WxUser) (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(item)
+	return
+}
+
+type WxUserItem struct {
+	UserId          int       `description:"用户id"`
+	OpenId          string    `description:"open_id"`
+	UnionId         string    `description:"union_id"`
+	CompanyId       int       `description:"客户id"`
+	NickName        string    `description:"用户昵称"`
+	RealName        string    `description:"用户实际名称"`
+	Mobile          string    `description:"手机号码"`
+	BindAccount     string    `description:"绑定时的账号"`
+	Email           string    `description:"邮箱"`
+	Headimgurl      string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
+	ApplyMethod     int       `description:"0:未申请,1:已付费客户申请试用,2:非客户申请试用"`
+	FirstLogin      int       `description:"是否第一次登陆"`
+	IsFreeLogin     int       `description:"是否免登陆,true:免登陆,false:非免登陆"`
+	LoginTime       time.Time `description:"登录时间"`
+	CreatedTime     time.Time `description:"创建时间"`
+	LastUpdatedTime time.Time `description:"最近一次修改时间"`
+}
+
+func GetWxUserItemByUnionid(unionid string) (item *WxUserItem, err error) {
+	sql := `SELECT * FROM wx_user WHERE union_id=? `
+	err = orm.NewOrm().Raw(sql, unionid).QueryRow(&item)
+	return
+}
+
+func GetWxUserItemByUserId(userId int) (item *WxUserItem, err error) {
+	sql := `SELECT * FROM wx_user WHERE user_id=? `
+	err = orm.NewOrm().Raw(sql, userId).QueryRow(&item)
+	return
+}
+
+func GetWxUserItemByOpenId(openId string) (item *WxUserItem, err error) {
+	sql := `SELECT * FROM wx_user WHERE open_id=? `
+	err = orm.NewOrm().Raw(sql, openId).QueryRow(&item)
+	return
+}
+
+
+type WxLoginResp struct {
+	Authorization  string
+	UserId         int
+	FirstLogin     int
+	Headimgurl     string `description:"用户头像"`
+	Mobile         string `description:"手机号"`
+	Email          string `description:"邮箱"`
+	CompanyName    string `description:"客户名称"`
+	Status         string `description:"状态"`
+	EndDate        string `description:"到期日期"`
+	ProductName    string `description:"客户类型名称"`
+}

+ 31 - 0
models/wx_user_code.go

@@ -0,0 +1,31 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type WxUserCode struct {
+	Id             int `orm:"column(id);pk"`
+	WxCode         string
+	UserId         int
+	Code           int
+	FirstLogin     int
+	Authorization  string
+	UserPermission int
+	CreateTime     time.Time
+}
+
+//添加联系人日志信息
+func AddWxUserCode(item *WxUserCode) (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(item)
+	return
+}
+
+func GetWxUserCode(wxCode string)(item *WxUserCode,err error)  {
+	o := orm.NewOrm()
+	sql:=`SELECT * FROM wx_user_code WHERE wx_code=? `
+	err=o.Raw(sql,wxCode).QueryRow(&item)
+	return
+}

+ 25 - 0
models/wx_user_log.go

@@ -0,0 +1,25 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type WxUserLog struct {
+	Id         int `orm:"column(id);pk"`
+	UserId     int
+	OpenId     string
+	UnionId    string
+	Mobile     string
+	Email      string
+	Handle     string
+	Remark     string
+	CreateTime time.Time
+}
+
+//添加联系人日志信息
+func AddWxUserLog(item *WxUserLog) (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(item)
+	return
+}

+ 6 - 0
routers/router.go

@@ -19,6 +19,12 @@ func init() {
 				&controllers.HomeController{},
 			),
 		),
+		beego.NSNamespace("/wechat",
+			beego.NSInclude(
+				&controllers.WechatController{},
+				&controllers.WechatCommonController{},
+			),
+		),
 	)
 	beego.AddNamespace(ns)
 }

+ 6 - 25
utils/config.go

@@ -20,18 +20,8 @@ var (
 	WxId                string //微信原始ID
 	WxAppId             string
 	WxAppSecret         string
-	TemplateIdByProduct string //产品运行报告通知-模板ID
-	TemplateRedirectUrl string //模板消息跳转地址
 )
 
-//pc端微信配置信息
-var (
-	PcWxId                string //微信原始ID
-	PcWxAppId             string
-	PcWxAppSecret         string
-	PcTemplateIdByProduct string //产品运行报告通知-模板ID
-	PcTemplateRedirectUrl string //模板消息跳转地址
-)
 
 func init() {
 	RunMode = beego.AppConfig.String("run_mode")
@@ -45,24 +35,15 @@ func init() {
 	MYSQL_URL_EDB = config["mysql_url_edb"]
 
 	if RunMode == "release" {
-		WxAppId = "wx4a844c734d8c8e56"
-		WxAppSecret = "26c586e7ccb3c575433f0f37797b3eeb"
-		WxId = "gh_b67e0049fb8c"
-		TemplateIdByProduct = "Cp2wF8gvBtxyWV4DeYuI172oqwyYXVRSm3AyJO42d84"
-		TemplateRedirectUrl = "https://ficc.hzinsights.com/reportdtl?id="
+		WxAppId = "wxcc32b61f96720d2f"
+		WxAppSecret = "06894933fafb24dafead7eaae09c08e0"
+		WxId = "gh_a9d3744e1072"
 
-		PcWxAppId = "wx615472d6874eeb7f"
-		PcWxAppSecret="97fe374fb0cc90ef58c4b49d431366f1"
 		STATIC_DIR = "/home/static/imgs/"
 	} else {
-		WxAppId = "wx9b5d7291e581233a"
-		WxAppSecret = "f4d52e34021eee262dce9682b31f8861"
-		WxId = "gh_5dc508325c6f"
-		TemplateIdByProduct = "-YjuPOB7Fqd-S3ilabYa6wvjDY9aXmeEfPN6DCiy-EY"
-		TemplateRedirectUrl = "http://rddpweb.brilliantstart.cn/reportdtl?id="
-
-		PcWxAppId = "wx7c8084f6e5b1d85a"
-		PcWxAppSecret="9e4210cd5a363aa1f316b7c4b8898418"
+		WxAppId = "wxcc32b61f96720d2f"
+		WxAppSecret = "06894933fafb24dafead7eaae09c08e0"
+		WxId = "gh_a9d3744e1072"
 
 		STATIC_DIR = "/home/static/imgs/"
 	}

+ 2 - 30
utils/constants.go

@@ -19,7 +19,7 @@ const (
 )
 
 const (
-	APPNAME          = "弘则-日度点评"
+	APPNAME          = "弘则-查研观项"
 	EmailSendToUsers = "glji@hzinsights.com"
 )
 
@@ -29,11 +29,6 @@ const (
 	RegularEmail  = `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`                                             //匹配电子邮箱
 )
 
-//验证码code
-const (
-	REGISTER_CODE = iota + 1 //注册
-	LOGIN_CODE               //登录
-)
 
 //聚合短信
 var (
@@ -44,19 +39,6 @@ var (
 	JhGjAppKey = "3326ad2c1047a4cd92ace153e6044ca3"
 )
 
-//科大讯飞--语音合成
-const (
-	XfSTATUS_FIRST_FRAME    = 0 //第一帧标识
-	XfSTATUS_CONTINUE_FRAME = 1 //中间帧标识
-	XfSTATUS_LAST_FRAME     = 2 //最后一帧标识
-	XfAPPID                 = "5ed70e9d"
-	XfAPIKey                = "d580509ca262e9586fb65a7064d5ce77"
-	XfAPISecret             = "a085720dc55850c720fa5576335f847a"
-	XfHostUrl               = "wss://tts-api.xfyun.cn/v2/tts"
-	XfOrigin                = "http://tts-api.xfyun.cn/"
-	XfHost                  = "tts-api.xfyun.cn"
-)
-
 //OSS
 var (
 	Endpoint   string = "oss-cn-shanghai.aliyuncs.com"
@@ -68,14 +50,4 @@ var (
 
 	AccessKeyId     string = "LTAIFMZYQhS2BTvW"
 	AccessKeySecret string = "12kk1ptCHoGWedhBnKRVW5hRJzq9Fq"
-)
-
-//客户状态
-const (
-	COMPANY_STATUS_TRY_OUT   = "试用"
-	COMPANY_STATUS_FOREVER   = "永续"
-	COMPANY_STATUS_FREEZE    = "冻结"
-	COMPANY_STATUS_LOSE      = "流失"
-	COMPANY_STATUS_FORMAL    = "正式"
-	COMPANY_STATUS_POTENTIAL = "潜在"
-)
+)