/// <summary> /// 生成微信AccessToken /// </summary> /// <param name="appId">ID</param> /// <param name="appSecret">秘钥</param> /// <param name="errMsg">出错信息</param> /// <returns></returns> public static string BuildAccessToken(string appId, string appSecret, out string errMsg) { errMsg = ""; try { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret); IHttpForm _httpForm = new HttpForm("", 15000, true, 8); url += "&rnd=" + Guid.NewGuid().ToString(); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = url }); Dictionary <object, object> dict = JsonConvert.DeserializeObject <Dictionary <object, object> >(_response.Response); if (dict.ContainsKey("access_token")) { return(dict["access_token"].ToString()); } errMsg = string.Format("获取AccessToken失败:{0}", _response.Response); return(""); } catch (Exception ex) { errMsg = string.Format("BuildAccessToken异常:{0}|{1}", ex.Message, ex.StackTrace); return(""); } }
/// <summary> /// 生成JSSDK_API调用用到的票据 /// </summary> /// <param name="accessToken"></param> /// <param name="errMsg">出错信息</param> /// <returns></returns> public static string BuildJsApiTickets(string accessToken, out string errMsg) { errMsg = ""; try { string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={0}", accessToken); IHttpForm _httpForm = new HttpForm("", 1500, true, 8); url += "&rnd=" + Guid.NewGuid().ToString(); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = url }); Dictionary <object, object> dict = JsonConvert.DeserializeObject <Dictionary <object, object> >(_response.Response); if (dict.ContainsKey("ticket")) { return(dict["ticket"].ToString()); } errMsg = string.Format("获取JsApiTickets失败:{0}", _response.Response); return(""); } catch (Exception ex) { errMsg = string.Format("BuildJsApiTickets异常::{0}|{1}", ex.Message, ex.StackTrace); return(""); } }
/// <summary> /// 获取access_token,获取授权,返回json数据 /// </summary> private string GetGrantTypeRequest(string appid, string appsecret, int flag) { string url = string.Empty; if (flag == 2) { url = string.Format("https://api.yixin.im/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret); } else if (flag == 1) { url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret); } else if (flag == 3) { return(""); } IHttpForm _httpForm = new HttpForm(managerSiteAddr, 1500, true, 8); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = url }); string json = _response.Response.ToString(); return(json); }
private static string DoPost(NameValueCollection collection) { IHttpForm httpForm = new HttpForm("", 60000, true, 8); HttpFormResponse response = httpForm.Post(new HttpFormPostRequest() { Url = Config.GATE_WAY, FormFields = collection }); return(response.Response); }
/// <summary> /// 自定义菜单get请求 /// </summary> /// <param name="url"></param> /// <param name="access_token"></param> /// <returns></returns> private string MenuRequest(string url, string access_token) { IHttpForm _httpForm = new HttpForm(managerSiteAddr, 1500, true, 8); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = url }); string json = _response.Response.ToString(); return(json); }
/// <summary> /// 设置自定义菜单(包含创建和删除) /// </summary> /// <param name="postData">菜单json数据</param> /// <param name="access_token">凭证</param> /// <returns></returns> private string CreateMenuRequest(string url, string postData, string access_token) { IHttpForm _httpForm = new HttpForm(managerSiteAddr, 1500, true, 8); HttpFormResponse _response = _httpForm.Post(new HttpFormPostRawRequest() { Url = url, Data = postData }); string json = _response.Response.ToString(); return(json); }
/// <summary> /// v1.3.17 2011-12-15 /// </summary> private CookieContainer Login(string name, string pass) { IHttpForm http = HttpFormFactory.DefaultHttpForm(); name = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(name)); pass = HttpUtility.UrlEncode(pass); var preloginUrl = string.Format("http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su={0}&client=ssologin.js(v1.3.17)&_={1}", name, DateTimeHelper.GetTimestamp()); HttpFormResponse response = http.Get(preloginUrl); Match m = Regex.Match(response.Response, "\"retcode\":(?<retcode>\\d),\"servertime\":(?<servertime>\\d+),\"pcid\":\"[\\w]+\",\"nonce\":\"(?<nonce>[0-9a-zA-Z]+)\"", RegexOptions.IgnoreCase); var servertime = m.Groups["servertime"].Value; var nonce = m.Groups["nonce"].Value; JSSha1Util jsMD5 = new JSSha1Util(); var password = jsMD5.Hex_sha1("" + jsMD5.Hex_sha1(jsMD5.Hex_sha1(pass)) + servertime + nonce); var postData = string.Format("entry=weibo&gateway=1&from=&savestate=7&useticket=1&ssosimplelogin=1&vsnf=1&vsnval=&su={0}&service=miniblog&servertime={1}&nonce={2}&pwencode=wsse&sp={3}&encoding=UTF-8&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META", name, servertime, nonce, password); HttpFormPostRawRequest postRequest = new HttpFormPostRawRequest(); postRequest.Data = postData; postRequest.Url = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.17)"; postRequest.Referer = "http://weibo.com/"; postRequest.Cookies = new CookieContainer(); response = http.Post(postRequest); var content = response.Response; m = Regex.Match(content, "location\\.replace\\(['\"](?<url>.*?)['\"]\\)", RegexOptions.IgnoreCase); var nextUrl = m.Groups["url"].Value; response.Cookies = CookieHelper.UpdateDomain(response.Cookies, "weibo.com"); HttpFormGetRequest request = new HttpFormGetRequest(); request.Cookies = response.Cookies; request.Referer = "http://weibo.com/"; request.Url = nextUrl; response = http.Get(request); bool isLogin = response.Response.Contains("\"result\":true,\""); return(response.Cookies); }
public void Get_Async_With_Callback_Should_Return_Cached_Response_When_Url_Exists_In_Cache() { // ReSharper disable RedundantAssignment HttpFormResponse httpResponse = new HttpFormResponse { Response = "This is dummy response" }; // ReSharper restore RedundantAssignment cache.Setup(c => c.TryGet(It.IsAny <string>(), out httpResponse)).Returns(true); _cachingHttpForm.GetAsync(new HttpFormGetRequest { Url = "http://www.test.com" }, h => Assert.True(h.Response.Length > 0), delegate { }); }
public string BuildAccessToken(string appid, string appsecret, int customerId) { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret); IHttpForm _httpForm = new HttpForm("", 15000, true, 8); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = url }); Dictionary <object, object> dict = JsonConvert.DeserializeObject <Dictionary <object, object> >(_response.Response); if (dict.ContainsKey("access_token")) { return(dict["access_token"].ToString()); } throw new Exception(string.Format("非Senparc获取AccessToken失败->appid:{0},appsecret:{1},商户Id:{2}", appid, appsecret, customerId)); }
public string Get(string url) { HttpFormGetRequest request = new HttpFormGetRequest(); request.Url = url; request.Proxy = Proxy; request.Encoding = Encode; HttpFormResponse response = http.Get(request); if (response == null) { return(null); } return(response.Response); }
public string Post(string url, string postData) { HttpFormPostRawRequest request = new HttpFormPostRawRequest(); request.Url = url; request.Data = postData; request.Proxy = Proxy; request.Encoding = Encode; HttpFormResponse response = http.Post(request); if (response == null) { return(null); } return(response.Response); }
/// <summary> /// 获取微信用户基本信息(包括UnionID机制) /// </summary> /// <param name="accessToken"></param> /// <param name="openid"></param> /// <returns></returns> public static MPUserInfoResult GetWxUserInfo(string wxApiUrl, out string errmsg) { errmsg = ""; try { IHttpForm _httpForm = new HttpForm("HOT-MPHelper", 15000, true, 8); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = wxApiUrl }); MPUserInfoResult result = JsonConvert.DeserializeObject <MPUserInfoResult>(_response.Response); return(result); } catch (Exception ex) { errmsg = ex.Message; LogHelper.Write("获取微信用户基本信息(GetWxUserInfo)异常 -->:" + ex.Message); return(null); } }
private string BuildTicket(string accessToken) { try { string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={0}", accessToken); IHttpForm _httpForm = new HttpForm("", 1500, true, 8); HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest() { Url = url }); Dictionary <object, object> dict = JsonHelper.JsonDeserialize <Dictionary <object, object> >(_response.Response); if (dict.ContainsKey("ticket")) { return(dict["ticket"].ToString()); } LogHelper.Log("GetTicket(获取jsapi_ticket失败):" + _response.Response, LogHelperTag.ERROR); return(""); } catch (Exception ex) { LogHelper.Log("WxJsApiTicketProvider->GetTicket(string accessToken)报错:" + ex.Message + "|accessToken:" + accessToken, LogHelperTag.ERROR); return(""); } }
protected void btnGo_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtAppKey.Text) || string.IsNullOrEmpty(txtAppSecret.Text)) { lblErrorMsg.Text = "请输入appkey和appsecret"; return; } Session.Clear(); var site = int.Parse(drpSite.SelectedValue); if (site == 5) { site = 0; } OAuthAPIEntity entity = OAuthAPIDAL.Load(txtAppKey.Text, txtUserName.Text, site); if (entity != null) { lblErrorMsg.Text = "已经存在"; txtToken.Text = entity.Token; txtTokenSecret.Text = entity.TokenSecret; IOAuthAPI oauthAPI2 = OAuthAPIFactory.CreateOAuthAPI(); oauthAPI2.RequestTokenUrl = entity.RequestTokenUrl; oauthAPI2.AuthorizeUrl = entity.AuthorizeUrl; oauthAPI2.AccessTokenUrl = entity.AccessTokenUrl; oauthAPI2.AppKey = entity.AppKey; oauthAPI2.AppSecret = entity.AppSecret; oauthAPI2.Token = entity.Token; oauthAPI2.TokenSecret = entity.TokenSecret; Session["oauthAPI"] = oauthAPI2; return; } OAuthAPIEntity oauthAPIEntity = GetOAuthAPI(site); oauthAPIEntity.AppKey = txtAppKey.Text; oauthAPIEntity.AppSecret = txtAppSecret.Text; oauthAPIEntity.UserName = txtUserName.Text; oauthAPIEntity.Password = txtPassword.Text; oauthAPIEntity.Site = site; Session["oauthAPIObj"] = oauthAPIEntity; if (int.Parse(drpSite.SelectedValue) >= 5) { IHttpForm http = HttpFormFactory.DefaultHttpForm(); string authorizeFormat = "https://api.weibo.com/oauth2/authorize?client_id={0}&redirect_uri={1}&response_type=code"; string authorize = string.Format(authorizeFormat, oauthAPIEntity.AppKey, "http://barefoot.3322.org/queryservice.svc/query"); HttpFormGetRequest getRequest = new HttpFormGetRequest(); getRequest.Cookies = Login(oauthAPIEntity.UserName, oauthAPIEntity.Password); getRequest.Url = authorize; HttpFormResponse response = http.Get(getRequest); Match m = null; if (!response.Response.StartsWith("\"code=")) { m = Regex.Match(response.Response, "<input\\stype=\"hidden\"\\sname=\"regCallback\"\\svalue=\"(?<regCallback>[^\"]+)\"/>", RegexOptions.IgnoreCase | RegexOptions.Multiline); string regCallback = m.Groups["regCallback"].Value; string regPostData = "action=submit&response_type=code®Callback=" + regCallback + "&redirect_uri=http://barefoot.3322.org/queryservice.svc/query&client_id=" + oauthAPIEntity.AppKey + "&state=&from="; HttpFormPostRawRequest regRequest = new HttpFormPostRawRequest(); regRequest.Data = regPostData; regRequest.Url = "https://api.weibo.com/oauth2/authorize"; regRequest.Cookies = response.Cookies; response = http.Post(regRequest); } string code = response.Response.Trim('\"').Substring(5); HttpFormPostRawRequest request = new HttpFormPostRawRequest(); request.Url = "https://api.weibo.com/oauth2/access_token"; string postDataFormat = "client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}&redirect_uri=http://barefoot.3322.org/queryservice.svc/query"; string postData = string.Format(postDataFormat, oauthAPIEntity.AppKey, oauthAPIEntity.AppSecret, code); request.Data = postData; response = http.Post(request); m = Regex.Match(response.Response, "{\"access_token\":\"(?<token>[^\"]+)\","); string token = m.Groups["token"].Value; txtToken.Text = token; txtTokenSecret.Text = code; this.lblErrorMsg.Text = "授权成功"; oauthAPIEntity.Token = token; oauthAPIEntity.TokenSecret = code; oauthAPIEntity.Version = 2; Session["oauthAPIObj"] = oauthAPIEntity; } else { IOAuthAPI oauthAPI = OAuthAPIFactory.CreateOAuthAPI(); oauthAPI.RequestTokenUrl = oauthAPIEntity.RequestTokenUrl; oauthAPI.AuthorizeUrl = oauthAPIEntity.AuthorizeUrl; oauthAPI.AccessTokenUrl = oauthAPIEntity.AccessTokenUrl; if (oauthAPI.GetRequestToken(oauthAPIEntity.AppKey, oauthAPIEntity.AppSecret, Config.CallbackUrl)) { var authorizationUrl = oauthAPI.GetAuthorize(Config.CallbackUrl); Session["oauthAPI"] = oauthAPI; if (!string.IsNullOrEmpty(authorizationUrl)) { Response.Redirect(authorizationUrl); } } } }