Beispiel #1
0
        /// <summary>
        /// 获取接口token
        /// </summary>
        /// <param name="type">接口类型</param>
        /// <param name="isForce">是否强刷</param>
        public static string GetAccess_token(Access_Type type = Access_Type.weixin, bool isForce = false)
        {
            string   Token = string.Empty;
            DateTime YouXRQ;
            // 读取XML文件中的数据,并显示出来 ,注意文件路径
            string       filepath = System.Web.HttpContext.Current.Server.MapPath("~/config/APIConfig.xml");
            StreamReader str      = new StreamReader(filepath, System.Text.Encoding.UTF8);
            XmlDocument  xml      = new XmlDocument();

            xml.Load(str);
            str.Close();
            str.Dispose();
            Token  = xml.SelectSingleNode("xml").SelectSingleNode(type.ToString() + "_Access_Token").InnerText;
            YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode(type + "_Access_YouXRQ").InnerText);

            if (isForce || DateTime.Now > YouXRQ)
            {
                DateTime     _youxrq = DateTime.Now;
                Access_token mode    = GetAccess_tokenByServer(type);
                xml.SelectSingleNode("xml").SelectSingleNode(type.ToString() + "_Access_Token").InnerText = mode.access_token;
                _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in));
                xml.SelectSingleNode("xml").SelectSingleNode(type.ToString() + "_Access_YouXRQ").InnerText = _youxrq.ToString();
                xml.Save(filepath);
                Token = mode.access_token;
            }
            return(Token);
        }
Beispiel #2
0
        /*
         * access_token是变化的,有自己的周期,官方解释为:"有效期为7200秒",这就要 求我们把获得的access_token存入一个物理文件或者Application中,请求到过期后修改这些内容,需要用的时候读出来.
         * 有些人可能想到了,如果过期我就在获得一个就好了,不用物理文件和Application也可以达到同样的效果,但是需要注意了微信平台对每天获得
         * access_token的次数也作了限制,一个用户出发多次,如果用户多,那肯定就超出了。所以我们还是按照以上的思路实现这些功能:
         * 在此之前我们已经了解了获得access_token的方法(连接),现在只需要保证它的随时更新就好了.
         */

        /// <summary>
        /// 从服务器获取access_token
        /// </summary>
        private static Access_token GetAccess_tokenByServer(Access_Type type = Access_Type.weixin)
        {
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(true);
            string       strUrl         = "";

            switch (type)
            {
            case Access_Type.weixin:
                //strUrl = "https://api.vdian.com/token?grant_type=client_credential&appkey=" + masterSettings.WeixinAppId + "&secret=" + masterSettings.WeixinAppSecret;
                strUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", masterSettings.WeixinAppId, masterSettings.WeixinAppSecret);
                break;

            case Access_Type.weidian:
                //strUrl = "https://api.vdian.com/token?grant_type=client_credential&appkey=" + masterSettings.WeiDianAppId + "&secret=" + masterSettings.WeixinAppSecret;
                break;
            }

            Access_token   mode = new Access_token();
            HttpWebRequest req  = (HttpWebRequest)HttpWebRequest.Create(strUrl);

            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
                StreamReader    reader     = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string          content    = reader.ReadToEnd();
                //在这里对Access_token 赋值
                //Access_token token = new Access_token();
                //token = JsonHelper.ParseFromJson<Access_token>(content);
                //token = JsonConvert.DeserializeObject<Access_token>(content);
                JObject obj2 = JsonConvert.DeserializeObject(content) as JObject;

                if (obj2 != null && obj2.ToString().Contains("result"))
                {
                    obj2 = JsonConvert.DeserializeObject(obj2["result"].ToString()) as JObject;
                    mode.access_token = obj2["access_token"].ToString();
                    mode.expires_in   = obj2["expire_in"].ToString();
                }
                else if (obj2 != null && type == Access_Type.weixin)
                {
                    obj2 = JsonConvert.DeserializeObject(obj2.ToString()) as JObject;
                    mode.access_token = obj2["access_token"].ToString();
                    mode.expires_in   = obj2["expires_in"].ToString();
                }
            }
            return(mode);
        }
Beispiel #3
0
        /// <summary>
        /// 调用微信接口获取所有门店信息
        /// </summary>
        /// <param name="context"></param>
        private void getPoiList(System.Web.HttpContext context)
        {
            context.Response.ContentType = "application/json";
            try
            {
                Thread.Sleep(1000);
                DataTable          dtPoiInfo   = WxPoiHelper.GetPoiListInfo();
                List <PoiInfoList> poiInfoList = new List <PoiInfoList>();
                if (dtPoiInfo.Rows.Count == 0)//如果没有同步,则调用微信接口重新获取
                {
                    //获取access_token
                    string token = Access_token.GetAccess_token(Access_token.Access_Type.weixin, true);
                    //门店列表接口提交url
                    string url = "https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" + token;
                    //提交json串,门店列表索引开始:begin,门店列表返回数量限制:limit
                    string json = @"{""begin"":0,""limit"":10}";
                    //调用post提交方法
                    string strPOIList = new Hishop.Weixin.MP.Util.WebUtils().DoPost(url, json);
                    //将传回的json字符串转换为json对象
                    JObject obj3 = JsonConvert.DeserializeObject(strPOIList) as JObject;
                    //将json对象转换为实体类对象
                    poiInfoList = JsonHelper.JsonToList <PoiInfoList>(obj3["business_list"].ToString());

                    //同步微信门店信息
                    if (WxPoiHelper.SyncPoiListInfo(poiInfoList))
                    {
                        dtPoiInfo = WxPoiHelper.GetPoiListInfo();
                    }
                }


                //获取所有门店的坐标
                string offset = string.Empty;
                foreach (DataRow row in dtPoiInfo.Rows)
                {
                    offset += row["longitude"] + "," + row["latitude"] + ";";//增加精度纬度
                }
                offset = offset.TrimEnd(';');
                //将门店坐标放入数组
                string[] offsetList = offset.Split(';');
                /****************根据配送范围将门店的坐标循环匹配用户当前的坐标,误差范围:1公里*******************/
                //允许的误差值(配送范围)
                double range = Convert.ToDouble(context.Request["range"]);
                //获取用户的坐标
                double userLongtitude = Convert.ToDouble(context.Request["userLontitude"]);
                double userLatitude   = Convert.ToDouble(context.Request["userLatitude"]);
                //循环判断获取距离,得到配送范围内的门店poi_id
                List <string> poi_id            = new List <string>();
                List <double> poi_user_distance = new List <double>();
                for (int i = 0; i < offsetList.Length; i++)
                {
                    string[] oa       = offsetList[i].Split(',');//获取门店经度,纬度
                    double   distance = GetDistance(userLatitude, userLongtitude, Convert.ToDouble(oa[1]), Convert.ToDouble(oa[0]));
                    if (distance <= range)
                    {
                        poi_id.Add(dtPoiInfo.Rows[i]["poi_id"].ToString());
                        poi_user_distance.Add(distance);
                    }
                }
                bool   isUserInRange = false;
                string matchIds      = "";
                string matchDistance = "";
                if (poi_id.Count > 0)//如果有配送范围内的用户,则返回第一个匹配到的门店后台id
                {
                    for (int i = 0; i < poi_id.Count; i++)
                    {
                        DataTable dtSender = WxPoiHelper.GetSenderByPoiId(poi_id[i]);
                        foreach (DataRow row in dtSender.Rows)
                        {
                            if (row["clientUserId"].ToString() != "")
                            {
                                matchIds      += row["clientUserId"] + ",";
                                matchDistance += poi_user_distance[i] + ",";
                            }
                        }
                    }
                    isUserInRange = true;
                    //如果匹配到的微信门店还没有绑定至后台账号,给出提示
                    if (matchIds.Length == 0)
                    {
                        context.Response.Write("{\"success\":false,\"errMsg\":\"匹配到了未绑定的门店,或者门店还未通过审核!\"}");
                        return;
                    }
                    //根据门店id匹配到对应的子账号id:sender
                    matchDistance = matchDistance.TrimEnd(',');
                    matchIds      = matchIds.TrimEnd(',');
                    //string[] sender = matchId.Split(',');
                    //string[] clientUserId = matchId.Split(',');

                    /*
                     * //将匹配到的所有门店以门店名字进行展示 (目前更换为街道名)
                     * DataTable dtStoreName = WxPoiHelper.GetStoreName(matchIds);
                     * string storeNameBtns = "";
                     * foreach (DataRow row in dtStoreName.Rows)
                     * {
                     *  storeNameBtns += "<span role='btnStreet' distributorId='" + row["userid"].ToString() + "'>" + row["storeName"].ToString() + "</span>";
                     * }
                     */
                    //将匹配到的所有街道以街道名字进行展示
                    DataTable dtStreetName   = WxPoiHelper.GetStoreStreets(matchIds);
                    string    streetNameBtns = "";
                    foreach (DataRow row in dtStreetName.Rows)
                    {
                        streetNameBtns += "<span role='btnStreet' la='" + row["latitude"] + "' lo='" + row["longitude"] + "'  distributorId='" + row["distributorid"].ToString() + "'>" + row["regionName"].ToString() + "</span>";
                    }


                    context.Response.Write("{\"success\":true,\"isUserInRange\":\"" + isUserInRange + "\",\"distributorId\":\"" + streetNameBtns + "\"}");
                }

                else
                {
                    context.Response.Write("{\"success\":true,\"isUserInRange\":\"" + isUserInRange + "\"}");
                }

                /*
                 * //调试
                 * string[] la0 = offsetList[0].Split(',');
                 * double distance = GetDistance(userLatitude,userLongtitude,Convert.ToDouble(la0[1]),Convert.ToDouble(la0[0]));
                 * context.Response.Write("{\"success\":true,\"userLo\":" + userLongtitude + ",\"userLa\":" + userLatitude + ",\"poiLA\":\"" + offsetList[0] + "\",\"distance\":"+distance+"}");
                 */
            }
            catch (Exception ex)
            {
                context.Response.Write("{\"success\":false,\"errMsg\":\"" + ex.Message + "\"}");
            }
        }