public TreatController(IOptions <MyOptions> optionsAccessor) { _optionsAccessor = optionsAccessor.Value; _weixinHelper = new WeixinHelper(_optionsAccessor.WeixinAppId, _optionsAccessor.WeixinAppSecret); _lovePlatformApi = new LovePlatformApi(_optionsAccessor.WebApiUrl); }
public ActionResult Index(string signature, string timestamp, string nonce) { //验证调用者身份 if (CheckWeixinSignature(signature, timestamp, nonce)) { try { //读取调用内容XML string requestXml; using (var reader = new StreamReader(Request.InputStream)) { requestXml = reader.ReadToEnd(); } SignalRHelper.SendMessageToChatRoom("微信", "接口调用请求@" + requestXml); //解析XML var requestDocument = XDocument.Parse(requestXml); var datas = requestDocument.Elements().ToArray(); //通用数据模型 var commonModel = new { //接收人Id ToUserName = datas.Elements("ToUserName").First().Value, //发送人Id FromUserName = datas.Elements("FromUserName").First().Value, //发送时间 CreateTime = datas.Elements("CreateTime").First().Value, //消息类型 MsgType = datas.Elements("MsgType").First().Value }; var weixin = new WeixinHelper(commonModel.FromUserName); if (commonModel.MsgType == "text" && datas.Elements("Content").First().Value == "重置") { weixin.RemoveData(); } var user = weixin.GetFromUser(); //根据传入消息类型处理消息并返回 string responseMessage; switch (commonModel.MsgType) { //纯文本消息 case "text": var textModel = new { //消息Id MsgId = datas.Elements("MsgId").First().Value, //文本消息内容 Content = datas.Elements("Content").First().Value }; var askNick = weixin.GetData<string>("AskForNickName"); if (!string.IsNullOrWhiteSpace(askNick)) { if (textModel.Content.Contains("小白")) { responseMessage = "哇,你就是传说中的小白吧?终于等到你了!我是小黑的替身哦,你对我说的话我会帮你转告给小黑的~"; weixin.SaveNickName(textModel.Content); weixin.RemoveData("AskForNickName"); } else { responseMessage = "好的,那我就叫你 " + textModel.Content + " 啦~"; weixin.SaveNickName(textModel.Content); weixin.RemoveData("AskForNickName"); } } else { if (string.IsNullOrWhiteSpace(user.NickName)) { responseMessage = "我还不知道你的名字,应该怎么称呼你?"; weixin.SaveData("AskForNickName", responseMessage); } else { if (textModel.Content.StartsWith("问:")) { var qa = textModel.Content.Split(new string[] { "问:", "答:" }, StringSplitOptions.RemoveEmptyEntries); if (qa.Length == 2) { weixin.SaveQa(qa[0], qa[1]); if (user.IsSpecial) { responseMessage = "谢谢小白!小黑一定把你告诉我的话铭记于心! "; } else { responseMessage = "谢谢你!" + user.NickName + ",我已经记住了!"; } } else { if (user.IsSpecial) { responseMessage = "不好意思小白!小黑太笨了,没有明白你说的是什么呢!/:P-( "; } else { responseMessage = "对不起,我没有明白你教给我的东西。"; } } } else { var answer = weixin.GetAnswer(textModel.Content); if (!string.IsNullOrWhiteSpace(answer)) { responseMessage = answer; } else { if (user.IsSpecial) { responseMessage = "不好意思,小白,小黑的目前还很笨,都不知道如何回应你这句话,但是你可以教我说,比如发给我:“问:小黑最好的朋友是谁 答:当然是小白啦”,这样小黑就又聪明一点了呢~"; } else { responseMessage = "对不起,我还不知道如何回应你这句话,你可以多教教我,比如:“问:一加一等于几 答:二”"; } } } } } weixin.SaveTextMessage(textModel.Content, responseMessage); //responseMessage = "您好,我收到了消息:\r\n" + textModel.Content; break; case "image": goto default; case "voice": goto default; case "video": goto default; //位置消息 case "location": var locationModel = new { //纬度 Location_X = datas.Elements("Location_X").First().Value, //经度 Location_Y = datas.Elements("Location_Y").First().Value, //缩放级别 Scale = datas.Elements("Scale").First().Value, //位置信息 Label = datas.Elements("Label").First().Value, //消息Id MsgId = datas.Elements("MsgId").First().Value }; responseMessage = string.Format("您的位置:\r\n经度:{0}\r\n纬度:{1}\r\n缩放:{2}\r\n信息:{3}" , locationModel.Location_Y, locationModel.Location_X, locationModel.Scale, locationModel.Label); break; case "link": goto default; //事件消息 case "event": //获取事件类型 var eventType = datas.Elements("Event").First().Value; //对不同的事件进行不同的处理 switch (eventType) { //关注事件 case "subscribe": if (string.IsNullOrWhiteSpace(user.NickName)) { responseMessage = "非常高兴你能关注我,我是哦呀叽,我应该怎么称呼你?"; weixin.SaveData("AskForNickName", responseMessage); } else { responseMessage = user.NickName + ",感谢你再次关注我。我的功能还不完善,请多多指教!"; } weixin.SaveTextMessage(user.UserName, responseMessage); //带参数的二维码(需微信认证) var qr = datas.Elements("EventKey").FirstOrDefault(); if (qr != null) { var qrscene = qr.Value; if (qrscene.StartsWith("qrscene")) { var ticket = datas.Elements("Ticket").First().Value; responseMessage = string.Format("您未关注并扫描了二维码:\r\nqrscene:{0}\r\nticket:{1}\r\n", qrscene, ticket); } } break; //取消关注 case "unsubscribe": responseMessage = "非常遗憾您取消了关注小网格工作室!希望能再次获得您的关注,谢谢,再见!"; break; //自动上报用户位置(需微信认证) case "LOCATION": var Latitude = datas.Elements("Latitude").First().Value; var Longitude = datas.Elements("Longitude").First().Value; var Precision = datas.Elements("Scale").First().Value; responseMessage = string.Format("您自动上报的位置:\r\n经度:{0}\r\n纬度:{1}\r\n精度:{2}", Longitude, Latitude, Precision); break; //扫描带参数的二维码(需微信认证) case "SCAN": var EventKey = datas.Elements("EventKey").First().Value; var Ticket = datas.Elements("Ticket").First().Value; responseMessage = string.Format("您已关注并扫描了二维码:\r\nscene_id:{0}\r\nticket:{1}\r\n", EventKey, Ticket); break; //未知事件类型 default: responseMessage = "您好,暂不支持[" + eventType + "]类型的事件!"; break; } break; //未知类型消息 default: responseMessage = "您好,暂不支持[" + commonModel.MsgType + "]类型的消息!"; break; } //拼接返回的XML内容(目前只返回文本消息) var responseDocument = new XDocument( new XElement("xml", new XElement("ToUserName", new XCData(commonModel.FromUserName)), new XElement("FromUserName", new XCData(commonModel.ToUserName)), new XElement("CreateTime", new XCData(StringHelper.GetUnixTimeString())), new XElement("MsgType", new XCData("text")), new XElement("Content", new XCData(responseMessage)) ) ); //将响应XML内容转换为字符串返回 var responseXml = responseDocument.ToString(SaveOptions.DisableFormatting); SignalRHelper.SendMessageToChatRoom("微信", "接口调用响应@" + responseXml); WeixinHelper.SaveRecord(requestXml, responseXml); return Content(responseXml); } catch (Exception ex) { SignalRHelper.SendMessageToChatRoom("微信", "接口调用异常@" + ex.Message + "@" + ex.StackTrace); } } SignalRHelper.SendMessageToChatRoom("微信", "接口调用失败!"); return Content("授权错误"); }
protected void Page_Load(object sender, EventArgs e) { this.Response.Redirect(WeixinHelper.ResolveClientUrl("http://mp.weixin.qq.com/bizmall/mallshelf?id=&t=mall/list&biz=MzI5NDQ2MDk4Mw==&shelf_id=1&showwxpaytitle=1#wechat_redirect"), true); }
private void getuserinfo(HttpContext context) { string OpenID = GetOpenID(context); if (string.IsNullOrEmpty(OpenID)) { WebUtil.WriteJsonError(context, ErrorCode.InvalideRequest, "获取用户OpenID失败"); return; } ErrInfo err = new ErrInfo(); string accesstoken = WeixinHelper.GetAccessToken(null); var wechatuser = WeixinHelper.GetUserInfo(OpenID, accesstoken, out err); if (wechatuser == null) { if (err.ErrCode == 40001)//invalid credential { accesstoken = WeixinHelper.GetAccessToken(accesstoken); wechatuser = WeixinHelper.GetUserInfo(OpenID, accesstoken, out err); } } if (wechatuser == null) { WebUtil.WriteJsonError(context, ErrorCode.InvalideRequest, err.ErrMsg); return; } Foresight.DataAccess.Wechat_User user = Foresight.DataAccess.Wechat_User.GetWechat_UserByUserOpenID(OpenID); if (user == null) { user = new Foresight.DataAccess.Wechat_User() { OpenId = OpenID, }; } if (!string.IsNullOrEmpty(wechatuser.NickName)) { user.NickName = wechatuser.NickName; } if (!string.IsNullOrEmpty(wechatuser.HeadImgUrl)) { user.HeadImgUrl = wechatuser.HeadImgUrl.Replace("\\", ""); } if (!string.IsNullOrEmpty(wechatuser.Sex)) { user.Sex = int.Parse(wechatuser.Sex); } if (!string.IsNullOrEmpty(wechatuser.City)) { user.City = wechatuser.City; } if (!string.IsNullOrEmpty(wechatuser.Country)) { user.Country = wechatuser.Country; } if (!string.IsNullOrEmpty(wechatuser.Province)) { user.Province = wechatuser.Province; } if (!string.IsNullOrEmpty(wechatuser.Language)) { user.Language = wechatuser.Language; } if (!string.IsNullOrEmpty(wechatuser.SubScribe)) { user.SubScribe = int.Parse(wechatuser.SubScribe); } if (!string.IsNullOrEmpty(wechatuser.SubscribeTime)) { user.SubscribeTime = ConvertDate(wechatuser.SubscribeTime); } if (user.SubScribe != 0) { user.UnSubscribeTime = DateTime.MinValue; } else { if (user.UnSubscribeTime == DateTime.MinValue) { user.UnSubscribeTime = DateTime.Now; } } if (user.FirstSubScribeTime == DateTime.MinValue) { user.FirstSubScribeTime = user.SubscribeTime; } user.Save(); WebUtil.WriteJsonResult(context, new { status = true, HeadImgUrl = user.HeadImgUrl, NickName = user.NickName }); }
public ActionResult Check() { string signature = ZNRequest.GetString("signature"); string timestamp = ZNRequest.GetString("timestamp"); string nonce = ZNRequest.GetString("nonce"); string echostr = ZNRequest.GetString("echostr"); String[] arr = new String[] { WeixinHelper.Token, timestamp, nonce }; Array.Sort(arr); StringBuilder content = new StringBuilder(); for (int i = 0; i < arr.Length; i++) { content.Append(arr[i]); } //加密并返回验证结果 var result = string.IsNullOrWhiteSpace(signature) ? false : signature.ToUpper().Equals(WeixinHelper.SHA1(content.ToString())); return(Content(result ? echostr : "")); }
protected void Page_Load(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(Request.QueryString["ID"])) { Response.Write("非法的请求"); this.Response.End(); return; } int activityID = Convert.ToInt32(Request.QueryString["ID"]); var activity = LotteryHelper.GetActivity(activityID); if (activity == null) { Response.Write("活动已关闭"); this.Response.End(); return; } string CookieKey = WebUtil.GetOpenIDPrefix(); string OpenID = this.Request.Cookies[CookieKey].Value; string activityid_key = string.IsNullOrEmpty(WebUtil.getApplicationPath()) ? "activity" : WebUtil.getApplicationPath() + "_activity"; string activityHome = string.Empty; string file = string.Empty; if (activity.UserLimit) { var joinuser = Foresight.DataAccess.Wechat_LotteryActivityUser.GetWechatLotteryActivityUserByOpenID(activity.ID, OpenID); if (joinuser == null) { activityHome = "/html/newweixin/lottery/lotteryinfocollect.html"; file = Server.MapPath("~" + activityHome); if (System.IO.File.Exists(file)) { this.Response.Cookies.Add(new HttpCookie(CookieKey, OpenID)); this.Response.Cookies.Add(new HttpCookie(activityid_key, activity.ID.ToString())); this.Response.Redirect(WeixinHelper.ResolveClientUrl(activityHome + "?t=" + DateTime.Now.Ticks), true); return; } else { Response.Write("活动页面未创建"); this.Response.End(); return; } } } if (string.IsNullOrEmpty(activityHome)) { activityHome = string.Format("/html/newweixin/lottery/{0}/index.html", activity.ID.ToString()); file = Server.MapPath("~" + activityHome); if (!System.IO.File.Exists(file)) { activityHome = string.Format("/html/newweixin/lottery/{0}/index.html", activity.Type); file = Server.MapPath("~" + activityHome); } if (!System.IO.File.Exists(file)) { activityHome = string.Format("/html/newweixin/lottery/{0}/index.html", activity.Type); if (activity.Type.Equals(Utility.EnumModel.LotteryTypeDefine.Goldenegg.ToString())) { activityHome = "/html/newweixin/lottery/lottery_zjd/index.html"; } else if (activity.Type.Equals(Utility.EnumModel.LotteryTypeDefine.Shake.ToString())) { activityHome = "/html/newweixin/lottery/lottery_yly/index.html"; } else if (activity.Type.Equals(Utility.EnumModel.LotteryTypeDefine.Shave.ToString())) { activityHome = "/html/newweixin/lottery/lottery_ggl/index.html"; } else if (activity.Type.Equals(Utility.EnumModel.LotteryTypeDefine.Turntable.ToString())) { activityHome = "/html/newweixin/lottery/lottery_zp/index.html"; } file = Server.MapPath("~" + activityHome); } } this.Response.Clear(); this.Response.Cookies.Add(new HttpCookie(CookieKey, OpenID)); this.Response.Cookies.Add(new HttpCookie(activityid_key, activity.ID.ToString())); this.Response.Redirect(WeixinHelper.ResolveClientUrl(activityHome + "?t=" + DateTime.Now.Ticks), true); } catch (Exception ex) { LogHelper.WriteError("WeiXin", this.Request.Url.ToString(), ex); Response.Write("请求已过期,请刷新后重试"); return; } }
/// <summary> /// 详情 /// </summary> public ActionResult Info() { try { var number = ZNRequest.GetString("key"); if (string.IsNullOrWhiteSpace(number)) { return(Json(new { result = false, message = "参数异常" }, JsonRequestBehavior.AllowGet)); } Article model = db.Single <Article>(x => x.Number == number); if (model == null) { return(Json(new { result = false, message = "信息异常" }, JsonRequestBehavior.AllowGet)); } //待审核 if (model.Status == Enum_Status.Audit) { var newmodel = new Article(); newmodel.ID = model.ID; newmodel.Title = model.Title; newmodel.ArticlePower = model.ArticlePower; newmodel.Status = model.Status; return(Json(new { result = true, message = newmodel }, JsonRequestBehavior.AllowGet)); } //已删除 if (model.Status == Enum_Status.Delete || model.Status == Enum_Status.DeleteCompletely) { var newmodel = new Article(); newmodel.ID = model.ID; newmodel.Title = model.Title; newmodel.ArticlePower = model.ArticlePower; newmodel.Status = model.Status; return(Json(new { result = true, message = newmodel }, JsonRequestBehavior.AllowGet)); } ////私密 //if (model.ArticlePower == Enum_ArticlePower.Myself) //{ // var newmodel = new Article(); // newmodel.ID = model.ID; // newmodel.Title = model.Title; // newmodel.ArticlePower = model.ArticlePower; // newmodel.Status = model.Status; // return Json(new { result = true, message = newmodel }, JsonRequestBehavior.AllowGet); //} ////加密 //var password = ZNRequest.GetString("ArticlePassword"); //if (model.ArticlePower == Enum_ArticlePower.Password && model.ArticlePowerPwd != password) //{ // var newmodel = new Article(); // newmodel.ID = model.ID; // newmodel.Title = model.Title; // newmodel.ArticlePower = model.ArticlePower; // newmodel.Status = model.Status; // return Json(new { result = true, message = newmodel }, JsonRequestBehavior.AllowGet); //} //当前用户编号 string xwp = ZNRequest.GetString("xwp"); var password = ZNRequest.GetString("ArticlePassword"); //微信分享设置 string url = ZNRequest.GetString("url"); url = System.Text.RegularExpressions.Regex.Replace(url, @":\d{2,5}/", "/");//去端口号 Share share = new Share(); share.AppID = WeixinHelper.AppID; share.NonceStr = WeixinHelper.NonceStr; share.TimeStr = UnixTimeHelper.FromDateTime(DateTime.Now).ToString(); share.Signature = WeixinHelper.GetSignature(url, share.TimeStr); model.Share = share; if (model.CreateUserNumber != xwp) { //私密 if (model.ArticlePower == Enum_ArticlePower.Myself) { var newmodel = new Article(); newmodel.ID = model.ID; newmodel.Title = model.Title; newmodel.ArticlePower = Enum_ArticlePower.Myself; newmodel.Share = share; return(Json(new { result = true, message = newmodel }, JsonRequestBehavior.AllowGet)); } //加密 if (model.ArticlePower == Enum_ArticlePower.Password && model.ArticlePowerPwd != password) { var newmodel = new Article(); newmodel.ID = model.ID; newmodel.Title = model.Title; newmodel.ArticlePower = Enum_ArticlePower.Password; newmodel.Share = share; return(Json(new { result = true, message = newmodel }, JsonRequestBehavior.AllowGet)); } } else { model.ArticlePower = Enum_ArticlePower.Public; } //浏览数 new SubSonic.Query.Update <Article>(provider).Set("Views").EqualTo(model.Views + 1).Where <Article>(x => x.ID == model.ID).Execute(); //创建人 User createUser = db.Single <User>(x => x.Number == model.CreateUserNumber); if (createUser != null) { model.NickName = createUser == null ? "" : createUser.NickName; model.Avatar = createUser == null ? "" : createUser.Avatar; model.AutoMusic = createUser.AutoMusic; model.ShareNick = createUser.ShareNick; } //文章部分 model.ArticlePart = new SubSonic.Query.Select(provider).From <ArticlePart>().Where <ArticlePart>(x => x.ArticleNumber == model.Number).OrderAsc("SortID").ExecuteTypedList <ArticlePart>(); model.CreateDateText = model.CreateDate.ToString("yyyy-MM-dd"); //模板配置 model.BackgroundJson = db.Single <Background>(x => x.ArticleNumber == model.Number && x.IsUsed == Enum_Used.Approved); if (model.Template >= 0) { model.TemplateJson = AppHelper.GetArticleTemplate().FirstOrDefault(x => x.ID == model.Template); } if (model.ColorTemplate > 0) { model.ColorTemplateJson = AppHelper.GetColorTemplate().FirstOrDefault(x => x.ID == model.ColorTemplate); } //漂浮装扮 var custom = db.Single <ArticleCustom>(x => x.ArticleNumber == model.Number); if (custom != null) { model.Showy = custom.ShowyUrl; model.MusicID = custom.MusicID; model.MusicName = custom.MusicName; model.MusicUrl = custom.MusicUrl; model.Transparency = custom.Transparency; model.MarginTop = custom.MarginTop; } return(Json(new { result = true, message = model }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { LogHelper.ErrorLoger.Error("HomeController_Info:" + ex.Message); } return(Json(new { result = false, message = "失败" }, JsonRequestBehavior.AllowGet)); }