/// <summary> /// 获取当前菜单,如果菜单不存在,将返回null /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="agentId">企业应用的id,整型。可在应用的设置页面查看</param> /// <returns></returns> public static GetMenuResult GetMenu(string accessTokenOrAppId, int agentId) { return(ApiHandlerWapper.TryCommonApi(accessToken => { var url = string.Format(Config.ApiWorkHost + "/cgi-bin/menu/get?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); var jsonString = RequestUtility.HttpGet(CommonDI.CommonSP, url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; try { var jsonResult = SerializerHelper.GetObject <GetMenuResultFull>(jsonString); if (jsonResult.button == null || jsonResult.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return finalResult; }, accessTokenOrAppId)); }
/// <summary> /// 获取当前菜单,如果菜单不存在,将返回null /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public static MenuJsonResult GetMenu(string accessToken) { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); MenuJsonResult finalResult; try { var jsonResult = JsonConvert.DeserializeObject <MenuJsonResult>(jsonString); if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { Log.Instance.WriteError(ex.ToString()); finalResult = null; } return(finalResult); }
public static T ConvertJson(string url) { string content = RequestUtility.HttpGet(url); T result = JsonConvert.DeserializeObject <T>(content); return(result); }
/// <summary> /// 第四步:拉取用户信息(需scope为 snsapi_userinfo) /// </summary> /// <param name="accessToken"></param> /// <param name="openId">要获取用信息的用户OpenId</param> /// <returns></returns> public static OAuthUserInfo GetUserInfo(string accessToken, string openId) { var url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", accessToken, openId); string result = RequestUtility.HttpGet(url, null); return(ApiHelper.GetResult <OAuthUserInfo>(result)); }
public async Task <JsonResult> SendAPi(int urlID, string url, string urlPara) { using (ApiManaRepository rep = new ApiManaRepository()) { var apiUrl = await rep.GetApiUrlAsync(urlID); Dictionary <string, string> dicPara = new Dictionary <string, string>(); string[] paraArray = urlPara.Split('&'); foreach (string str in paraArray) { if (!string.IsNullOrEmpty(str)) { string[] p = str.Split('='); dicPara.Add(p[0], p[1]); } } string result = string.Empty; if (apiUrl.method == 1) { result = RequestUtility.HttpGet(url + apiUrl.Url, dicPara); } else { result = RequestUtility.HttpPost(url + apiUrl.Url, dicPara); } return(Json(result)); } }
/// <summary> /// 获取当前菜单,如果菜单不存在,将返回null /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public static GetMenuResult GetMenu(string accessTokenOrAppId) { return(ApiHandlerWapper.TryCommonApi(accessToken => { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; JavaScriptSerializer js = new JavaScriptSerializer(); try { var jsonResult = js.Deserialize <GetMenuResultFull>(jsonString); if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult, new ButtonGroup()); } catch (WeixinException ex) { finalResult = null; } return finalResult; }, accessTokenOrAppId)); }
/// <summary> /// 获取当前菜单 json /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public string GetMenu2(string accessToken) { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); return(jsonString); }
/// <summary> /// 获得当前服务器外网IP /// </summary> private string GetIP() { try { if (!string.IsNullOrEmpty(IP)) { return(IP); } var url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=IP&rsv_pq=db4eb7d40002dd86&rsv_t=14d7uOUvNnTdrhnrUx0zdEVTPEN8XDq4aH7KkoHAEpTIXkRQkUD00KJ2p94&rqlang=cn&rsv_enter=1&rsv_sug3=2&rsv_sug1=2&rsv_sug7=100&rsv_sug2=0&inputT=875&rsv_sug4=875"; var htmlContent = RequestUtility.HttpGet(url, cookieContainer: null); var result = Regex.Match(htmlContent, @"(?<=本机IP:[^\d+]*)(\d+\.\d+\.\d+\.\d+)(?=</span>)"); if (result.Success) { IP = result.Value; } return(IP); } catch { return(null); } }
/// <summary> /// 从微信公众平台API获取信息的公共方法 /// </summary> /// <param name="urlFormat">API接口地址格式</param> /// <param name="accessToken">微信公众号访问授权AccessToken</param> /// <param name="querys">除了AccessToken还需要传递的其他参数</param> /// <returns></returns> public static T Get <T>(string accessToken, string urlFormat, params string[] querys) { var url = GetApiUrl(urlFormat, accessToken, querys); string result = RequestUtility.HttpGet(url, null); return(GetResult <T>(result)); }
/// <summary> /// 获取当前菜单,如果菜单不存在,将返回null /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="agentId">企业应用的id,整型。可在应用的设置页面查看</param> /// <returns></returns> public static GetMenuResult GetMenu(string accessToken, int agentId) { var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; JavaScriptSerializer js = new JavaScriptSerializer(); try { var jsonResult = js.Deserialize <GetMenuResultFull>(jsonString); if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return(finalResult); }
public static GetMenuResult GetMenu(string accessToken, int agentId) { var url = string.Format(Config.ApiWorkHost + "/cgi-bin/menu/get?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; try { #if NET45 JavaScriptSerializer js = new JavaScriptSerializer(); var jsonResult = js.Deserialize <GetMenuResultFull>(jsonString); #else var jsonResult = JsonConvert.DeserializeObject <GetMenuResultFull>(jsonString); #endif if (jsonResult.button == null || jsonResult.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return(finalResult); }
public ActionResult Get(string url = "https://www.baidu.com") { var html = RequestUtility.HttpGet(url, encoding: Encoding.GetEncoding("GB2312")); html += "<script>alert('This is a remote page')</script>"; return(Content(html)); }
public void HttpGetTest() { return;//已经通过,但需要连接远程测试,太耗时,常规测试时暂时忽略。 var url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; var exceptResult = @"{""errcode"":40013,""errmsg"":""invalid appid""}"; var actualResult = RequestUtility.HttpGet(url,null); Assert.AreEqual(exceptResult, actualResult); }
public ActionResult SimulateLogin() { var url = "http://www.baidu.com"; var cookieContainer = new CookieContainer(); var html = RequestUtility.HttpGet(url, cookieContainer, Encoding.UTF8, null, null, false); return(Content(html)); }
/// <summary> /// 第三步:刷新access_token(如果需要) /// 由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新, /// refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效的后,需要用户重新授权。 /// </summary> /// <param name="appId">公众号的appid</param> /// <param name="refreshToken">填写通过第二步获取到的refresh_token参数</param> /// <param name="grantType"></param> /// <returns></returns> public static OAuthAccessTokenResult RefreshToken(string appId, string refreshToken, string grantType = "refresh_token") { var url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type={1}&refresh_token={2}", appId, grantType, refreshToken); string result = RequestUtility.HttpGet(url, null); return(ApiHelper.GetResult <OAuthAccessTokenResult>(result)); }
/// <summary> /// 第二步:获取AccessToken /// 用户访问第一步网页授权页面后,无论同意或拒绝,都会返回redirectUrl页面。 /// 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。 /// 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE /// </summary> /// <param name="appId">公众号的appid</param> /// <param name="secret">公众号的appsecret</param> /// <param name="code">code作为换取access_token的票据,每次用户授权带上的code将不一样, /// code只能使用一次,5分钟未被使用自动过期。</param> /// <param name="grantType">目前只有authorization_code一种</param> /// <returns></returns> public static OAuthAccessTokenResult GetAccessToken(string appId, string secret, string code, string grantType = "authorization_code") { var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type={3}", appId, secret, code, grantType); string result = RequestUtility.HttpGet(url, null); return(ApiHelper.GetResult <OAuthAccessTokenResult>(result)); }
/// <summary> /// 获取凭证接口 /// </summary> /// <param name="grant_type">获取access_token填写client_credential</param> /// <param name="appid">第三方用户唯一凭证</param> /// <param name="secret">第三方用户唯一凭证密钥,既appsecret</param> /// <returns></returns> public static AccessTokenResult GetToken(string appid, string secret, string grant_type = "client_credential") { //微信公众平台获取access_token接口地址 string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret); string result = RequestUtility.HttpGet(url, null); return(ApiHelper.GetResult <AccessTokenResult>(result)); }
public void HttpGetTest() { return;//已经通过,但需要连接远程测试,太耗时,常规测试时暂时忽略。 var url = Config.ApiMpHost + "/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; var exceptResult = @"{""errcode"":40013,""errmsg"":""invalid appid""}"; var actualResult = RequestUtility.HttpGet(CommonDI.CommonSP, url, null); Assert.AreEqual(exceptResult, actualResult); }
public GetDataResponse GetDateResponse(string getTokenUrl) { var returnText = RequestUtility.HttpGet(getTokenUrl, null); var js = new JavaScriptSerializer(); var returnObj = js.Deserialize <GetDataResponse>(returnText); if (returnObj.result != "success") { LogHelper.Error(typeof(XiaoMiData), returnText); } return(returnObj); }
private MpMenuJsonResult GetMenuData() { try { var url = string.Format("https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token={0}", AccessTokenContainer.TryGetAccessToken(BaseClass.AppId, BaseClass.Secret)); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); return(JsonConvert.DeserializeObject <MpMenuJsonResult>(jsonString)); } catch (Exception e) { return(null); } }
static void Main(string[] args) { //get String url = "http://10.1.1.243:9980/eagle/metric/list"; //get 1 String result1 = RequestUtility.HttpGet(url); Console.WriteLine(result1); System.Threading.Thread.Sleep(1000); //get 2 String result2 = RequestUtility.HttpGetTimeOut(url); Console.WriteLine(result2); System.Threading.Thread.Sleep(1000); }
public static MenuResult GetMenu(string accessTokenOrAppId) { return(ApiHandlerWapper.TryCommonApi(accessToken => { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken.AsUrlData()); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); MenuResult finalResult; finalResult = JsonConvert.DeserializeObject <MenuResult>(jsonString); if (finalResult.menu == null || finalResult.menu.button.Count == 0) { return null; } return finalResult; }, accessTokenOrAppId)); }
private void button3_Click_1(object sender, EventArgs e) { try { var xiaomiDate = new XiaoMiData(); var allSetting = xiaomiDate.GetSetting(); richTextBox1.Text = "get all setting,count:" + allSetting.Count; LogHelper.Info(typeof(Form1), "get all setting,count:" + allSetting.Count); foreach (var setting in allSetting) { //if (setting.WechatId != "13354280516") //{ // continue; //} richTextBox1.Text += "get old access token:wechatId:" + setting.WechatId; LogHelper.Info(typeof(Form1), "get old access token:wechatId:" + setting.WechatId); if (setting.RefreshToken != null) { var url = xiaomiDate.RefreshTokenURL(setting.RefreshToken); LogHelper.Info(typeof(Form1), "get old access token url:" + url); var returnText = RequestUtility.HttpGet(url, null); LogHelper.Info(typeof(Form1), "get new access token::" + returnText); var js = new JavaScriptSerializer(); var returnObj = (Dictionary <string, string>)js.Deserialize(returnText.Replace("&&&START&&&", ""), typeof(Dictionary <string, string>)); if (!returnObj.ContainsKey("error") && returnObj.ContainsKey("access_token") && returnObj.ContainsKey("mac_key") && returnObj.ContainsKey("refresh_token")) { richTextBox1.Text += "update access token:" + returnObj["access_token"]; xiaomiDate.UpdateSettingMacAndToken(returnObj["access_token"], returnObj["mac_key"], returnObj["refresh_token"], setting.WechatId); } else { LogHelper.Error(typeof(Form1), "get new access token error:" + returnText); } } else { LogHelper.Info(typeof(Form1), "current user have not refresh token:"); } } } catch (Exception ex) { LogHelper.Error(typeof(Form1), ex); } }
public async Task <ActionResult> wxAppLogin(string appid, string code) { var config = CommonService.lstSysWeChatConfig.FirstOrDefault(a => a.WeixinCorpId == appid); if (config == null) { throw new UnauthorizedAccessException(); } string s = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code"; string url = string.Format(s, appid, config.WeixinCorpSecret, code); var returnText = RequestUtility.HttpGet(url, Encoding.UTF8); JavaScriptSerializer js = new JavaScriptSerializer(); if (returnText.Contains("errcode")) { //可能发生错误 WxJsonResult errorResult = js.Deserialize <WxJsonResult>(returnText); if (errorResult.errcode != ReturnCode.请求成功) { LogManager.GetLogger(this.GetType()).Error("{2}\r\n微信请求发生错误!错误代码:{0},说明:{1}", (int)errorResult.errcode, errorResult.errmsg, url); //发生错误 throw new ErrorJsonResultException( string.Format("微信请求发生错误!错误代码:{0},说明:{1}", (int)errorResult.errcode, errorResult.errmsg), null, errorResult, url); } } var result = js.Deserialize <MicroAppUserInfo>(returnText); var user = new SysUser() { UserName = result.openid, Id = 0 }; await _authenticationService.SignInNoDB(user, true); return(Json(new { User = result }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 使用GET请求测试URL和TOKEN是否可用 /// </summary> /// <param name="url"></param> /// <param name="token"></param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> public static bool CheckUrlAndToken(string url, string token, int timeOut = 2000) { try { string timestamp = DateTime.Now.Ticks.ToString(); string nonce = "GodBlessYou"; string echostr = Guid.NewGuid().ToString("n"); string signature = CheckSignature.GetSignature(timestamp, nonce, token); url += string.Format("{0}signature={1}×tamp={2}&nonce={3}&echostr={4}", url.Contains("?") ? "&" : "?", signature.AsUrlData(), timestamp.AsUrlData(), nonce.AsUrlData(), echostr.AsUrlData()); var responseStr = RequestUtility.HttpGet(url, null, timeOut: timeOut); return(echostr == responseStr); } catch { return(false); } }
public static GetMenuResult GetMenu(string accessTokenOrAppId) { return(ApiHandlerWapper.TryCommonApi(accessToken => { var url = string.Format(Config.ApiMpHost + "/cgi-bin/menu/get?access_token={0}", accessToken.AsUrlData()); var jsonString = RequestUtility.HttpGet(CommonDI.CommonSP, url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; try { #if NET45 JavaScriptSerializer js = new JavaScriptSerializer(); var jsonResult = js.Deserialize <GetMenuResultFull>(jsonString); #else var jsonResult = Newtonsoft.Json.JsonConvert.DeserializeObject <GetMenuResultFull>(jsonString); #endif if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinMenuException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult, new ButtonGroup()); } catch (WeixinMenuException) { throw; //finalResult = null; } catch (Exception) { throw; } return finalResult; }, accessTokenOrAppId)); }
public string GetAccessToken(string appid, string secret) { //正常情况下access_token有效期为7200秒,这里使用缓存设置短于这个时间即可 string access_token = MemoryCacheHelper.GetCacheItem <string>("access_token", delegate() { string grant_type = "client_credential"; var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret); string result = RequestUtility.HttpGet(url); string token = string.Empty; if (result.Contains("access_token")) { AccessTokenInfo at = JsonHelper <AccessTokenInfo> .ConvertObjJson(result); token = at.access_token; } return(token); }, new TimeSpan(0, 0, 7000)//7000秒过期 ); return(access_token); }
public static JsonMessage Process(HttpRequestModel model) { JsonMessage slt = new JsonMessage() { Flag = false }; if (model == null) { slt.Message = "参数错误"; return(slt); } if (string.IsNullOrEmpty(model.Url)) { slt.Message = "请填写网址"; return(slt); } if (string.IsNullOrEmpty(model.Method)) { slt.Message = "请不要篡改请求方式"; return(slt); } model.Url = model.Url.ToLower(); if (!model.Url.StartsWith("http://")) { model.Url = "http://" + model.Url; } if (!string.IsNullOrEmpty(model.Params)) { if (model.Params.StartsWith("?")) { model.Params = model.Params.Replace("?", ""); } if (model.Method == "get") { if (model.Url.IndexOf("?") > 0) { model.Url = model.Url + "&" + model.Params; } else { model.Url = model.Url + "?" + model.Params; } } } try { switch (model.Method) { case "get": slt.Flag = true; slt.Data = RequestUtility.HttpGet(model.Url); break; case "post": slt.Flag = true; Stream queryStream = RequestUtility.GetQueryStream(model.Params); slt.Data = RequestUtility.HttpPost(model.Url, null, queryStream); break; } } catch (Exception ex) { slt.Flag = false; slt.Message = ex.Message; } return(slt); }
public IActionResult Index() { Func <string, FileVersionInfo> getFileVersionInfo = dllFileName => #if NET45 FileVersionInfo.GetVersionInfo(Server.MapPath("~/bin/" + dllFileName)); #elif NETCOREAPP2_0 || NETSTANDARD2_0 { var dllPath = Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.GetMapPath( System.IO.Path.Combine(AppContext.BaseDirectory, dllFileName)); //dll所在目录 return(FileVersionInfo.GetVersionInfo(dllPath)); }; #else { var dllPath = Server.GetMapPath("~/bin/netcoreapp1.1/" + dllFileName); return(FileVersionInfo.GetVersionInfo(dllPath)); }; #endif Func <FileVersionInfo, string> getDisplayVersion = fileVersionInfo => Regex.Match(fileVersionInfo.FileVersion, @"\d+\.\d+\.\d+").Value; TempData["WeixinVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.dll")); TempData["MpVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.MP.dll")); TempData["ExtensionVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.MP.MvcExtension.dll")); TempData["OpenVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.Open.dll")); //TempData["QYVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.QY.dll"));//已经停止更新 TempData["WorkVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.Work.dll")); TempData["RedisCacheVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.Cache.Redis.dll")); TempData["MemcachedCacheVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.Cache.Memcached.dll")); TempData["WxOpenVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.WxOpen.dll")); TempData["WebSocketVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.WebSocket.dll")); //缓存 //var containerCacheStrategy = CacheStrategyFactory.GetContainerCacheStrategyInstance(); var containerCacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance().ContainerCacheStrategy; TempData["CacheStrategy"] = containerCacheStrategy.GetType().Name.Replace("ContainerCacheStrategy", ""); //文档下载版本 var configHelper = new ConfigHelper(this.HttpContext); var config = configHelper.GetConfig(); TempData["NewestDocumentVersion"] = config.Versions.First(); #if NET45 Weixin.WeixinTrace.SendCustomLog("首页被访问", string.Format("Url:{0}\r\nIP:{1}", Request.Url, Request.UserHostName)); #else Weixin.WeixinTrace.SendCustomLog("首页被访问", string.Format("Url:{0}\r\nIP:{1}", Request.Host, HttpContext.Connection.RemoteIpAddress)); //or use Header: REMOTE_ADDR #endif //测试Get方法 var html = RequestUtility.HttpGet("https://baidu.com", refererUrl: "https://sdk.weixin.senparc.com"); if (html.Length == 0) { throw new Exception("RequestUtility.HttpGet()方法测试失败"); } return(View()); }