using Aliyun.Acs.Core; using Aliyun.Acs.Core.Exceptions; using Aliyun.Acs.Core.Profile; using Aliyun.Acs.Dysmsapi.Model.V20170525; using Apache.NMS; using Apache.NMS.ActiveMQ; using dccdc.BLL; using dccdc.Common; using dccdc.Models; using dccdc.Models.WeiXin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Mvc; using System.Xml; namespace dccdc.Controllers { /// /// 疫苗相关微信 --zzq 2018年5月18日 11:32:08 /// public class YiMiaoWXController : Controller { public string cs() { var result = new ERPUserBll().Setopenid("32", "1"); return result.ToString(); } [AllowAnonymous] // GET: WeiXin [HttpGet] public string Index() { string echostr = Request.QueryString["echostr"]; return CheckSignature() ? echostr : "error"; } [AllowAnonymous] [HttpPost] public string Index(FormCollection fc) { string postString; using (Stream stream = Request.InputStream) { Byte[] postBytes = new Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); postString = Encoding.UTF8.GetString(postBytes); } log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(postString); string signature = Request.QueryString["signature"]; string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; string msg_signature = Request.QueryString["msg_signature"]; log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(signature); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(timestamp); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(nonce); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg_signature); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(postString); //if (CheckSignature()) //{ // log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("成功!"); //} WXBizMsgCrypt wxbiz = new WXBizMsgCrypt(Common.Global.YMToken, Common.Global.YMEncodingAESKey, Common.Global.YMAppId); string msg = postString; int code = wxbiz.DecryptMsg(msg_signature, timestamp, nonce, postString, ref msg); //msg = postString; //int code = 0; string retmsg = string.Empty; log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(msg); XmlNode root = doc.FirstChild; var xmlElement = root["MsgType"]; if (xmlElement != null) { string msgType = xmlElement.InnerText; log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msgType); switch (msgType.ToLower()) { case "event": retmsg = ExecEvent(doc); break; case "text": //retmsg = ExceText(doc); break; } } } catch (Exception ex) { log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(ex.Message); } if (string.IsNullOrEmpty(retmsg)) return retmsg; else { log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(retmsg); int t_code = wxbiz.EncryptMsg(retmsg, timestamp, nonce, ref msg); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg); if (t_code == 0) return msg; else { log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(t_code.ToString()); return ""; } } } private string ExecEvent(XmlDocument doc) { string msg = string.Empty; XmlNode root = doc.FirstChild; var xmlElement = root["Event"]; if (xmlElement != null) { var Event = xmlElement.InnerText; var element = root["FromUserName"]; if (element != null) { string openid = element.InnerText; openuser ou = getopenuser(openid); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("openuser:" + Newtonsoft.Json.JsonConvert.SerializeObject(ou)); try { new BLL.weixinBll().updateOpenUserYM(ou); } catch (Exception ex) { log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(ex.Message); } switch (Event) { case "subscribe": log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("关注微信"); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("openid:" + openid); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("appid:" + Global.YMAppId); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("Appsecret:" + Global.YMAppsecret); var comm = new BLL.Common(); string xiaoxi = @" 1 <![CDATA[HI " + ou.nickname + @"~" + comm.getParm_Value("wxgztitleym", "欢迎关注德城区疾病预防控制中心微信公众号", "微信关注消息标题(疫苗)") + @"]]> "; msg = CreateNews(openid, "news", xiaoxi); var EventKey = root["EventKey"]; if (EventKey != null) { string userid = EventKey.InnerText; if (userid.StartsWith("qrscene_")) { userid = userid.Replace("qrscene_", ""); new ERPUserBll().Setopenid(userid, openid); } } break; case "unsubscribe": // var opuunsubscribe = cont.OpenUser.Find(new[] { openid }); //ou = getopenuser(openid); //updateOpenUser(ou); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("取消关注"); //unsubscribe(openid); break; case "SCAN": var ek = root["EventKey"]; if (ek != null) { string userid = ek.InnerText; new ERPUserBll().Setopenid(userid, openid); } break; } } } return msg; } #region 校验开发者 private bool CheckSignature() { string signature = Request.QueryString["signature"]; string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; string[] arrTmp = { Common.Global.YMToken, timestamp, nonce }; //string[] arrTmp = { Token, timestamp, nonce }; Array.Sort(arrTmp);//字典排序 string tmpStr = string.Join("", arrTmp); var sha1 = System.Security.Cryptography.SHA1.Create(); tmpStr = BitConverter.ToString(sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(tmpStr))).Replace("-", ""); //对该字符串进行sha1加密 tmpStr = tmpStr.ToLower();//对字符串中的字母部分进行小写转换,非字母字符不作处理 //WriteLog(tmpStr);//计入日志 if (tmpStr == signature)//开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。开发者通过检验signature对请求进行校验,若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,否则接入失败 { return true; } return false; } #endregion #region 获取微信信息 /// /// 读取微信用户信息 /// /// /// private openuser getopenuser(string openid) { var accessToken = Common.Global.getAccessTokenYM; log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("accessToken:" + Newtonsoft.Json.JsonConvert.SerializeObject(accessToken)); WebClient wc = new WebClient(); var stream = wc.OpenRead("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken.access_token + "&openid=" + openid + "&lang=zh_CN"); var sr = new StreamReader(stream); string token = sr.ReadToEnd(); sr.Close(); stream.Dispose(); log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(token); var ou = Newtonsoft.Json.JsonConvert.DeserializeObject(token); if (string.IsNullOrEmpty(ou.openid)) { error err = Newtonsoft.Json.JsonConvert.DeserializeObject(token); Exception wx = new Exception(err.errmsg + "\r\n" + err.errcode); throw wx; } return ou; } #endregion /// /// 生成返回消息 /// /// /// /// /// string CreateNews(string touser, string type, string xiaoxi) { string msg = @"" + GetNowTime() + @"" + xiaoxi + @" "; return msg; } /// /// 获取时间差 /// /// int GetNowTime() { return (int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1))).TotalSeconds; } /// /// 通过时间差获取时间 /// /// /// DateTime getTime(int tick) { return TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)).AddSeconds(tick); } /// /// 关注用户页面 /// /// public ActionResult OpenUserList() { return View(); } /// /// 获取关注用户列表 /// /// /// /// /// /// public JsonResult getOpenUserList(string nc, string bz, int page, int pagesize) { var bll = new weixinBll(); var count = bll.getGZCountYM(nc, bz); var list = bll.getGZListYM(nc, bz, page, pagesize); return Json(new { Total = count, Rows = list }); } /// /// 备注关注用户 /// /// /// /// public JsonResult remark(string openid, string bz) { try { var bll = new weixinBll(); var c = bll.remarkGZYM(openid, bz); if (c > 0) { /* * { "openid":"oDF3iY9ffA-hqb2vVvbr7qxf6A0Q", "remark":"pangzi" } */ var data = new { openid = openid, remark = bz }; WebClient wc = new WebClient(); wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); log4net.LogManager.GetLogger(this.GetType()).Info(Newtonsoft.Json.JsonConvert.SerializeObject(data)); var result = wc.UploadData("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + Common.Global.getAccessTokenYM.access_token, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(data))); string jg = System.Text.Encoding.UTF8.GetString(result); var rjg = Newtonsoft.Json.JsonConvert.DeserializeObject(jg); if (rjg.errmsg == "ok") { return Json(new { State = 1, Message = "修改成功!" }); } else { return Json(new { State = 0, Message = jg }); } } else { return Json(new { State = 0, Message = "没有数据备注成功!" }); } } catch (Exception ex) { return Json(new { State = 0, Message = ex.Message }); } } #region 菜单维护 /// /// 微信菜单管理 /// /// public ActionResult Menu() { return View(); } /// /// 微信菜单类型 /// /// [HttpPost] public JsonResult getCDLX() { return Json( new[] { new { id="zu",name="菜单组" }, new { id="click",name="点击推事件" }, new { id="view",name="跳转URL" } } ); } /// /// 获取菜单列表 /// /// [HttpPost] public string getMeun() { // string sql = "select * from menu"; var dt = new BLL.weixinBll().getMenuYM(); return Newtonsoft.Json.JsonConvert.SerializeObject(dt); } /// /// 获取上级菜单 /// /// [HttpPost] public string getSJCD() { var dt = new BLL.weixinBll().getSJCDYM(); var dr = new Models.WeiXin.menu { id = 0, name = "顶级菜单" }; dt.Insert(0, dr); return Newtonsoft.Json.JsonConvert.SerializeObject(dt); } /// /// 删除菜单 /// /// 菜单ID /// [HttpPost] public JsonResult delCD(int id) { return Json(new BLL.weixinBll().delCdYM(id)); } /// /// 保存菜单 /// /// 菜单实体 /// [HttpPost] public JsonResult saveCD(Models.WeiXin.menu m) { return Json(new BLL.weixinBll().saveCDYM(m)); } #endregion #region 发送菜单 /// /// 提交微信菜单 /// /// [HttpPost] public string CreateWXMenu() { List