SoFunction
Updated on 2025-03-07

C#.net WeChat public account interface development

WeChat is becoming more and more popular, and WeChat public platform has become a new favorite. This article usesC#.netDevelop WeChat public signal interface.

WeChat interface address code:

weixin _wx = new weixin();

        string postStr = "";

        if (() == "post")

        {

          Stream s = ;

          byte[] b = new byte[];

          (b, 0, (int));

          postStr = Encoding.(b);


          if (!(postStr)) //Request processing
          {

            _wx.Handle(postStr); 

          }

        }

        else

        {

          _wx.Auth();

        }


WeChat processing category:

public class weixin

  {

    private string Token = "weixin_token"; //Switch to your own token
     

    public void Auth()

    {

      string echoStr = ["echoStr"];

      if (CheckSignature())

      {

        if (!(echoStr))

        {

          (echoStr);

          ();

        }

      }

    }


    public void Handle(string postStr)

    {

      //Encapsulate request class
      XmlDocument doc = new XmlDocument();

      (postStr);

      XmlElement rootElement = ;


      XmlNode MsgType = ("MsgType");


      RequestXML requestXML = new RequestXML();

       = ("ToUserName").InnerText;

       = ("FromUserName").InnerText;

       = ("CreateTime").InnerText;

       = ;


      if ( == "text")

      {

         = ("Content").InnerText;

      }

      else if ( == "location")

      {

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

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

         = ("Scale").InnerText;

         = ("Label").InnerText;

      }

      else if ( == "image")

      {

         = ("PicUrl").InnerText;

      }


      //Reply to the message
      ResponseMsg(requestXML);

    }


    /// <summary>

    /// Verify WeChat signature
    /// </summary>

    /// * Sort dictionary order of token, timestamp, and nonce
    /// * Splice three parameter strings into one string for sha1 encryption
    /// * The strings obtained by the developer can be compared with signature, identifying that the request comes from WeChat.
    /// <returns></returns>

    private bool CheckSignature()

    {

      string signature = ["signature"];

      string timestamp = ["timestamp"];

      string nonce = ["nonce"];

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

      (ArrTmp);   //Dictionary sort
      string tmpStr = ("", ArrTmp);

      tmpStr = (tmpStr, "SHA1");

      tmpStr = ();

      if (tmpStr == signature)

      {

        return true;

      }

      else

      {

        return false;

      }

    }

    

    /// <summary>

    /// Reply message (WeChat information returns)
    /// </summary>

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

    private void ResponseMsg(RequestXML requestXML)

    {

      try

      {

        string resxml = "";

        mijiya mi = new mijiya(,);


        if ( == "text")

        {

          //Execute a series of operations here to automatically reply to content.
          string _reMsg = ();

          if ( == 1)

          {

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

            resxml += ();

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

          }

          else

          {

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

          }

        }

        else if ( == "location")

        {

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

          if (city == "0")

          {

            resxml = "&lt;xml&gt;&lt;ToUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/ToUserName&gt;&lt;FromUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/FromUserName&gt;&lt;CreateTime&gt;" + ConvertDateTimeInt() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Okay, we know your location. You can:" + () + "]]&gt;&lt;/Content&gt;&lt;FuncFlag&gt;1&lt;/FuncFlag&gt;&lt;/xml&gt;";

          }

          else

          {

            resxml = "&lt;xml&gt;&lt;ToUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/ToUserName&gt;&lt;FromUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/FromUserName&gt;&lt;CreateTime&gt;" + ConvertDateTimeInt() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Okay, we know your location. You can:" + () + "]]&gt;&lt;/Content&gt;&lt;FuncFlag&gt;1&lt;/FuncFlag&gt;&lt;/xml&gt;";

          }

        }

        else if ( == "image")

        {

          resxml = "&lt;xml&gt;&lt;ToUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/ToUserName&gt;&lt;FromUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/FromUserName&gt;&lt;CreateTime&gt;" + ConvertDateTimeInt() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Dear, I don't understand what you mean. You can:" + () + "]]&gt;&lt;/Content&gt;&lt;FuncFlag&gt;1&lt;/FuncFlag&gt;&lt;/xml&gt;";

          //Return to less than 10
          //int size = 10;

          //resxml = "&lt;xml&gt;&lt;ToUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/ToUserName&gt;&lt;FromUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/FromUserName&gt;&lt;CreateTime&gt;" + ConvertDateTimeInt() + "&lt;/CreateTime&gt;&lt;MsgType&gt;&lt;![CDATA[news]]&gt;&lt;/MsgType&gt;&lt;Content&gt;&lt;![CDATA[]]&gt;&lt;/Content&gt;&lt;ArticleCount&gt;" + size + "&lt;/ArticleCount&gt;&lt;Articles&gt;";

          //List&lt;string&gt; list = new List&lt;string&gt;();

          //// If there are 20 queries to return results
          //for (int i = 0; i &lt; 20; i++)

          //{

          //  ("1");

          //}

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


          //for (int i = 0; i &lt; size &amp;&amp; i &lt; ; i++)

          //{

          // resxml += "<item><Title><![CDATA[Shenyang-Heilongjiang]]></Title><Description><![CDATA[New Year's Day Special Price: ¥300 Market Price: ¥400]]></Description><PicUrl><![CDATA[" + "" + piclist[i] + "]]></PicUrl><Url><![CDATA[]]></Url></item>";
          //}

          //resxml += "&lt;/Articles&gt;&lt;FuncFlag&gt;1&lt;/FuncFlag&gt;&lt;/xml&gt;";

        }

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

        {

          resxml = "&lt;xml&gt;&lt;ToUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/ToUserName&gt;&lt;FromUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/FromUserName&gt;&lt;CreateTime&gt;" + ConvertDateTimeInt() + "&lt;/CreateTime&gt;&lt;MsgType&gt;&lt;![CDATA[text]]&gt;&lt;/MsgType&gt;&lt;Content&gt;&lt;![CDATA[" + () + "]]&gt;&lt;/Content&gt;&lt;FuncFlag&gt;1&lt;/FuncFlag&gt;&lt;/xml&gt;";

          

        }

        else

        {

          resxml = "&lt;xml&gt;&lt;ToUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/ToUserName&gt;&lt;FromUserName&gt;&lt;![CDATA[" +  + "]]&gt;&lt;/FromUserName&gt;&lt;CreateTime&gt;" + ConvertDateTimeInt() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Dear, I don't understand what you mean. You can:" + () + "]]&gt;&lt;/Content&gt;&lt;FuncFlag&gt;1&lt;/FuncFlag&gt;&lt;/xml&gt;";

          

        }

        //WriteTxt(resxml);

        (resxml);


        WriteToDB(requestXML, resxml,);

      }

      catch (Exception ex)

      {

        //WriteTxt("Exception:" + + "Struck:" + ());
        wx_logs.MyInsert("abnormal:" +  + "Struck:" + ());

      }

    }

     

    /// &lt;summary&gt;

    ///Unix time converted to datetime
    /// &lt;/summary&gt;

    /// &lt;param name="timeStamp"&gt;&lt;/param&gt;

    /// &lt;returns&gt;&lt;/returns&gt;

    private DateTime UnixTimeToTime(string timeStamp)

    {

      DateTime dtStart = (new DateTime(1970, 1, 1));

      long lTime = (timeStamp + "0000000");

      TimeSpan toNow = new TimeSpan(lTime);

      return (toNow);

    }


    /// &lt;summary&gt;

    /// Convert datetime to unixtime
    /// &lt;/summary&gt;

    /// &lt;param name="time"&gt;&lt;/param&gt;

    /// &lt;returns&gt;&lt;/returns&gt;

    private int ConvertDateTimeInt( time)

    {

       startTime = (new (1970, 1, 1));

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

    }


    /// &lt;summary&gt;

    /// Call Baidu map to return coordinate information
    /// &lt;/summary&gt;

    /// <param name="y">Longitude</param>
    /// <param name="x">latitude</param>
    /// &lt;returns&gt;&lt;/returns&gt;

    public string GetMapInfo(string x, string y)

    {

      try

      {

        string res = ;

        string parame = ;

        string url = "/maps/api/geocode/xml";

        parame = "latlng=" + x + "," + y + "&amp;language=zh-CN&amp;sensor=false";//This key is for personal application
        res = webRequestPost(url, parame);


        XmlDocument doc = new XmlDocument();


        (res);

        XmlElement rootElement = ;

        string Status = ("status").InnerText;

        if (Status == "OK")

        {

          // Get only cities
          XmlNodeList xmlResults = ("/GeocodeResponse").ChildNodes;

          for (int i = 0; i &lt; ; i++)

          {

            XmlNode childNode = xmlResults[i];

            if ( == "status")

            {

              continue;

            }


            string city = "0";

            for (int w = 0; w &lt; ; w++)

            {

              for (int q = 0; q &lt; [w].; q++)

              {

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


                if ( == "long_name")

                {

                  city = ;

                }

                else if ( == "locality")

                {

                  return city;

                }

              }

            }

            return city;

          }

        }

      }

      catch (Exception ex)

      {

        //WriteTxt("map exception:" + () + "Struck:" + ());
        return "0";

      }


      return "0";

    }


    /// &lt;summary&gt;

    /// Post Submit Call Crawl
    /// &lt;/summary&gt;

    /// <param name="url">Submit address</param>
    /// <param name="param">param</param>
    /// &lt;returns&gt;string&lt;/returns&gt;

    public string webRequestPost(string url, string param)

    {

      byte[] bs = .(param);


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

       = "Post";

       = 120 * 1000;

       = "application/x-www-form-urlencoded;";

       = ;


      using (Stream reqStream = ())

      {

        (bs, 0, );

        ();

      }

      using (WebResponse wr = ())

      {

        //The received page content is processed here

        Stream strm = ();


        StreamReader sr = new StreamReader(strm, .UTF8);


        string line;


         sb = new ();


        while ((line = ()) != null)

        {

          (line + );

        }

        ();

        ();

        return ();

      }

    }


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

    {

      wx_tmsg wx = new wx_tmsg();

      ();

       = ;

       = ;

       = ;

       = ;

       = ;

      wx.Location_X = requestXML.Location_X;

      wx.Location_Y = requestXML.Location_Y;

       = ;

       = ;

       = ;

       = _xml;

       = _pid;

      try

      {

        ();

      }

      catch (Exception ex)

      {

        wx_logs.MyInsert();

        //;

      }


    }

  }


  //WeChat request class
  public class RequestXML

  {

    private string toUserName="";

    /// &lt;summary&gt;

    /// The WeChat account of the message recipient is generally the WeChat account of the public platform account
    /// &lt;/summary&gt;

    public string ToUserName

    {

      get { return toUserName; }

      set { toUserName = value; }

    }


    private string fromUserName = "";

    /// &lt;summary&gt;

    /// WeChat signal of the sender
    /// &lt;/summary&gt;

    public string FromUserName

    {

      get { return fromUserName; }

      set { fromUserName = value; }

    }


    private string createTime = "";

    /// &lt;summary&gt;

    /// Creation time
    /// &lt;/summary&gt;

    public string CreateTime

    {

      get { return createTime; }

      set { createTime = value; }

    }


    private string msgType = "";

    /// &lt;summary&gt;

    /// Information type Geographic location: location, text message: text, message type: image
    /// &lt;/summary&gt;

    public string MsgType

    {

      get { return msgType; }

      set { msgType = value; }

    }


    private string content = "";

    /// &lt;summary&gt;

    /// Information content
    /// &lt;/summary&gt;

    public string Content

    {

      get { return content; }

      set { content = value; }

    }


    private string location_X = "";

    /// &lt;summary&gt;

    /// Geographical latitude
    /// &lt;/summary&gt;

    public string Location_X

    {

      get { return location_X; }

      set { location_X = value; }

    }


    private string location_Y = "";

    /// &lt;summary&gt;

    /// Geographical location longitude
    /// &lt;/summary&gt;

    public string Location_Y

    {

      get { return location_Y; }

      set { location_Y = value; }

    }


    private string scale = "";

    /// &lt;summary&gt;

    /// Map zoom size
    /// &lt;/summary&gt;

    public string Scale

    {

      get { return scale; }

      set { scale = value; }

    }


    private string label = "";

    /// &lt;summary&gt;

    /// Geographic location information
    /// &lt;/summary&gt;

    public string Label

    {

      get { return label; }

      set { label = value; }

    }


    private string picUrl = "";

    /// &lt;summary&gt;

    /// Image link, developers can use HTTP GET to obtain
    /// &lt;/summary&gt;

    public string PicUrl

    {

      get { return picUrl; }

      set { picUrl = value; }

    }

}

Note: What are usedmijiyaClasses mainly call the database to automatically reply to keyword matching and can be written according to your own business situation.