public static HttpUtil shareInstance(){ if (instance == null){ GameObject ob = new GameObject(); ob.name = "httpUtil"; instance = (HttpUtil)ob.AddComponent<HttpUtil>(); DontDestroyOnLoad(ob); } return instance; }
public IList<CarRealtimeData> GetAllCarRealtimeDatas(string openId, IList<string> vid, string interval) { #region Make parameters and Request the GPS-DataInterface IDictionary<string, string> commRequestObj = new Dictionary<string, string>(); commRequestObj.Add("openid", openId); IDictionary<string, object> contentParam = new Dictionary<string, object>(); contentParam.Add("vid", vid); contentParam.Add("interval", interval); IDictionary<string, object> jsonObj = new Dictionary<string, object>(); jsonObj.Add("code", "5"); jsonObj.Add("content", contentParam); jsonObj.Add("serialNum", GenerateTimestamp()); jsonObj.Add("commRequest", commRequestObj); JavaScriptSerializer serializer = new JavaScriptSerializer(); string paramsString = serializer.Serialize(jsonObj); // Request the GPS-DataInterface via http protocol string responseStr = new HttpUtil().ExecutePost(MiscConstants.DATA_INTERFACE_URL, paramsString); #endregion #region Deserialize result json string and return IList<TeamGroup> data IDictionary<string, object> responseDict = serializer.Deserialize<IDictionary<string, object>>(responseStr); IDictionary<string, object> commResponseDict = (IDictionary<string, object>)(responseDict["commResponse"]); IList<CarRealtimeData> carList = new List<CarRealtimeData>(); IList<object> content = new List<object>(); if (commResponseDict["result"].ToString().Equals("1")) { content = (IList<object>)responseDict["content"]; foreach (var item in content) { IDictionary<string, object> itemDict = (IDictionary<string, object>)item; var dataItem = new CarRealtimeData() { vid = itemDict["vid"].ToString(), speed = itemDict["speed"].ToString(), position = itemDict["position"].ToString(), gpsTime = itemDict["gpsTime"].ToString(), }; carList.Add(dataItem); } } return carList; #endregion }
/// <summary> /// 订阅号 通过code去腾讯的微信后台换取access_token和openid /// </summary> /// <param name="code"></param> /// <returns></returns> public static string GetOpenId(string code) { string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + MiscConstants.APP_ID + "&secret=" + MiscConstants.APP_SECRET + "&code=" + code + "&grant_type=authorization_code"; HttpUtil httpUtil = new HttpUtil(); string jsonString = httpUtil.ExecuteGet(url); SerializeUtil serializeUtil = new SerializeUtil(); IDictionary<string, string> dict = serializeUtil.ToObject<IDictionary<string, string>>(jsonString); //string accessToken = dict["access_token"]; string openId = dict["openid"]; return openId; }
public IList<CarEntity> GetAllCars(string openId) { #region Make parameters and Request the GPS-DataInterface IDictionary<string, string> commRequestObj = new Dictionary<string, string>(); commRequestObj.Add("openid", openId); IDictionary<string, object> jsonObj = new Dictionary<string, object>(); jsonObj.Add("code", "4"); jsonObj.Add("content", null); jsonObj.Add("serialNum", GenerateTimestamp()); jsonObj.Add("commRequest", commRequestObj); JavaScriptSerializer serializer = new JavaScriptSerializer(); string paramsString = serializer.Serialize(jsonObj); // Request the GPS-DataInterface via http protocol string responseStr = new HttpUtil().ExecutePost(MiscConstants.DATA_INTERFACE_URL, paramsString); #endregion #region Deserialize result json string and return IList<TeamGroup> data IDictionary<string, object> responseDict = serializer.Deserialize<IDictionary<string, object>>(responseStr); IDictionary<string, object> commResponseDict = (IDictionary<string, object>)(responseDict["commResponse"]); IList<CarEntity> carList = new List<CarEntity>(); IList<object> content = new List<object>(); if (commResponseDict["result"].ToString().Equals("1")) { content = (IList<object>)responseDict["content"]; foreach (var item in content) { IDictionary<string, object> itemDict = (IDictionary<string, object>)item; var carEntity = new CarEntity() { tid = itemDict["tid"].ToString(), vid = itemDict["vid"].ToString(), vLicense = itemDict["vLicense"].ToString(), cid = itemDict["cid"].ToString() }; carList.Add(carEntity); } } return carList; #endregion }
protected void Page_Load(object sender, EventArgs e) { StreamReader reader = new StreamReader(Request.InputStream); string jsonStr = reader.ReadToEnd(); // jsonObj 中已经含有字段"code"和"content" IDictionary<string,object> jsonObj = (IDictionary<string,object>)serializer.DeserializeObject(jsonStr); // 时间戳 DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); DateTime nowTime = DateTime.Now; long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero); #if DEBUG // 已经绑定的openId, 某个openId如下 string userId = "oRggMwOdVpu4OeS8H3dJkEgdiEuo"; #else string userId = (Session["UserId"] == null) ? "" : Session["UserId"].ToString(); #endif // DEBUG 结束 IDictionary<string, string> commRequestObj = new Dictionary<string, string>(); string responseStr = string.Empty; if (userId != string.Empty) { commRequestObj.Add("openid", userId); // jsonObj 中已经含有字段"code"和"content" jsonObj.Add("serialNum", unixTime); jsonObj.Add("commRequest", commRequestObj); string paramsString = serializer.Serialize(jsonObj); // 请求GPS数据接口 responseStr = new HttpUtil().ExecutePost(MiscConstants.DATA_INTERFACE_URL, paramsString); } Response.Clear(); Response.Write(responseStr);//sent result to client Response.End(); }
protected void Page_Load(object sender, EventArgs e) { StreamReader reader = new StreamReader(Request.InputStream); string jsonStr = reader.ReadToEnd(); // jsonObj 中已经含有字段"content" IDictionary<string, object> jsonObj = (IDictionary<string, object>)serializer.DeserializeObject(jsonStr); // 时间戳 DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); DateTime nowTime = DateTime.Now; long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero); #if DEBUG // 已经绑定的openId, 某个openId如下 string userId = "oRggMwOdVpu4OeS8H3dJkEgdiEuo"; #else string userId = (Session["UserId"] == null) ? "" : Session["UserId"].ToString(); #endif // DEBUG 结束 IDictionary<string, string> commRequestObj = new Dictionary<string, string>(); commRequestObj.Add("openid", userId); // jsonObj 中已经含有字段"content" jsonObj.Add("code", "7"); jsonObj.Add("serialNum", unixTime); jsonObj.Add("commRequest", commRequestObj); string paramsString = SerializerProperty.Serialize(jsonObj); // 请求GPS数据接口 string responseStr = new HttpUtil().ExecutePost(MiscConstants.DATA_INTERFACE_URL, paramsString); //json反序列化 IDictionary<string, object> responseRoot = serializer.Deserialize<IDictionary<string, object>>(responseStr); IDictionary<string, object> commResponse = (IDictionary<string, object>)(responseRoot["commResponse"]); //IDictionary<string, HistoricalTrack> responseContent = null; HistoricalTrack responseContent = null; IList<GPSData> gpsList = new List<GPSData>(); StringBuilder coords = new StringBuilder(); //存待转换的gps坐标 string ak = "EMwoMb94rarHMWw4MP1lr8rb"; //百度地图密钥 if (commResponse["result"].ToString().Equals("1") || commResponse["result"].ToString().Equals("4")) { //成功 object tmpJsonObj = responseRoot["content"]; // 先反序列化,然后按照class 'HistoricalTrack'来反序列化 responseContent = serializer.Deserialize<HistoricalTrack>(serializer.Serialize(tmpJsonObj)); gpsList = responseContent.data; for (int i = 0, len = gpsList.Count; i < len; i++) { coords.Append(gpsList[i].lon).Append(",").Append(gpsList[i].lat).Append(";"); } } string resultString = string.Empty; if (commResponse["result"].ToString().Equals("1")) { //string baiduGPSUrl = "http://api.map.baidu.com/geoconv/v1/?coords={coords}&from=1&to=5&ak={ak}"; string strVar = coords.ToString(); string coordsString = strVar.Substring(0, strVar.Length - 1); string baiduGPSUrl = string.Format("http://api.map.baidu.com/geoconv/v1/?coords={0}&from=1&to=5&ak={1}", coordsString, ak); string responseBaiduStr = new HttpUtil().ExecuteGet(baiduGPSUrl); IDictionary<string, object> baiduResponseDict = serializer.Deserialize<IDictionary<string, object>>(responseBaiduStr); IList<ContractCoordinate> positionData = serializer.Deserialize<IList<ContractCoordinate>>(serializer.Serialize(baiduResponseDict["result"])); // 将从数据接口得到的数据中的lon, lat替换成相应的客户需要的坐标系 for (int i = 0, len = gpsList.Count; i < len; i++) { gpsList[i].lon = positionData[i].x; gpsList[i].lat = positionData[i].y; } } else if (commResponse["result"].ToString().Equals("4")) { responseContent.data = new List<GPSData>(); } resultString = serializer.Serialize(responseContent); Response.Clear(); Response.Write(resultString);//sent result to client Response.End(); }
/// <summary> /// 验证用户UserId(企业号中用UserId)请求GPS数据库中此用户是否被验证成功 /// </summary> private void ValidateUser() { Session["HostUrl"] = MiscConstants.HOST_URL; // Session["UserId"]的维护 // userId 貌似为28位字符串,但是并未得到官方正式,至少它是长度大于9的 if (Session["UserId"] == null || Session["UserId"].ToString().Equals(string.Empty)) { string state = Request["state"]; string code = Request["code"]; if (code != null && code.Length > 0) { //通过code去腾讯的微信后台换取access_token和userId //OpenId Session["UserId"] = OAuthUtil.GetOpenId(code); } } #region Session["isBinded"]的维护 // Session["isBinded"]的维护 if (!(Session["isBinded"] != null && Session["isBinded"].ToString().Equals("1"))) { IDictionary<string, object> jsonObj = new Dictionary<string, object>(); //时间戳 DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); DateTime nowTime = DateTime.Now; long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero); string userIdVar = (Session["UserId"] == null) ? string.Empty : Session["UserId"].ToString(); //string UserId = "oRggMwOdVpu4OeS8H3dJkEgdiEuo"; IDictionary<string, string> commRequestObj = new Dictionary<string, string>(); commRequestObj.Add("openid", userIdVar); jsonObj.Add("serialNum", unixTime); jsonObj.Add("commRequest", commRequestObj); jsonObj.Add("code", "2"); jsonObj.Add("content", null); string paramsString = serializer.Serialize(jsonObj); if (userIdVar != string.Empty) { string responseStr = new HttpUtil().ExecutePost(MiscConstants.DATA_INTERFACE_URL, paramsString); IDictionary<string, object> resultJsonObj = serializer.Deserialize<IDictionary<string, object>>(responseStr); IDictionary<string, object> resultDict = (IDictionary<string, object>)(resultJsonObj["commResponse"]); string resultCodeVar = resultDict["result"].ToString(); // 如果此用户未被绑定,就redirect到login.aspx页面 if (resultCodeVar == "2" || resultCodeVar == "5") { string code = Request["code"]; if (code != null && code.Length > 0) { string state1 = Request["state"]; //var redirectUrl = MiscConstants.HOST_URL + "/views/login.aspx?state=" + state1 + "&code=" + code + "&userId=" + userIdVar + "&resultCode=" + resultCodeVar; var redirectUrl = MiscConstants.HOST_URL + "/views/login.aspx"; Response.Redirect(redirectUrl); } } // 否则,设置Session["isBinded"]为“1” else Session["isBinded"] = "1"; } } #endregion }
/// <summary> /// billDate格式 20141212 /// </summary> /// <param name="context"></param> /// <param name="billDate"></param> /// <returns></returns> public BaseResult DownloadBill(HttpContextBase context, string billDate,WeChatParam param) { var packageReq = new RequestHandler(context); packageReq.SetKey(GetConfig.GetKey(param)); packageReq.SetParameter("appid", GetConfig.GetAppid(param)); packageReq.SetParameter("mch_id", GetConfig.GetMchId(param)); packageReq.SetParameter("nonce_str", GetNoncestr()); packageReq.SetParameter("bill_date", billDate); packageReq.SetParameter("bill_type", "ALL"); packageReq.SetParameter("sign", packageReq.CreateMd5Sign()); var reqXml = packageReq.ParseXml(); var httpClient = new HttpUtil(); httpClient.SetCharset(context.Request.ContentEncoding.BodyName); var result = httpClient.Send(reqXml, ApiList.DownloadBillUrl); try { var xe = XElement.Parse(result, LoadOptions.SetLineInfo); var reResult1 = xe.GetElement("return_code") == null ? "" : xe.GetElement("return_code").Value; var reResult2 = xe.GetElement("return_msg") == null ? "" : xe.GetElement("return_msg").Value; return new BaseResult() { IsSuccess = false, Data = "", Message = reResult1 +"_" + reResult2 }; } catch (Exception) { var list = new List<Bill>(); var myList = result.Replace("\r\n", "|").Split('|').Skip(1).ToList<string>(); myList.RemoveAt(myList.Count() - 1); myList.RemoveAt(myList.Count() - 1); myList.RemoveAt(myList.Count() - 1); string[] arr; foreach (var str in myList) { arr = str.Replace("`", "").Split(','); #region 赋值 list.Add(new Bill() { 交易时间 = arr[0], 公众账号ID = arr[1], 商户号 = arr[2], 子商户号 = arr[3], 设备号 = arr[4], 微信订单号 = arr[5], 商户订单号 = arr[6], 用户标识 = arr[7], 交易类型 = arr[8], 交易状态 = arr[9], 付款银行 = arr[10], 货币种类 = arr[11], 总金额 = arr[12], 企业红包金额 = arr[13], 微信退款单号 = arr[14], 商户退款单号 = arr[15], 退款金额 = arr[16], 企业红包退款金额 = arr[17], 退款类型 = arr[18], 退款状态 = arr[19], 商品名称 = arr[20], 商户数据包 = arr[21], 手续费 = arr[22], 费率 = arr[23] }); #endregion } return new BaseResult() { IsSuccess = true, Data = list }; } }
/// <summary> /// 传入ProductName,OrderNumber,TotalFee,TimeExpire,OpenId(可选),TradeType,NotifyUrl(可选) /// </summary> /// <param name="param"></param> /// <param name="context"></param> /// <returns></returns> public string GetUnifiedOrder(PayParam param, HttpContextBase context) { if (param.TotalFee == null || string.IsNullOrWhiteSpace(param.ProductName) || string.IsNullOrWhiteSpace(param.OrderNumber) || string.IsNullOrWhiteSpace(param.TimeExpire) || param.TradeType == null) { return "参数错误"; } var req = new RequestHandler(context); req.SetKey(GetConfig.GetKey(param)); req.SetParameter("appid", GetConfig.GetAppid(param)); req.SetParameter("mch_id", GetConfig.GetMchId(param)); req.SetParameter("nonce_str", GetNoncestr()); req.SetParameter("body", param.ProductName); req.SetParameter("out_trade_no", param.OrderNumber); req.SetParameter("total_fee", param.TotalFee.ToString()); req.SetParameter("spbill_create_ip", IPHelper.GetVisitorIP()); req.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); req.SetParameter("time_expire", param.TimeExpire); req.SetParameter("notify_url", string.IsNullOrWhiteSpace(param.NotifyUrl) ? GetConfig.GetNotify(param) : param.NotifyUrl); req.SetParameter("trade_type", param.TradeType.ToString()); if (!string.IsNullOrWhiteSpace(param.OpenId)) { req.SetParameter("openid", param.OpenId); } req.SetParameter("sign", req.CreateMd5Sign()); var reqXml = req.ParseXml(); //LogHelper.WriteLog("aa_", "reqXml的值是:" + reqXml); var http = new HttpUtil(); http.SetCharset(context.Request.ContentEncoding.BodyName); var result = http.Send(reqXml, ApiList.UnifiedOrderUrl); return result; }
/// <summary> /// 传入订单号OrderNumber,RefundNumber,总金额total_fee(分),RefundFee退款金额(分), /// </summary> /// <param name="context"></param> /// <param name="param"></param> /// <returns></returns> public BaseResult Refund(HttpContextBase context, PayParam param) { if (param.TotalFee == null || param.RefundFee == null || string.IsNullOrWhiteSpace(param.OrderNumber) || string.IsNullOrWhiteSpace(param.RefundNumber)) { return new BaseResult() { IsSuccess = false, Message = "参数错误!" }; } #region 财付通退款,已OK //var packageReq = new RequestHandler(context); //packageReq.SetKey(Key); //packageReq.SetParameter("partner", "1225604801"); //packageReq.SetParameter("out_trade_no", param.OrderNumber); //packageReq.SetParameter("out_refund_no", param.OrderNumber); //packageReq.SetParameter("total_fee", param.TotalFee.Value.ToString(CultureInfo.InvariantCulture)); //packageReq.SetParameter("refund_fee", param.RefundFee.Value.ToString(CultureInfo.InvariantCulture)); //packageReq.SetParameter("op_user_id", "1225604801"); //packageReq.SetParameter("op_user_passwd", "111111"); //packageReq.SetParameter("sign", packageReq.CreateSign()); //var httpClient = new HttpUtil(); ////httpClient.SetCharset(context.Request.ContentEncoding.BodyName); ////这里很神奇,必须要用 GB2312编码,不能通过 context.Request.ContentEncoding.BodyName获取编码 //httpClient.SetCharset("gb2312"); //httpClient.SetCertInfo(WeChatCertPath, WeChatCertPwd); //var reqXml = packageReq.GetRequestURL(); //var result = httpClient.Send(reqXml, "https://mch.tenpay.com/refundapi/gateway/refund.xml"); //var xe = XElement.Parse(result, LoadOptions.SetLineInfo); //return new BaseResult() { IsSuccess = false }; #endregion #region 微信退款 var packageReq = new RequestHandler(context); packageReq.SetKey(GetConfig.GetKey(param)); packageReq.SetParameter("appid", GetConfig.GetAppid(param)); packageReq.SetParameter("mch_id", GetConfig.GetMchId(param)); packageReq.SetParameter("nonce_str", GetNoncestr()); packageReq.SetParameter("out_trade_no", param.OrderNumber); packageReq.SetParameter("out_refund_no", param.RefundNumber); packageReq.SetParameter("total_fee", (param.TotalFee.Value).ToString(CultureInfo.InvariantCulture)); packageReq.SetParameter("refund_fee", param.RefundFee.Value.ToString(CultureInfo.InvariantCulture)); packageReq.SetParameter("op_user_id", GetConfig.GetMchId(param)); packageReq.SetParameter("sign", packageReq.CreateMd5Sign()); var reqXml = packageReq.ParseXml(); var httpClient = new HttpUtil(); httpClient.SetCharset(context.Request.ContentEncoding.BodyName); httpClient.SetCertInfo(GetConfig.GetCertPath(param), GetConfig.GetCertPwd(param)); var result = httpClient.Send(reqXml, "https://api.mch.weixin.qq.com/secapi/pay/refund"); var xe = XElement.Parse(result, LoadOptions.SetLineInfo); var returnCode = xe.GetElement("return_code").Value; //退款成功 if (returnCode.Equals("SUCCESS")) { var resultCode = xe.GetElement("result_code").Value; if (resultCode.Equals("SUCCESS")) { var outTradeNo = xe.GetElement("out_trade_no").Value; //在外面回写订单 return new BaseResult() { IsSuccess = true, Data = new Dictionary<string, string> { {"OrderNumber", outTradeNo} } }; } } var errCodeDes = xe.GetElement("err_code_des") == null ? "" : xe.GetElement("err_code_des").Value; var returnMsg = xe.GetElement("return_msg") == null ? "" : xe.GetElement("return_msg").Value; return new BaseResult() { IsSuccess = false, Message = returnMsg + errCodeDes }; #endregion }