C\#.net 위 챗 공식 계 정 인터페이스 개발

위 챗 이 오 면 올 수록 인기 가 많아 지고 위 챗 공중 플랫폼 은 새로운 인기 로 개발 되 었 다.본 고 는 C\#.net 으로 위 챗 공중 신호 인 터 페 이 스 를 개발 하고 자 한다.
위 챗 인터페이스 주소 코드:

weixin _wx = new weixin();

        string postStr = "";

        if (Request.HttpMethod.ToLower() == "post")

        {

          Stream s = System.Web.HttpContext.Current.Request.InputStream;

          byte[] b = new byte[s.Length];

          s.Read(b, 0, (int)s.Length);

          postStr = Encoding.UTF8.GetString(b);


          if (!string.IsNullOrEmpty(postStr)) //    

          {

            _wx.Handle(postStr); 

          }

        }

        else

        {

          _wx.Auth();

        }


     :

public class weixin

  {

    private string Token = "weixin_token"; //     token

     

    public void Auth()

    {

      string echoStr = System.Web.HttpContext.Current.Request.QueryString["echoStr"];

      if (CheckSignature())

      {

        if (!string.IsNullOrEmpty(echoStr))

        {

          System.Web.HttpContext.Current.Response.Write(echoStr);

          System.Web.HttpContext.Current.Response.End();

        }

      }

    }


    public void Handle(string postStr)

    {

      //     

      XmlDocument doc = new XmlDocument();

      doc.LoadXml(postStr);

      XmlElement rootElement = doc.DocumentElement;


      XmlNode MsgType = rootElement.SelectSingleNode("MsgType");


      RequestXML requestXML = new RequestXML();

      requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;

      requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;

      requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;

      requestXML.MsgType = MsgType.InnerText;


      if (requestXML.MsgType == "text")

      {

        requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;

      }

      else if (requestXML.MsgType == "location")

      {

        requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;

        requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;

        requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;

        requestXML.Label = rootElement.SelectSingleNode("Label").InnerText;

      }

      else if (requestXML.MsgType == "image")

      {

        requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;

      }


      //    

      ResponseMsg(requestXML);

    }


    /// <summary>

    ///       

    /// </summary>

    /// *  token、timestamp、nonce           

    /// *                   sha1  

    /// *               signature  ,          。

    /// <returns></returns>

    private bool CheckSignature()

    {

      string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];

      string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];

      string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];

      string[] ArrTmp = { Token, timestamp, nonce };

      Array.Sort(ArrTmp);   //    

      string tmpStr = string.Join("", ArrTmp);

      tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

      tmpStr = tmpStr.ToLower();

      if (tmpStr == signature)

      {

        return true;

      }

      else

      {

        return false;

      }

    }

    

    /// <summary>

    ///     (      )

    /// </summary>

    /// <param name="weixinXML"></param>

    private void ResponseMsg(RequestXML requestXML)

    {

      try

      {

        string resxml = "";

        mijiya mi = new mijiya(requestXML.Content,requestXML.FromUserName);


        if (requestXML.MsgType == "text")

        {

          //          ,          . 

          string _reMsg = mi.GetReMsg();

          if (mi.msgType == 1)

          {

            resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content><ArticleCount>2</ArticleCount><Articles>";

            resxml += mi.GetRePic(requestXML.FromUserName);

            resxml += "</Articles><FuncFlag>1</FuncFlag></xml>";

          }

          else

          {

            resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + _reMsg + "]]></Content><FuncFlag>1</FuncFlag></xml>";

          }

        }

        else if (requestXML.MsgType == "location")

        {

          string city = GetMapInfo(requestXML.Location_X, requestXML.Location_Y);

          if (city == "0")

          {

            resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[  ,         。   :" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

          }

          else

          {

            resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[  ,         。   :" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

          }

        }

        else if (requestXML.MsgType == "image")

        {

          resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[ ,         。   :" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

          //  10   

          //int size = 10;

          //resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content><ArticleCount>" + size + "</ArticleCount><Articles>";

          //List<string> list = new List<string>();

          ////   20        

          //for (int i = 0; i < 20; i++)

          //{

          //  list.Add("1");

          //}

          //string[] piclist = new string[] { "/Abstract_Pencil_Scribble_Background_Vector_main.jpg", "/balloon_tree.jpg", "/bloom.jpg", "/colorful_flowers.jpg", "/colorful_summer_flower.jpg", "/fall.jpg", "/fall_tree.jpg", "/growing_flowers.jpg", "/shoes_illustration.jpg", "/splashed_tree.jpg" };


          //for (int i = 0; i < size && i < list.Count; i++)

          //{

          //  resxml += "<item><Title><![CDATA[  -   ]]></Title><Description><![CDATA[    :¥300    :¥400]]></Description><PicUrl><![CDATA[" + "http://www.hougelou.com" + piclist[i] + "]]></PicUrl><Url><![CDATA[http://www.hougelou.com]]></Url></item>";

          //}

          //resxml += "</Articles><FuncFlag>1</FuncFlag></xml>";

        }

        else if (wx_tmsg.GetMsgCount(requestXML.FromUserName) == 0)

        {

          resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + mi.GetFirst() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

          

        }

        else

        {

          resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[ ,         。   :" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

          

        }

        //WriteTxt(resxml);

        System.Web.HttpContext.Current.Response.Write(resxml);


        WriteToDB(requestXML, resxml,mi.pid);

      }

      catch (Exception ex)

      {

        //WriteTxt("  :" + ex.Message + "Struck:" + ex.StackTrace.ToString());

        wx_logs.MyInsert("  :" + ex.Message + "Struck:" + ex.StackTrace.ToString());

      }

    }

     

    /// <summary>

    /// unix     datetime

    /// </summary>

    /// <param name="timeStamp"></param>

    /// <returns></returns>

    private DateTime UnixTimeToTime(string timeStamp)

    {

      DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

      long lTime = long.Parse(timeStamp + "0000000");

      TimeSpan toNow = new TimeSpan(lTime);

      return dtStart.Add(toNow);

    }


    /// <summary>

    /// datetime   unixtime

    /// </summary>

    /// <param name="time"></param>

    /// <returns></returns>

    private int ConvertDateTimeInt(System.DateTime time)

    {

      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

      return (int)(time - startTime).TotalSeconds;

    }


    /// <summary>

    ///       ,      

    /// </summary>

    /// <param name="y">  </param>

    /// <param name="x">  </param>

    /// <returns></returns>

    public string GetMapInfo(string x, string y)

    {

      try

      {

        string res = string.Empty;

        string parame = string.Empty;

        string url = "http://maps.googleapis.com/maps/api/geocode/xml";

        parame = "latlng=" + x + "," + y + "&language=zh-CN&sensor=false";// key     

        res = webRequestPost(url, parame);


        XmlDocument doc = new XmlDocument();


        doc.LoadXml(res);

        XmlElement rootElement = doc.DocumentElement;

        string Status = rootElement.SelectSingleNode("status").InnerText;

        if (Status == "OK")

        {

          //     

          XmlNodeList xmlResults = rootElement.SelectSingleNode("/GeocodeResponse").ChildNodes;

          for (int i = 0; i < xmlResults.Count; i++)

          {

            XmlNode childNode = xmlResults[i];

            if (childNode.Name == "status")

            {

              continue;

            }


            string city = "0";

            for (int w = 0; w < childNode.ChildNodes.Count; w++)

            {

              for (int q = 0; q < childNode.ChildNodes[w].ChildNodes.Count; q++)

              {

                XmlNode childeTwo = childNode.ChildNodes[w].ChildNodes[q];


                if (childeTwo.Name == "long_name")

                {

                  city = childeTwo.InnerText;

                }

                else if (childeTwo.InnerText == "locality")

                {

                  return city;

                }

              }

            }

            return city;

          }

        }

      }

      catch (Exception ex)

      {

        //WriteTxt("map  :" + ex.Message.ToString() + "Struck:" + ex.StackTrace.ToString());

        return "0";

      }


      return "0";

    }


    /// <summary>

    /// Post       

    /// </summary>

    /// <param name="url">    </param>

    /// <param name="param">  </param>

    /// <returns>string</returns>

    public string webRequestPost(string url, string param)

    {

      byte[] bs = System.Text.Encoding.UTF8.GetBytes(param);


      HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + "?" + param);

      req.Method = "Post";

      req.Timeout = 120 * 1000;

      req.ContentType = "application/x-www-form-urlencoded;";

      req.ContentLength = bs.Length;


      using (Stream reqStream = req.GetRequestStream())

      {

        reqStream.Write(bs, 0, bs.Length);

        reqStream.Flush();

      }

      using (WebResponse wr = req.GetResponse())

      {

        //                 


        Stream strm = wr.GetResponseStream();


        StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);


        string line;


        System.Text.StringBuilder sb = new System.Text.StringBuilder();


        while ((line = sr.ReadLine()) != null)

        {

          sb.Append(line + System.Environment.NewLine);

        }

        sr.Close();

        strm.Close();

        return sb.ToString();

      }

    }


    private void WriteToDB(RequestXML requestXML,string _xml,int _pid)

    {

      wx_tmsg wx = new wx_tmsg();

      wx.AddNew();

      wx.FromUserName = requestXML.FromUserName;

      wx.ToUserName = requestXML.ToUserName;

      wx.MsgType = requestXML.MsgType;

      wx.Msg = requestXML.Content;

      wx.Creatime = requestXML.CreateTime;

      wx.Location_X = requestXML.Location_X;

      wx.Location_Y = requestXML.Location_Y;

      wx.Label = requestXML.Label;

      wx.Scale = requestXML.Scale;

      wx.PicUrl = requestXML.PicUrl;

      wx.reply = _xml;

      wx.pid = _pid;

      try

      {

        wx.Update();

      }

      catch (Exception ex)

      {

        wx_logs.MyInsert(ex.Message);

        //ex.message;

      }


    }

  }


  //     

  public class RequestXML

  {

    private string toUserName="";

    /// <summary>

    ///         ,            

    /// </summary>

    public string ToUserName

    {

      get { return toUserName; }

      set { toUserName = value; }

    }


    private string fromUserName = "";

    /// <summary>

    ///         

    /// </summary>

    public string FromUserName

    {

      get { return fromUserName; }

      set { fromUserName = value; }

    }


    private string createTime = "";

    /// <summary>

    ///     

    /// </summary>

    public string CreateTime

    {

      get { return createTime; }

      set { createTime = value; }

    }


    private string msgType = "";

    /// <summary>

    ///          :location,    :text,    :image

    /// </summary>

    public string MsgType

    {

      get { return msgType; }

      set { msgType = value; }

    }


    private string content = "";

    /// <summary>

    ///     

    /// </summary>

    public string Content

    {

      get { return content; }

      set { content = value; }

    }


    private string location_X = "";

    /// <summary>

    ///       

    /// </summary>

    public string Location_X

    {

      get { return location_X; }

      set { location_X = value; }

    }


    private string location_Y = "";

    /// <summary>

    ///       

    /// </summary>

    public string Location_Y

    {

      get { return location_Y; }

      set { location_Y = value; }

    }


    private string scale = "";

    /// <summary>

    ///       

    /// </summary>

    public string Scale

    {

      get { return scale; }

      set { scale = value; }

    }


    private string label = "";

    /// <summary>

    ///       

    /// </summary>

    public string Label

    {

      get { return label; }

      set { label = value; }

    }


    private string picUrl = "";

    /// <summary>

    ///     ,      HTTP GET  

    /// </summary>

    public string PicUrl

    {

      get { return picUrl; }

      set { picUrl = value; }

    }

}
설명: 그 중에서 사용 되 는 mijiya 류 는 주로 데이터 베 이 스 를 호출 하여 키워드 와 일치 하 는 자동 답장 내용 으로 자신의 업무 상황 에 따라 작성 할 수 있 습 니 다.

좋은 웹페이지 즐겨찾기