public async Task <IHttpActionResult> GetAccessTokenAsync() { //if (System.Web.HttpRuntime.Cache["JsapiTicket"] != null) //{ // var oldvm = (AccessTokenVM)System.Web.HttpRuntime.Cache["JsapiTicket"]; // if (oldvm.access_token != null && oldvm.expires_in == 7200) // { // return Json((AccessTokenVM)System.Web.HttpRuntime.Cache["JsapiTicket"]); // } //} var vm = await WeChatHepler.GetAccessTokenAsync(SettingsManager.WeiXin.AppId, SettingsManager.WeiXin.AppSecret); //if (vm.access_token != null && vm.expires_in == 7200) //{ // System.Web.HttpRuntime.Cache.Insert("JsapiTicket", vm, null, DateTime.Now.AddSeconds(7200), Cache.NoSlidingExpiration); //} return(Ok(vm)); }
public async Task <JsonResult> JsapiTicket() { if (System.Web.HttpRuntime.Cache["JsapiTicket"] != null) { var oldvm = (JsapiTicketVM)System.Web.HttpRuntime.Cache["JsapiTicket"]; if (oldvm.ticket != null && oldvm.expires_in == 7200) { return(Json((JsapiTicketVM)System.Web.HttpRuntime.Cache["JsapiTicket"])); } } var vm = await WeChatHepler.GetJsapiTicketAsync(SettingsManager.WeiXin.AppId, SettingsManager.WeiXin.AppSecret); if (vm.ticket != null && vm.expires_in == 7200) { System.Web.HttpRuntime.Cache.Insert("JsapiTicket", vm, null, DateTime.Now.AddSeconds(7200), Cache.NoSlidingExpiration); } return(Json(vm)); }
/** * snsapi_userinfo * **/ public async Task <ActionResult> OAuthSnsApiUserInfo() { string code = Request.QueryString["code"]; try { if (!string.IsNullOrEmpty(code)) { OAuthToken oauthToken = await WeChatHepler.GetAsync <OAuthToken>( $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={SettingsManager.WeiXin.AppId}&secret={SettingsManager.WeiXin.AppSecret}&code={code}&grant_type=authorization_code"); if (!string.IsNullOrEmpty(oauthToken?.openid) && !string.IsNullOrEmpty(oauthToken.access_token)) { OAuthUserInfo userInfo = await WeChatHepler.GetAsync <OAuthUserInfo>( $"https://api.weixin.qq.com/sns/userinfo?access_token={oauthToken.access_token}&openid={oauthToken.openid}&lang=zh_CN"); if (userInfo != null) { Log("获取到用户信息nickName:" + userInfo.nickname); ViewData["headImage"] = userInfo.headimgurl; ViewData["openid"] = userInfo.Openid; ViewData["nickName"] = userInfo.nickname; if (userInfo.sex == 0) { ViewData["sex"] = "未知"; } else if (userInfo.sex == 1) { ViewData["sex"] = "男"; } else { ViewData["sex"] = "女"; } ViewData["province"] = userInfo.province; ViewData["city"] = userInfo.city; } else { Log("未获取到用户信息"); } } else { Log("access_token:" + oauthToken.access_token + ",openid:" + oauthToken.openid); } } else { return(Redirect( $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={SettingsManager.WeiXin.AppId}&redirect_uri={Server.UrlEncode("http://" + Request.Url.Host + Url.Action("OAuthSnsApiUserInfo"))}&response_type=code&scope=snsapi_userinfo&state=123456#wechat_redirect")); } } catch (Exception ex) { Log(ex.Message); ViewData["errmsg"] = ex.Message; } return(View()); }
/** * snsapi_base * **/ public async Task <ActionResult> OAuthSnsApiBase() { string code = Request.QueryString["code"]; try { if (!string.IsNullOrEmpty(code)) { OAuthToken oauthToken = await WeChatHepler.GetAsync <OAuthToken>( $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={SettingsManager.WeiXin.AppId}&secret={SettingsManager.WeiXin.AppSecret}&code={code}&grant_type=authorization_code"); string accesstoken = string.Empty; AccessTokenVM tokenVm = await WeChatHepler.GetAccessTokenAsync(SettingsManager.WeiXin.AppId, SettingsManager.WeiXin.AppSecret); if (!string.IsNullOrEmpty(tokenVm?.access_token)) { accesstoken = tokenVm.access_token; } if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid)) { OAuthUserInfo userInfo = await WeChatHepler.GetAsync <OAuthUserInfo>( $"https://api.weixin.qq.com/cgi-bin/user/info?access_token={accesstoken}&openid={oauthToken.openid}&lang=zh_CN"); if (userInfo != null) { Log("获取到用户信息nickName:" + userInfo.nickname); // return View(userInfo); //BatchSendMessagesVM message = new BatchSendMessagesVM { Touser = new string[] { userInfo.Openid, "oBjaPuA6nUCz6ufJFtse-3sDYB4I" }, Msgtype = "text", Text = new Message { Content = "测试消息!" } }; var message = new SingleSendMessagesVM { ToUser = userInfo.Openid, MsgType = "text", Text = new Message { Content = "单发测试消息!" } }; string json = JsonConvert.SerializeObject(message, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }); Log("post:" + json); HttpContent content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var oo = await WeChatHepler.SingleSendMessagesAsync(accesstoken, content); Log("群发消息:" + oo.ErrMsg); ViewData["headImage"] = userInfo.headimgurl; ViewData["openid"] = userInfo.Openid; ViewData["nickName"] = userInfo.nickname; if (userInfo.sex == 0) { ViewData["sex"] = "未知"; } else if (userInfo.sex == 1) { ViewData["sex"] = "男"; } else { ViewData["sex"] = "女"; } ViewData["province"] = userInfo.province; ViewData["city"] = userInfo.city; } else { Log("未获取到用户信息"); } } else { Log("access_token:" + oauthToken.access_token + ",openid:" + oauthToken.openid); } } else { return(Redirect( $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={SettingsManager.WeiXin.AppId}&redirect_uri={"http://" + Request.Url.Host + Url.Action("OAuthSnsApiBase")}&response_type=code&scope=snsapi_base&state=123456#wechat_redirect")); } } catch (Exception ex) { Log(ex.Message); ViewData["errmsg"] = ex.Message; } return(View()); }
public void Execute() { // Trace.WriteLine("现在时间是:" + DateTime.Now); lock (_lock) { if (_shuttingDown) { return; } ILoggingService _logger = new LoggingService(); try { VideoServices videoServices = new VideoServices(); ReservationServices reservationServices = new ReservationServices(); CacheService cacheServices = new CacheService(); var videos = videoServices.GetNoticedElementsAsync().Result; //_logger.Info("消息发送处理视频:" + videos.Count() + "条"); foreach (var video in videos) { var res = video.Reservations; //_logger.Info("Reservations.Any:" + video.Reservations.Any()); if (!video.Reservations.Any()) { continue; } string accesstoken; if (cacheServices.IsSet("access_token")) { accesstoken = (string)cacheServices.Get("access_token"); } else { var atvm = WeChatHepler.GetAccessTokenAsync(SettingsManager.WeiXin.AppId, SettingsManager.WeiXin.AppSecret).Result; accesstoken = atvm.access_token; cacheServices.Set("access_token", accesstoken, 120); } //_logger.Info("accesstoken:" + accesstoken); var msg = $"您预约的直播视频[{video.Title}]即将在{video.StartDate:F}直播,At@{DateTime.Now}"; _logger.Info("消息内容:" + msg); var openIds = res.Select(d => d.OpenId).ToArray(); if (openIds.Length == 1) { // _logger.Info("accesstoken:单发"); var message = new SingleSendMessagesVM { ToUser = openIds[0], MsgType = "text", Text = new Message { Content = msg } }; var json = JsonConvert.SerializeObject(message, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }); //Log("post:" + json); HttpContent content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = WeChatHepler.SingleSendMessagesAsync(accesstoken, content).Result; if (result.ErrCode == 0) { foreach (var r in res) { r.NoticedDate = DateTime.Now; } videoServices.Update(video); } _logger.Info($"单发结果[errcode:{result.ErrCode},errmsg:{result.ErrMsg}];消息主体:{json}"); } else { // _logger.Info("accesstoken:群发"); var message = new BatchSendMessagesVM { ToUser = openIds, MsgType = "text", Text = new Message { Content = msg } }; var json = JsonConvert.SerializeObject(message, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }); //Log("post:" + json); HttpContent content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = WeChatHepler.BatchSendMessagesAsync(accesstoken, content).Result; if (result.ErrCode == 0) { foreach (var r in res) { r.NoticedDate = DateTime.Now; } videoServices.Update(video); } _logger.Info($"群发结果[errcode:{result.ErrCode},errmsg:{result.ErrMsg}];消息主体:{json}"); } } } catch (Exception ex) { _logger.Fatal("发送失败:" + ex.Message); } } }
public async Task <HttpResponseMessage> ReservationVideo(int videoId) { if (!User.Identity.IsAuthenticated) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "还未授权")); } var openId = User.Identity.Name; try { var video = _videoServices.GetById(videoId); if (video == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "不存在此视频!")); } var vm = new Reservation { VideoId = videoId, OpenId = openId.ToString(), CreatedDate = DateTime.Now }; var message = new SingleSendMessagesVM { ToUser = openId.ToString(), MsgType = "text", Text = new Message { Content = $"你已成功预约了直播:【{video.Title}】" } }; var returnMsg = "预约成功"; var res = _reservationServices.GetById(vm.VideoId, vm.OpenId); if (res != null) { _reservationServices.Delete(res); message.Text = new Message { Content = $"你已成功取消了直播:【{video.Title}】的预约" }; returnMsg = "已取消预约"; } else { _reservationServices.Create(vm); } var json = JsonConvert.SerializeObject(message, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }); HttpContent content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); string accesstoken; if (_cacheServices.IsSet("access_token")) { accesstoken = (string)_cacheServices.Get("access_token"); } else { var atvm = await WeChatHepler.GetAccessTokenAsync(SettingsManager.WeiXin.AppId, SettingsManager.WeiXin.AppSecret); accesstoken = atvm.access_token; _cacheServices.Set("access_token", accesstoken, 120); } var result = await WeChatHepler.SingleSendMessagesAsync(accesstoken, content); _logger.Info($"单发结果[errcode:{result.ErrCode},errmsg:{result.ErrMsg}];消息主体:{json}"); return(Request.CreateResponse(HttpStatusCode.OK, returnMsg)); } catch (Exception ex) { _logger.Fatal(ex); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message, ex)); } }