原来用C#开发一个企业微信(企业公众号),这么简单?

首先去微信公众平台注册企业公众号:

本篇文章学习目标:

通过本文学习到如何使用企业号开发一个。企业聊天对话机器人。

微信企业号地址

如何注册这里不再多说。

成为开发者的第一步,验证并相应服务器的数据:

  1. 创建你的企业应用:

   这时候在你企业号管理员中就能看到你创建的,企业应用了。

  

2. 添加企业应用配置:

点开一个企业应用-》 点击消息配置

点击接受消息。启用API接收。

 一顿鬼操作,到这里。咱们开始上干活:代码部分:

首先创建一个WEB 项目 ,创建 WeiXin.ashx

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;
using Tencent;

namespace WeiXinProject
{
    /// <summary>
    /// WeiXin 的摘要说明    企业号基础操作API实现: 博客地址:https://blog.csdn.net/u010919083
    /// </summary>
    public class WeiXin : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Como.LogUtil.WriteLog("========================0.WeiXin 开始服务器验证========================= ");
            string postString = string.Empty;
            if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
            {
                using (Stream stream = HttpContext.Current.Request.InputStream)
                {
                    Byte[] postBytes = new Byte[stream.Length];
                    stream.Read(postBytes, 0, (Int32)stream.Length);
                    postString = Encoding.UTF8.GetString(postBytes);
                }

                if (!string.IsNullOrEmpty(postString))
                {
                    // Execute(postString);   postString为:" + postString
                    Como.LogUtil.WriteLog("========================1.WeiXin 服务器验证========================= ");
                //    Como.LogUtil.WriteLog("postString为:" + postString);
                    JMMessage(postString);
                }
            }
            else
            {
                Auth();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary> 
        /// 成为开发者的第一步,验证并相应服务器的数据    企业号基础操作API实现: 博客地址:https://blog.csdn.net/u010919083
        /// </summary>
        private void Auth()
        {
            #region 获取关键参数
            string token = ConfigurationManager.AppSettings["CorpToken"];//从配置文件获取Token
            if (string.IsNullOrEmpty(token))
            {
                Como.LogUtil.WriteLog(string.Format("CorpToken 配置项没有配置!"));
            }
            string encodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"];//从配置文件获取EncodingAESKey
            if (string.IsNullOrEmpty(encodingAESKey))
            {
                Como.LogUtil.WriteLog(string.Format("EncodingAESKey 配置项没有配置!"));
            }
            string corpId = ConfigurationManager.AppSettings["CorpId"];//从配置文件获取corpId
            if (string.IsNullOrEmpty(corpId))
            {
                Como.LogUtil.WriteLog(string.Format("CorpId 配置项没有配置!"));
            }
            #endregion

            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];

            string decryptEchoString = "";
            if (new CorpBasicApi().CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString))
            {
                if (!string.IsNullOrEmpty(decryptEchoString))
                {
                    HttpContext.Current.Response.Write(decryptEchoString);
                    HttpContext.Current.Response.End();
                }
            }

            //

        }

        ///2.解密关注者消息 图片 文字 等。。。。
        public void   JMMessage(string PostXML)
        {
            //公众平台上开发者设置的token, corpID, EncodingAESKey
            string sToken = ConfigurationManager.AppSettings["CorpToken"];
            string sCorpID = ConfigurationManager.AppSettings["CorpId"];
            string sEncodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"];
            
            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
            string sReqMsgSig = HttpContext.Current.Request.QueryString["msg_signature"];
            string sReqTimeStamp=HttpContext.Current.Request.QueryString["timestamp"];
            string sReqNonce =HttpContext.Current.Request.QueryString["nonce"];
            string sReqData =PostXML;
            string sMsg = "";  // 解析之后的明文
            int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);
            if (ret != 0)
            {
                System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret);
                Como.LogUtil.WriteLog("ERR: Decrypt Fail, ret: " + ret);
                return;
            }
            Como.LogUtil.WriteLog("解密后:XML:" + sMsg);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sMsg);
            XmlNode root = doc.FirstChild;

            string MsgType = root["MsgType"].InnerText;
            Como.LogUtil.WriteLog("MsgType为:" + MsgType);

            string FromUserName = root["FromUserName"].InnerText;
            Como.LogUtil.WriteLog("消息人为:" + FromUserName);

            if (MsgType == "text")
            {
                string content = root["Content"].InnerText;
                Como.LogUtil.WriteLog("内容Content为:" + content);
            }
            string imgpath = "C:\\WeiXinImages\\";
            string NameImg = DateTime.Now.ToString("yyyyMMDDssff") + ".JPG";
            if (MsgType == "image")
            {
                Como.LogUtil.WriteLog("MsgType为:图片");
                try
                {
                    string PicUrl = root["PicUrl"].InnerText;
                    Como.LogUtil.WriteLog("PicUrl为:" + PicUrl);
                   
                    Como.Tools.DownloadPicture(PicUrl, imgpath + NameImg, -1);
                }
                catch (Exception ex)
                {
                    Como.LogUtil.WriteLog("PicUrl异常为:" + ex.Message.ToString());
                }
            }
            string imgpathUrl = imgpath + NameImg;
            SendMessage(FromUserName, "您好" + FromUserName + ":图片路径为:" + imgpathUrl);
        }
         
        //3. 回复用户消息
        /// </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 += '"' + UserID + '"';
            Text += "," + '"' + @"msgtype"": ""text"", 
           ""agentid"": ""3"", 
            ""text"": {
           ""content"":";
            Text += '"' + StrMessg + '"';
            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("获取access_token,未获取到错误信息" + 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("回复失败!");
            }
        }
    }


    /// <summary>
    /// 企业号基础操作API实现: 博客地址:https://blog.csdn.net/u010919083
    /// </summary>
    public class CorpBasicApi       //: ICorpBasicApi
    {
        /// <summary>
        /// 验证企业号签名
        /// </summary>
        /// <param name="token">企业号配置的Token</param>
        /// <param name="signature">签名内容</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">nonce参数</param>
        /// <param name="corpId">企业号ID标识</param>
        /// <param name="encodingAESKey">加密键</param>
        /// <param name="echostr">内容字符串</param>
        /// <param name="retEchostr">返回的字符串</param>
        /// <returns></returns>
        public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
        {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
            int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr);
            if (result != 0)
            {
                Como.LogUtil.WriteLog("ERR: VerifyURL fail, ret: " + result);
                return false;
            }

            return true;

            //ret==0表示验证成功,retEchostr参数表示明文,用户需要将retEchostr作为get请求的返回参数,返回给企业号。
            // HttpUtils.SetResponse(retEchostr);
        }
    }

}

主逻辑代码部分就这么多了。如果有需要源码的。可以关注。私信我。

下面我们看效果:发送的图片服务器已记录。并存储。 这里将文本消息处理。 回复即可做成机器人哦。

主逻辑代码部分就这么多了。如果有需要源码的。可以关注。私信我。

转载请说明出处哦。

猜你喜欢

转载自blog.csdn.net/u010919083/article/details/104828267