package controllers import ( "encoding/json" "encoding/xml" "fmt" "hongze/hongze_mfyx_gzh/models" "hongze/hongze_mfyx_gzh/services" "hongze/hongze_mfyx_gzh/utils" "strconv" "time" ) type WechatController struct { BaseAuthController } type WechatCommonController struct { BaseCommonController } // @Title 微信登录公众号接口 // @Description 微信登录公众号接口 // @Param Code query string true "微信唯一编码code" // @Success 200 {object} models.UserDetailByUserLogin // @router /loginByGzh [get] func (this *WechatCommonController) WechatLoginByGzh() { 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.WxGetUserOpenIdByCodeGzh(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 + "appid:" + utils.WxPublicAppId + "secret:" + utils.WxPublicAppSecret return } openId := item.Openid if openId == "" { br.Msg = "获取用户信息失败" br.ErrMsg = "获取openid失败,openid:" + item.Openid return } resp := new(models.UserDetailByUserLogin) accessToken, err := services.GetWxAccessTokenByGzh() 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 } 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 } mfyxUserRecord, err := models.GetCygxUserRecordByOpenid(openId) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取用户信息失败" br.ErrMsg = "查询数量失败,Err:" + err.Error() return } user, err := models.GetWxUserItemByUserUnionId(unionId) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取用户信息失败" br.ErrMsg = "获取本地用户信息失败,Err:" + err.Error() return } items := new(models.CygxMfyxGzhUserRecord) 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() items.Subscribe = 1 items.SubscribeTime = time.Now() if user != nil { items.CygxUserId = user.UserId items.CygxBindAccount = user.Mobile if mfyxUserRecord != nil && mfyxUserRecord.CygxUserId != user.UserId { err = models.UpdateCygxUserRecordMobile(user.UserId, user.Mobile, unionId) if err != nil { br.Msg = "修复用户信息失败" br.ErrMsg = "修复用户信息失败,Err:" + err.Error() return } } } userRecord := &models.UserRecord{ OpenId: openId, //用户open_id UnionId: unionId, //用户union_id Subscribe: 0, NickName: wxUserInfo.Nickname, //用户昵称,最大长度:32 RealName: "", //用户实际名称,最大长度:32 Sex: wxUserInfo.Sex, //普通用户性别,1为男性,2为女性 Province: wxUserInfo.Province, //普通用户个人资料填写的省份,最大长度:30 City: wxUserInfo.City, //普通用户个人资料填写的城市,最大长度:30 Country: wxUserInfo.Country, //国家,如中国为CN,最大长度:30 Headimgurl: wxUserInfo.Headimgurl, //用户第三方(微信)头像,最大长度:512 CreateTime: time.Now(), //创建时间,关系添加时间、用户授权时间 CreatePlatform: 12, //注册平台,1:日度点评公众号,2:管理后台,3:pc端网站,4:查研观向小程序;默认:1 SessionKey: wxUserInfo.SessionKey, //微信小程序会话密钥,最大长度:255 } if user != nil { userRecord.UserId = user.UserId } if mfyxUserRecord == nil { _, err = models.AddMfyxGzhUserRecord(items) if err != nil { br.Msg = "获取用户信息失败" br.ErrMsg = "添加openid失败,Err:" + err.Error() return } _, err = models.AddUserRecord(userRecord) if err != nil { return } } timeUnix := time.Now().Unix() timeUnixStr := strconv.FormatInt(timeUnix, 10) 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.CygxMfyxGzhSession) itemsSession.UnionId = unionId itemsSession.OpenId = openId 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.AddCygxXzsSession(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 } // @Title 微信获取签名接口 // @Description 微信获取签名接口 // @Param Url query string true "url地址" // @Success 200 {object} models.WechatSign // @router /getWxSign [get] func (this *WechatCommonController) GetWxSign() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() getUrl := this.GetString("Url") accessToken, err := services.GetWxAccessTokenByGzh() if err != nil { br.Msg = "获取用户信息失败" br.ErrMsg = "获取access_token失败,err:" + err.Error() return } if accessToken == "" { br.Msg = "获取用户信息失败" br.ErrMsg = "access_token 为空," return } ticket, err := services.GetWxTicket(accessToken) if err != nil { br.Msg = "获取Ticket失败,请联系客服" br.ErrMsg = "获取Ticket失败,Err" + err.Error() return } if ticket == "" { br.Msg = "获取Ticket失败,请联系客服" br.ErrMsg = "ticket为空" + ticket return } nonceStr := utils.GetRandStringNoSpecialChar(16) signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr) resp := new(models.WechatSign) resp.AppId = utils.WxPublicAppId resp.NonceStr = nonceString resp.Timestamp = timestamp resp.Url = getUrl resp.Signature = signature br.Ret = 200 br.Success = true br.Msg = "获取签名成功" br.Data = resp } // @Title 获取用户详情 // @Description 获取用户详情接口 // @Success 200 {object} models.UserDetailByUserLogin // @router /user/detail [get] func (this *WechatController) UserInfo() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() user := this.User if user == nil { br.Msg = "请登录" br.ErrMsg = "请登录,用户信息为空" br.Ret = 408 return } uid := user.UserId var hasPermission int detail := new(models.UserDetail) if uid > 0 { var err error detail, err = models.GetUserDetailByUserId(uid) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取信息失败" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if detail == nil { br.Msg = "获取信息失败" br.ErrMsg = "获取信息失败,Err:用户不存在" return } userRecord, _ := models.GetUserRecordByUserId(uid, utils.WxPlatform) if userRecord != nil { detail.NickName = userRecord.NickName if detail.Headimgurl == "" { detail.Headimgurl = userRecord.Headimgurl } } if user.CompanyId > 1 { companyItem, err := models.GetCompanyDetailById(user.CompanyId) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取信息失败" br.ErrMsg = "获取客户信息失败,Err:" + err.Error() return } if companyItem != nil && companyItem.CompanyId > 1 { detail.CompanyName = companyItem.CompanyName detail.SellerName = companyItem.SellerName detail.SellerMobile = companyItem.Mobile // 获取用户所在公司剩余的点 companyPointsNum, err := models.GetCompanyPoints(user.CompanyId) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取信息失败" br.ErrMsg = "获取用户所在公司剩余的点失败,Err:" + err.Error() return } detail.CompanyPointsNum = companyPointsNum userYanxunaDetail, err := models.GetCygxUserYanxuanPermissionDetailByUserId(user.UserId) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取信息失败" br.ErrMsg = "获取信息失败,GetCygxUserYanxuanPermissionDetailByUserId Err:" + err.Error() return } if userYanxunaDetail != nil { detail.PermissionStatus = userYanxunaDetail.Status detail.StartDate = userYanxunaDetail.StartDate detail.EndDate = userYanxunaDetail.EndDate detail.PermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN } else { //查询研选的权限状态 var condition string var pars []interface{} condition += " AND company_id = ? AND status IN ('正式','试用') AND chart_permission_id = ? ORDER BY company_report_permission_id DESC LIMIT 1 " pars = append(pars, user.CompanyId, utils.CHART_PERMISSION_ID_YANXUAN) companyReportPermissionDetail, err := models.GetCompanyReportPermissionDetailByCondition(condition, pars) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取信息失败" br.ErrMsg = "获取用户所在公司剩余的点失败,Err:" + err.Error() return } companyProduct, err := models.GetCompanyProductDetail(user.CompanyId, 2) if err != nil { br.Msg = "获取信息失败" br.ErrMsg = "获取客户信息失败,Err:" + err.Error() return } if companyReportPermissionDetail == nil || companyProduct.IsSuspend == 1 { hasPermission = 1 } else { detail.PermissionStatus = companyReportPermissionDetail.Status detail.StartDate = companyReportPermissionDetail.StartDate detail.EndDate = companyReportPermissionDetail.EndDate } } } else { hasPermission = 1 } } else { //判断是否已经申请过 applyCount, err := models.GetApplyRecordCount(uid) if err != nil && err.Error() != utils.ErrNoRow() { br.Msg = "获取信息失败" br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error() return } if applyCount > 0 { hasPermission = 3 } else { hasPermission = 2 } detail.CompanyName = detail.Note } detail.HasPermission = hasPermission } else { ur, _ := models.GetCygxUserRecordByOpenid(user.OpenId) if ur != nil { detail.NickName = ur.NickName detail.Email = ur.CygxBindAccount detail.Mobile = ur.CygxBindAccount detail.NickName = ur.NickName detail.Headimgurl = ur.Headimgurl } hasPermission = 2 detail.HasPermission = hasPermission } if detail.Headimgurl == "" { detail.Headimgurl = utils.DefaultHeadimgurl } br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = detail } // @Title 微信获取签名接口 // @Description 微信获取签名接口 // @Param Url query string true "url地址" // @Success 200 {object} models.WechatSign // @router /notify [get,post] func (this *WechatCommonController) Notify() { echostr := this.GetString("echostr") method := this.Ctx.Input.Method() //添加请求日志记录 itemApiLog := new(models.CygxThreeApiLog) itemApiLog.CreateTime = time.Now() itemApiLog.Source = 1 itemApiLog.Url = this.Ctx.Input.URI() itemApiLog.Body = "" if method == "POST" { body := this.Ctx.Input.RequestBody utils.FileLog.Info("wechat echostr:" + string(body)) itemApiLog.Body = string(body) } go models.AddCygxThreeApiLog(itemApiLog) if method == "POST" { body := this.Ctx.Input.RequestBody item := new(models.Notify) err := xml.Unmarshal(body, &item) if err != nil { utils.FileLog.Info("xml.Unmarshal:" + err.Error()) } contactMsg := "感谢关注【买方研选】机构投资者研究共享平台\n\r\n\r\n点击下方【登录】按钮,即可获取模版消息推送! " var openId, returnResult string if item.MsgType != "" { openId = item.FromUserName } xmlTpl := ` %s ` createTime := strconv.FormatInt(time.Now().Unix(), 10) xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.WxId, createTime, contactMsg) total, err := models.GetCygxUserRecordCount(openId) if err != nil { utils.FileLog.Info("GetCygxUserRecordCount:" + err.Error()) } var unionId string if total == 0 { accessToken, err := services.GetWxAccessTokenByGzh() if err != nil { utils.FileLog.Info("accessToken:" + err.Error()) } if accessToken == "" { utils.FileLog.Info("access_token 为空 openId:" + openId) } wxUserInfo, err := services.WxGetUserInfo(openId, accessToken) if err != nil { utils.FileLog.Info("accessToken:" + err.Error()) return } if wxUserInfo.Errcode != 0 { userInfoJson, _ := json.Marshal(wxUserInfo) utils.FileLog.Info("获取用户信息失败,err:" + string(userInfoJson)) } unionId = wxUserInfo.Unionid if unionId != "" { services.AddCygxUserRecord(wxUserInfo) } } else { userRecordDetail, err := models.GetCygxUserRecordByOpenid(openId) if err != nil { utils.FileLog.Info("GetCygxUserRecordByOpenid:" + err.Error()) return } unionId = userRecordDetail.UnionId } if unionId == "" { utils.FileLog.Info("获取unionid失败,openId:" + openId) return } wxUser, err := models.GetUserRecordByUnionId(unionId) if err != nil { utils.FileLog.Info("GetUserDetailBuOpenid:" + err.Error()) } if wxUser == nil { utils.FileLog.Info("用户不存在openId:" + openId) return } if item.MsgType == "event" { switch item.Event { case "subscribe": fmt.Println("关注") go models.UserSubscribe(1, wxUser.UserId) go models.CygxUserSubscribe(1, unionId) break case "unsubscribe": fmt.Println("取消关注") go models.UserSubscribe(0, wxUser.UserId) go models.CygxUserSubscribe(0, unionId) break case "CLICK": returnResult = xmlTpl break default: utils.FileLog.Info("wechat notify event:" + item.Event) } this.Ctx.WriteString(xmlTpl) } else if item.MsgType == "text" { returnResult = xmlTpl this.Ctx.WriteString(returnResult) } else { returnResult = xmlTpl } this.Ctx.WriteString(returnResult) } else { this.Ctx.WriteString(echostr) } } //type DataOpenidArr struct { // Data OpenidArr `json:"data"` //} // //type OpenidArr struct { // Openid []string `json:"openid"` //} // //func init() { // access_token := "87_vfOIH2qwWI6cYG584J-SQklN5r5_HelQeLToq-ZNbb4LOl3SnxKSIH6qMfbljvOI9tTWTv0e9t2Gq41-u_WJhYyFzm7rH7bhRYaMhqaU713Wx9qhPfpbTb506GYXMLcAFAODC" // url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token // method := "GET" // client := &http.Client{} // req, err := http.NewRequest(method, url, nil) // // if err != nil { // fmt.Println(err) // return // } // res, err := client.Do(req) // if err != nil { // fmt.Println(err) // return // } // defer res.Body.Close() // // body, err := ioutil.ReadAll(res.Body) // if err != nil { // fmt.Println(err) // return // } // item := new(DataOpenidArr) // err = json.Unmarshal(body, &item) // fmt.Println(len(item.Data.Openid)) // // //var condition string // //var pars []interface{} // // // //condition = ` AND open_id IN (` + utils.GetOrmInReplace(len(item.Data.Openid)) + `) ` // //pars = append(pars, item.Data.Openid) // // // //listUserRecord, err := models.GetUserRecordList(condition, pars) // //if err != nil { // // fmt.Println(err) // // return // //} // accessToken, err := services.GetWxAccessTokenByGzh() // for k, v := range item.Data.Openid { // //if k > 1 { // // return // //} // // fmt.Println(k, "___", v) // openId := v // // wxUserInfo, err := services.WxGetUserInfo(openId, accessToken) // if err != nil { // utils.FileLog.Info("accessToken:" + err.Error()) // return // } // SubscribeTime := time.Unix(int64(wxUserInfo.SubscribeTime), 0).Format(utils.FormatDateTime) // fmt.Println(SubscribeTime) // if wxUserInfo.Errcode != 0 { // userInfoJson, _ := json.Marshal(wxUserInfo) // fmt.Println("获取用户信息失败,err:" + string(userInfoJson)) // } // unionId := wxUserInfo.Unionid // wxUser, err := models.GetUserRecordByUnionId(unionId) // if err != nil { // utils.FileLog.Info("GetUserDetailBuOpenid:" + err.Error()) // } // if wxUser == nil { // continue // } // if wxUser.UserId == 0 { // continue // } // // items := new(models.CygxMfyxGzhUserRecord) // 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() // items.Subscribe = 1 // items.SubscribeTime = time.Unix(int64(wxUserInfo.SubscribeTime), 0) // items.CygxUserId = wxUser.UserId // items.CygxBindAccount = wxUser.BindAccount // // total, err := models.GetCygxUserRecordCount(openId) // if total == 0 { // _, err = models.AddMfyxGzhUserRecord(items) // } // // userRecord := &models.UserRecord{ // OpenId: openId, //用户open_id // UnionId: unionId, //用户union_id // Subscribe: 1, // NickName: wxUserInfo.Nickname, //用户昵称,最大长度:32 // RealName: "", //用户实际名称,最大长度:32 // Sex: wxUserInfo.Sex, //普通用户性别,1为男性,2为女性 // Province: wxUserInfo.Province, //普通用户个人资料填写的省份,最大长度:30 // City: wxUserInfo.City, //普通用户个人资料填写的城市,最大长度:30 // Country: wxUserInfo.Country, //国家,如中国为CN,最大长度:30 // Headimgurl: wxUserInfo.Headimgurl, //用户第三方(微信)头像,最大长度:512 // CreateTime: time.Now(), //创建时间,关系添加时间、用户授权时间 // CreatePlatform: 12, //注册平台,1:日度点评公众号,2:管理后台,3:pc端网站,4:查研观向小程序;默认:1 // SessionKey: wxUserInfo.SessionKey, //微信小程序会话密钥,最大长度:255 // } // userRecord.UserId = wxUser.UserId // totalUserRecord, err := models.GetUserRecordCount(openId) // if totalUserRecord == 0 { // _, err = models.AddUserRecord(userRecord) // } // // fmt.Println("关注") // models.UserSubscribeInit(1, wxUser.UserId, SubscribeTime) // //go models.CygxUserSubscribe(1, unionId) // } // // fmt.Println("end") //}