Sharing code examples for WeChat development to reply to user messages

黄舟
Release: 2017-04-18 10:10:49
Original
1398 people have browsed it

The company’s WeChat was developed some time ago

Here is a summary of knowledge and sharing of experience, hoping to learn together. . . . .

I feel like it would be best to write a series later. . . .

Enterprise requirements:

Send a message to the designated enterprise user : Such as Attendance information, corporate notifications, personal information push, etc.,

/// </summary>
        /// <param name="UserID">要发送的人ID</param>
        /// <param name="StrMessg">消息</param>
        private void SendMessage(string UserID, string StrMessg)
        {
            Como.LogUtil.WriteLog("回复用户" + UserID + "消息");
            string Access_Token = Como.GetAccessToken.GetAccess_token();
            if (Access_Token == "")
                Como.LogUtil.WriteException("SendMessage 未能成功加载Access_Token");
            string Text = @"{
   ""touser"":";
            Text += &#39;"&#39; + UserID + &#39;"&#39;;
            Text += "," + &#39;"&#39; + @"msgtype"": ""text"", 
           ""agentid"": ""5"", 
            ""text"": {
           ""content"":";
            Text += &#39;"&#39; + StrMessg + &#39;"&#39;;
            Text += @"}, 
    ""safe"": ""0""
}";
            ;
            string url = String.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", Access_Token);
            string strResult = Como.Tools.GetPage(url, Text);

            JArray ja = (JArray)JsonConvert.DeserializeObject("[" + strResult + "]");
            string Error = "";
            try
            {
                if (strResult.Contains("errcode"))
                {
                    Error = ja[0]["errcode"].ToString();
                }
            }
            catch (Exception ex)
            {
                Como.LogUtil.WriteException("获取strResult,未获取到错误信息" + ex.Message.ToString());
            }
            string errcode = ja[0]["errcode"].ToString();
            string errmsg = ja[0]["errmsg"].ToString();
            if (errcode == "0" && errmsg == "ok")
            {
                Como.LogUtil.WriteLog("回复成功!");
            }
            else
            {
                Como.LogUtil.WriteLog("回复失败!");
                Como.LogUtil.WriteException("回复失败:SendMessage:" + strResult); 
            }
        }
Copy after login
/// <summary>
        /// 根据请求地址 和数据返回请求结果
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string GetPage(string posturl, string postData)
        {

            Stream outstream = null;

            Stream instream = null;

            StreamReader sr = null;

            HttpWebResponse response = null;

            HttpWebRequest request = null;

            Encoding encoding = Encoding.UTF8;

            byte[] data = encoding.GetBytes(postData);

            // 准备请求...

            try
            {

                // 设置参数

                request = WebRequest.Create(posturl) as HttpWebRequest;

                CookieContainer cookieContainer = new CookieContainer();

                request.CookieContainer = cookieContainer;

                request.AllowAutoRedirect = true;

                request.Method = "POST";

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

                request.ContentLength = data.Length;

                outstream = request.GetRequestStream();

                outstream.Write(data, 0, data.Length);

                outstream.Close();

                //发送请求并获取相应回应数据

                response = request.GetResponse() as HttpWebResponse;

                //直到request.GetResponse()程序才开始向目标网页发送Post请求

                instream = response.GetResponseStream();

                sr = new StreamReader(instream, encoding);

                //返回结果网页(html)代码

                string content = sr.ReadToEnd();

                string err = string.Empty;

                return content;

            }

            catch (Exception ex)
            {

                string err = ex.Message;
                Como.LogUtil.WriteException("Tools GetPage 异常为:"+err.ToString());
                return string.Empty;

            }

        }
Copy after login

Parameter

Reference Detailed explanation:

1.Como.GetAccessToken.GetAccess_token() //Get Access_token

2.GetPage //Return to the page

Request information Result

Based on the above, send the key code:

The following is: Example picture after success:

Sharing code examples for WeChat development to reply to user messages

The above is the detailed content of Sharing code examples for WeChat development to reply to user messages. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!