using BizCom; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SiteCore.wechat; using SQLData; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.SessionState; using Utils; using Utils.ImageUtils; using Utils.Serialization; namespace SiteCore.Handler { public partial class app { static int perPoint = 2000; public void runuser_login() { if (UrlPostParmsCheck("code")) { string code = GetPostString("code"); //string uname = GetPostString("uname"); //string pwd = GetPostString("pwd"); string nickname = GetPostString("nickname"); string avatarUrl = GetPostString("avatarUrl"); int gender = GetPostInt("gender"); //向微信服务端 使用登录凭证 code 获取 session_key 和 openid string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + mini_Appid_run + "&secret=" + mini_Secret_run + "&js_code=" + code + "&grant_type=" + grant_type; string type = "utf-8"; string json = GetUrltoHtml(url, type);//获取微信服务器返回字符串 //微信服务器验证成功 JObject jo = (JObject)JsonConvert.DeserializeObject(json); try { string openid = jo["openid"].ToString(); string session_key = jo["session_key"].ToString(); if (openid == "" || session_key == "") { conError("无法登录1"); return; } //pwd = SecurityHelper.EncryptMD5(pwd);//加密 SRunUser entity = SRunUser.GetByWeixinMiniOpenId(openid); bool isnew = false; if (entity == null) { entity = new SRunUser(); entity.miniopenid = openid; entity.openid = openid; isnew = true; } entity.Sex = gender; entity.NickName = nickname; if (avatarUrl != "") { Thread oThread = new Thread(delegate () { HttpHelper http = new HttpHelper(); HttpItem item = new HttpItem() { KeepAlive = true, Accept = "image/webp,image/*,*/*;q=0.8", URL = avatarUrl, ResultType = ResultType.Byte }; HttpResult hResult = http.GetHtml(item); using (MemoryStream ms = new MemoryStream(hResult.ResultByte)) { Bitmap bm = new Bitmap(ms); //Graphics g = Graphics.FromImage(bm);//实例一个画板的对象,就用上面的图像的画板 //g.DrawImage(bm, 0, 0); bm.Save(webConfig.runUserPicPath + "\\b\\" + entity.ID + ".jpg", ImageFormat.Jpeg); using (System.Drawing.Image imgThumb = System.Drawing.Image.FromStream(ms)) { ImageMaker.ToThumbnailImages(imgThumb, webConfig.runUserPicPath + "\\" + entity.ID + ".jpg", 100, "", 9, 3); //result = ImageMaker.ToThumbnailImages(imgThumb, saveFile, 600, "", 9, 3); } //bm.Save(webConfig.userPicPath + "\\" + entity.ID + ".jpg", ImageFormat.Jpeg); } }); oThread.Start(); } //封装成对象 string session_id = con.Session.SessionID; if (isnew) { entity.AddTime = DateTime.Now; entity.Create(); entity.UserPic = entity.ID + ".jpg"; entity.Update(); } else { entity.UserPic = entity.ID + ".jpg"; object sid = RedisHelper.StringGet(entity.ID.ToString()); if (sid != null && sid.ToString()!="") { RedisHelper.StringDelete(sid.ToString()); } entity.Update(); } UserObj uObj = new UserObj() { session_key = session_key, openid = openid, userid = entity.ID }; //存入内存中 RedisHelper.StringSet(session_id, JsonConvert.SerializeObject(uObj)); RedisHelper.StringSet(entity.ID.ToString(), session_id); //返回数据给小程序 StringBuilder userStr = new StringBuilder(); userStr.Append("{"); userStr.AppendFormat("\"session3\":\"{0}\"", session_id); userStr.AppendFormat(",\"userpic\":\"{0}\"", entity.UserPic); //userStr.AppendFormat(",\"mobile\":\"{0}\"", entity.Mobile); userStr.AppendFormat(",\"username\":\"{0}\"", entity.NickName); userStr.Append("}"); conSuccess("登录成功", userStr.ToString()); return; } catch (Exception ex) { //微信服务器验证失败 //string msg = jo["errcode"].ToString() + "," + jo["errmsg"].ToString(); conError("暂时无法登录"); } return; } conError("错误的参数"); } public void runuser_relogin() { if (UrlPostParmsCheck("code,iv,data")) { string code = GetPostString("code"); string iv = GetPostString("iv"); string data = GetPostString("data"); //向微信服务端 使用登录凭证 code 获取 session_key 和 openid string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + mini_Appid_run + "&secret=" + mini_Secret_run + "&js_code=" + code + "&grant_type=" + grant_type; string type = "utf-8"; string json = GetUrltoHtml(url, type);//获取微信服务器返回字符串 //微信服务器验证成功 JObject jo = (JObject)JsonConvert.DeserializeObject(json); try { string openid = jo["openid"].ToString(); string session_key = jo["session_key"].ToString(); if (openid == "" || session_key == "") { conError("无效CODE!"); return; } //pwd = SecurityHelper.EncryptMD5(pwd);//加密 SRunUser entity = SRunUser.GetByWeixinMiniOpenId(openid); if (entity == null) { conLoginError("请先登录"); return; } //封装成对象 string session_id = con.Session.SessionID; object sid = RedisHelper.StringGet(entity.ID.ToString()); if (sid != null) { RedisHelper.StringDelete(sid.ToString()); } UserObj uObj = new UserObj() { session_key = session_key, openid = openid, userid = entity.ID }; //存入内存中 RedisHelper.StringSet(session_id, JsonConvert.SerializeObject(uObj)); RedisHelper.StringSet(entity.ID.ToString(), session_id); StepInfoList sil = null; try { sil = DecryptRun(data, iv, session_key); } catch(Exception ex) { XLog.SaveLog(0, "不能解密" + ex.Message); conLoginError("请重新授权"); return; } if (sil.stepInfoList.Count > 30) { int step = sil.stepInfoList[30].step; DateTime wxTime = GetTime(sil.stepInfoList[30].timestamp); DateTime dTime = DateTime.Now; string sTime = dTime.ToString("yyyy-MM-dd"); StringBuilder tsql = new StringBuilder(); StringBuilder sql = new StringBuilder(); string tsTime = ""; tsql.AppendFormat("select top 1 addtime from s_runstep where userid={0} order by addtime desc", entity.ID); object result = DbHelper.DbConn.ExecuteScalar(tsql.ToString()); if (result == null || result.ToString() == "") { tsql = new StringBuilder(); tsql.AppendFormat("select top 1 addtime from s_runuser where id={0}", entity.ID); result = DbHelper.DbConn.ExecuteScalar(tsql.ToString()); if (result == null || result.ToString() == "") return; } DateTime rTime = Convert.ToDateTime(result); for (int i = 30; i >= 0; i--) { wxTime = GetTime(sil.stepInfoList[i].timestamp); if (rTime.Subtract(wxTime).TotalDays > 0) break; tsTime = wxTime.ToString("yyyy-MM-dd"); sql.AppendFormat("if (select count(0) from s_runstep where userid={0} and addtime='{1}' and updatetime='{1}')>0 begin ", entity.ID, tsTime); sql.AppendFormat(" update s_runstep set step={2} where userid={0} and addtime='{1}' ", entity.ID, tsTime, sil.stepInfoList[i].step); sql.AppendFormat(" end else begin"); sql.AppendFormat(" insert into s_runstep(userid,addtime,step,updatetime) values({0},'{1}',{2},'{1}') ", entity.ID, tsTime, sil.stepInfoList[i].step, tsTime); sql.AppendFormat(" end "); } if (sql.Length > 0) DbHelper.DbConn.ExecuteNonQuery(sql.ToString()); string usql = "select * from s_runstep where datediff(d,updatetime,'" + sTime + "')<=1 and userid=" + entity.ID + " order by updatetime asc"; DataTable dt = DbHelper.DbConn.ExecuteDataset(usql).Tables[0]; int p = 0; List lst = new List(); foreach (DataRow dr in dt.Rows) { p = getComStep(dr["step"], dr["comstep"]); if (p > 0) lst.Add(dr["updatetime"] + "_" + getComStep(dr["step"], dr["comstep"])); } //conSuccess(step.ToString() + "|" + p);//+ "|" + dTime.ToString("HH:mm") //返回数据给小程序 StringBuilder userStr = new StringBuilder(); userStr.Append("{"); userStr.AppendFormat("\"session3\":\"{0}\"", session_id); userStr.AppendFormat(",\"step\":\"{0}\"", step); if (lst.Count > 0) userStr.AppendFormat(",\"p\":\"{0}\"", string.Join(",", lst.ToArray())); else userStr.AppendFormat(",\"p\":\"{0}\"", ""); userStr.Append("}"); conSuccess("登录成功", userStr.ToString()); return; } } catch (Exception) { //微信服务器验证失败 string msg = jo["errcode"].ToString() + "," + jo["errmsg"].ToString(); conError(msg); } return; } conError("错误的参数"); } public void get_userallstep() { UserObj uo = GetUserEntity(); if (uo == null) return; string dTime = DateTime.Now.ToString("yyyy-MM-dd"); StringBuilder sql = new StringBuilder(); //sql.AppendFormat("select step from s_userstep where userid={0} and addtime='{1}'; ", uo.userid, dTime); sql.AppendFormat("select sum(step) as sumstep from s_runstep where userid={0} and addtime<>'{1}' ;", uo.userid, dTime); object result = DbHelper.DbConn.ExecuteScalar(sql.ToString()); conSuccess(result.ToString()); } public void get_userstep_report() { UserObj uo = GetUserEntity(); if (uo == null) return; int dtype = GetPostInt("dtype"); string sql = "select step,addtime as atime from s_runstep where userid="+uo.userid+" and datediff(d,addtime,getdate())<=7 order by addtime asc"; DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0]; conGridJson(dt.Rows.Count, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); } public void ins_userrunstep() { UserObj uo = GetUserEntity(); if (uo == null) return; if(UrlPostParmsCheck("iv,data")) { string iv = GetPostString("iv"); string data = GetPostString("data"); StepInfoList sil = null; try { sil = DecryptRun(data, iv, uo.session_key); } catch { conLoginError("请重新授权"); return; } if (sil.stepInfoList.Count > 30) { int step = sil.stepInfoList[30].step; DateTime wxTime= GetTime(sil.stepInfoList[30].timestamp); DateTime dTime = DateTime.Now; string sTime = dTime.ToString("yyyy-MM-dd"); StringBuilder tsql = new StringBuilder(); StringBuilder sql = new StringBuilder(); string tsTime = ""; tsql.AppendFormat("select top 1 addtime from s_runstep where userid={0} order by addtime desc", uo.userid); object result = DbHelper.DbConn.ExecuteScalar(tsql.ToString()); if (result == null || result.ToString() == "") { tsql = new StringBuilder(); tsql.AppendFormat("select top 1 addtime from s_runuser where id={0}", uo.userid); result = DbHelper.DbConn.ExecuteScalar(tsql.ToString()); if (result == null || result.ToString() == "") return; } //for (int i = 0; i <= 30; i++) //{ // wxTime = GetTime(sil.stepInfoList[i].timestamp); // //if (dTime.Subtract(wxTime).TotalDays < 0) break; // tsTime = wxTime.ToString("yyyy-MM-dd"); // sql.AppendFormat("if (select count(0) from s_runstep where userid={0} and addtime='{1}')>0 begin ", uo.userid, tsTime); // sql.AppendFormat(" update s_runstep set step={2} where userid={0} and addtime='{1}' ", uo.userid, tsTime, sil.stepInfoList[i].step); // sql.AppendFormat(" end else begin"); // sql.AppendFormat(" insert into s_runstep(userid,addtime,step,updatetime) values({0},'{1}',{2},'{1}') ", uo.userid, tsTime, sil.stepInfoList[i].step, tsTime); // sql.AppendFormat(" end "); //} DateTime rTime = Convert.ToDateTime(result); for (int i = 30; i >= 0; i--) { wxTime = GetTime(sil.stepInfoList[i].timestamp); if (rTime.Subtract(wxTime).TotalDays > 0) break; tsTime = wxTime.ToString("yyyy-MM-dd"); sql.AppendFormat("if (select count(0) from s_runstep where userid={0} and addtime='{1}' and updatetime='{1}')>0 begin ", uo.userid, tsTime); sql.AppendFormat(" update s_runstep set step={2} where userid={0} and addtime='{1}' ", uo.userid, tsTime, sil.stepInfoList[i].step); sql.AppendFormat(" end else begin"); sql.AppendFormat(" insert into s_runstep(userid,addtime,step,updatetime) values({0},'{1}',{2},'{1}') ", uo.userid, tsTime, sil.stepInfoList[i].step, tsTime); sql.AppendFormat(" end "); } if (sql.Length > 0) DbHelper.DbConn.ExecuteNonQuery(sql.ToString()); string usql = "select * from s_runstep where datediff(d,updatetime,'" + sTime + "')<=1 and userid="+uo.userid+" order by updatetime asc"; DataTable dt = DbHelper.DbConn.ExecuteDataset(usql).Tables[0]; int p = 0; List lst = new List(); foreach (DataRow dr in dt.Rows) { p = getComStep(dr["step"], dr["comstep"]); if (p > 0) lst.Add(Convert.ToDateTime(dr["updatetime"]).ToString("yyyy-MM-dd") + "_" + getComStep(dr["step"], dr["comstep"])); } if(lst.Count<1) conSuccess(step.ToString() + "|"); else conSuccess(step.ToString() + "|" + string.Join(",", lst.ToArray()));//+ "|" + dTime.ToString("HH:mm") return; } } conError("同步失败"); } private int getComStep(object step, object comstep) { if (Convert.ToInt32(comstep) >= 20000) return 0; int s = Convert.ToInt32(step); if (s > 20000) s = 20000; int p = (s - Convert.ToInt32(comstep)) / perPoint; return p; } public void get_runuser() { UserObj uo = GetUserEntity(); if (uo == null) return; int uid = uo.userid; //RedisHelper.StringGet() DataStruct dStruct = GetPostStruct(); dStruct.PageSize = 3; List lw = new List(); //lw.Add("state=1"); string order = ""; string key = GetString("key"); if (key.Length > 0) lw.Add(string.Format("title like '%{0}%'", key)); dStruct.Order = "addtime desc"; //lw.Add(" newstypeid=1 "); dStruct.MainWhere = string.Join(" and ", lw.ToArray()); dStruct.Fileds = "id,title,sectitle,coverimage,addtime as pubtime"; DataTable dt = WebCache.GetData("s_runuser", dStruct); conGridJson(dStruct.TotalCount, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); } public void get_runinfo() { UserObj uo = GetUserEntity(); if (uo == null) return; DataStruct dStruct = GetPostStruct(); string dTime = DateTime.Now.ToString("yyyy-MM-dd"); StringBuilder sql = new StringBuilder(); //sql.AppendFormat("select step from s_userstep where userid={0} and addtime='{1}'; ", uo.userid, dTime); sql.AppendFormat("select typeid as tid,con from s_runinfo where id in (select MAX(id) from S_RunInfo group by typeID) ;"); DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0]; conGridJson(dStruct.TotalCount, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); } public void get_runinfotype() { string sql = "select id,name from s_runinfotype order by sort"; DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0]; conGridJson(dt.Rows.Count, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); } public void get_run_rank() { //string sql = "select nickname,userpic,sex,SUM(step) as allstep from view_RunStep group by nickname,userpic,sex order by allstep desc"; DataTable dt = WebCache.GetRunRank(); conGridJson(dt.Rows.Count, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); } public void get_run_currank() { UserObj uo = GetUserEntity(); if (uo == null) return; //string sql = "select nickname,userpic,sex,SUM(step) as allstep from view_RunStep group by nickname,userpic,sex order by allstep desc"; DataTable dt = WebCache.GetCurRunRank(uo.userid); conGridJson(dt.Rows.Count, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); } public void like_runstep() { UserObj uo = GetUserEntity(); if (uo == null) return; if (UrlPostParmsCheck("sid")) { int sid = GetPostInt("sid"); string key = uo.userid + "_" + sid.ToString(); if (RedisHelper.HasKey(key)) { conError("0"); return; } RedisHelper.SetKeyValue(key, 1); StringBuilder sql = new StringBuilder(); sql.AppendFormat("update S_RunStep set likes=likes+1 where id=" + sid + ";"); sql.AppendFormat("delete from s_runsteplikes where stepid={0} and userid={1} ;", sid, uo.userid); sql.AppendFormat("insert into s_runsteplikes(stepid,userid,addtime)values({0},{1},getdate()) ;", sid, uo.userid); DbHelper.DbConn.ExecuteNonQuery(sql.ToString()); WebCache.RemoveRunCache("curRunRankFlag"); conSuccess("已点赞"); return; } conError("0"); } public void get_runuserlike() { UserObj uo = GetUserEntity(); if (uo == null) return; if (UrlPostParmsCheck("sid")) { int sid = GetPostInt("sid"); string sql = "select nickname,sex,userpic,addtime from view_runsteplikes where userid=" + uo.userid + " and stepid=" + sid; DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0]; conGridJson(dt.Rows.Count, Utils.Serialization.JsonString.DataTable2LowerAjaxJson(dt)); return; } conError("0"); } public void get_runstate() { conSuccess("0"); } public void get_runpoint() { UserObj uo = GetUserEntity(); if (uo == null) return; string sql = "select userpoint from s_runuser where id=" + uo.userid; object up = DbHelper.DbConn.ExecuteScalar(sql); if (up != null) conSuccess(up.ToString()); else conSuccess("0"); } public void com_runmain() { UserObj uo = GetUserEntity(); if (uo == null) return; int uid = uo.userid; if (UrlPostParmsCheck("con")) { string con = GetPostString("con"); string[] cArr = con.Split(','); string[] tArr; int step; int com_step; StringBuilder str = new StringBuilder(); for (int i = 0; i < cArr.Length; i++) { if (cArr[i] != "") { tArr = cArr[i].Split('_'); string sql = string.Format("select * from s_runstep where userid={0} and datediff(d,updatetime,getdate())<=1 ;", uid); DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0]; str = new StringBuilder(); foreach (DataRow dr in dt.Rows) { if (Convert.ToDateTime(dr["updatetime"]).ToString("yyyy-MM-dd") == tArr[0]) { step = Convert.ToInt32(dr["step"]); com_step = Convert.ToInt32(dr["comstep"]); if (com_step >= 20000) continue; if ((step - com_step) / perPoint >= Convert.ToInt32(tArr[1])) { str.AppendFormat("update S_RunStep set ComStep=ComStep+{0} where UserID={1} and datediff(d,updatetime,'{2}')= 0 ;", Convert.ToInt32(tArr[1]) * perPoint, uid, tArr[0]); str.AppendFormat("update S_RunUser set UserPoint+={0} where ID={1} ;", tArr[1], uid); str.AppendFormat("insert into s_runuserpoint(userid, point, summary) values({0}, {1}, '步数积分{1}') ;", uid, tArr[1]); } } } if(str.Length>0) { DbHelper.DbConn.ExecuteNonQuery(str.ToString()); } } } conSuccess("1"); return; } conError("错误的参数"); } #region private /// /// 时间戳转为C#格式时间 /// /// Unix时间戳格式 /// C#格式时间 private DateTime GetTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// /// 根据微信小程序平台提供的解密算法解密数据 /// /// 加密数据 /// 初始向量 /// 从服务端获取的SessionKey /// private StepInfoList DecryptRun(string encryptedData, string iv, string sessionKey) { if (sessionKey == "" || sessionKey == null) return null; StepInfoList userInfo; //创建解密器生成工具实例 AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); //设置解密器参数 aes.Mode = CipherMode.CBC; aes.BlockSize = 128; aes.Padding = PaddingMode.PKCS7; //格式化待处理字符串 byte[] byte_encryptedData = Convert.FromBase64String(encryptedData); byte[] byte_iv = Convert.FromBase64String(iv); byte[] byte_sessionKey = Convert.FromBase64String(sessionKey); aes.IV = byte_iv; aes.Key = byte_sessionKey; //根据设置好的数据生成解密器实例 ICryptoTransform transform = aes.CreateDecryptor(); //解密 byte[] final = transform.TransformFinalBlock(byte_encryptedData, 0, byte_encryptedData.Length); //生成结果 string result = Encoding.UTF8.GetString(final); //反序列化结果,生成用户信息实例 userInfo = JsonConvert.DeserializeObject(result); return userInfo; } #endregion } }