企業微信自建應用開發


企業微信自建應用可以讓用戶開發自己的應用並集成在企業微信里面。我們借助於企業微信的各種接口實現各種個性化的功能,其中一個典型的功能就是要能夠接收到用戶的輸入並根據用戶的輸入推送相關的信息給用戶,本篇博客就來實現這個功能。

准備工作:

1. 在企業微信管理后台創建自建應用並開啟API接收功能

並且要對我們開發的Web API接口進行測試,如果通過會顯示如下的界面,否則提示“回調錯誤”

2. 接口測試工具

微信提供了在線接口測試工具,地址:https://open.work.weixin.qq.com/wwopen/devtool/interface/combine。

其中URL是我們部署到服務器的Web接口地址,Token、EncodingAESKey、ToUserName都可以從企業微信獲取到,每個企業自建應用都有獨立的AgentID,請仔細查看相關文檔。這個回調接口測試的是我們的WebAPI接口中的Get請求,如上圖所示返回狀態“成功”。如果提示“失敗”,可能我們開發的Web API接口有錯誤。

 

這里直接提供測試通過的.NET Core 6.0(VS2022)環境下的WebAPI完整代碼供參考。

WebAPI的Controller源碼:

[ApiController]
[Route("api/[Controller]")]
public class WXController : ControllerBase
{
    [HttpGet]
    [HttpPost]
    [Route("GetMsg")]
    public string GetMsg(string msg_signature, string timestamp, string nonce, string echostr)
    {
        if (Request.Method.ToUpper().Equals("POST"))
        {
            Request.EnableBuffering();//啟動倒帶方式 
            byte[] bytes = null;
            string strHtml = string.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                Request.Body.CopyTo(ms);
                bytes = ms.ToArray();
                strHtml = Encoding.Default.GetString(bytes);
            }

            string token = "xxx"; //自行獲取
            string encodingAESKey = "xxx"; //自行獲取
            string corpId = "xxx"; //自行獲取
            string decryptEchoString = "";

            //接收
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
            int ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, strHtml, ref decryptEchoString);

            //解析XML
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(decryptEchoString);

            XmlNode toUserNameNode = xml.SelectSingleNode("/xml/ToUserName");
            XmlNode fromUserNameNode = xml.SelectSingleNode("/xml/FromUserName");
            XmlNode createTimeNode = xml.SelectSingleNode("/xml/CreateTime");
            XmlNode msgTypeNode = xml.SelectSingleNode("/xml/MsgType");
            XmlNode contentNode = xml.SelectSingleNode("/xml/Content");
            XmlNode msgIdNode = xml.SelectSingleNode("/xml/MsgId");
            XmlNode agentIDNode = xml.SelectSingleNode("/xml/AgentID");

            string toUserName = toUserNameNode.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
            string fromUserName = fromUserNameNode.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
            string createTime = createTimeNode.InnerText.Trim();
            string msgType = msgTypeNode.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
            string content = contentNode.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
            string msgId = msgIdNode.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
            string agentID = agentIDNode.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");

            string msg = "你好!<a href=\"https://www.cnblogs.com/guwei4037\">點這里查看</a>";

            dynamic item = null;
            //文字
            item = new
            {
                touser = fromUserName,
                msgtype = "text",
                agentid = "xxx",//agentid
                text = new
                {
                    content = msg
                },
                safe = "0"
            };

            var body = Newtonsoft.Json.JsonConvert.SerializeObject(item);
            var corpsecret = "xxx"; //每個企業微信自建應用都不同

            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpsecret;
            string reval = Utils.HttpUtil.GetData(url);
            dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(reval);
            string tocken = temp["access_token"];

            //獲取token,注意有效時間,可用緩存控制
            url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", tocken);
            string responseData = Utils.HttpUtil.PostData(url, body);
            System.Collections.IDictionary obj = Newtonsoft.Json.JsonConvert.DeserializeObject(responseData) as System.Collections.IDictionary;

            //執行保存到數據庫的操作...
            return decryptEchoString;
        }

        if (Request.Method.ToUpper().Equals("GET"))
        {
            string decryptEchoString = "";
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("sToken", "sEncodingAESKey", "sCorpID");
            int ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref decryptEchoString);
            return decryptEchoString;
        }

        return "";
    }
}

里面用到的WXBizMsgCrypt和Cryptography類的源碼,企業微信官方網站里面都有下載。官方網址:https://developer.work.weixin.qq.com/document/path/95372。

HttpUtil.cs(我自己寫的,比較簡單,僅供參考):

查看代碼
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Utils
{
    public class HttpUtil
    {
        /// <summary>
        /// GET請求數據
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetData(string url)
        {
            string responseData = String.Empty;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseData = reader.ReadToEnd();
                }
            }
            return responseData;
        }

        /// <summary>
        /// POST請求數據
        /// </summary>
        /// <param name="url"></param>
        /// <param name="type">GET or POST</param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static string PostData(string url, dynamic body)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            byte[] bs = Encoding.UTF8.GetBytes(body);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bs.Length;

            string responseData = String.Empty;

            using (Stream stream = req.GetRequestStream())
            {
                stream.Write(bs, 0, bs.Length);
            }

            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseData = reader.ReadToEnd();
                }
            }

            return responseData;
        }
    }
}

除了上面的3個類,還用到Newtonsoft.Json包,可以通過Nuget獲取。

最后在Startup的ConfigureServices方法中,添加如下代碼:

查看代碼
// If using Kestrel
services.Configure<KestrelServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

// If using IIS
services.Configure<IISServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

否則會出現"Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead"的異常。

將這個Web API發布到服務器的IIS之后,用戶可以留言給這個企業微信自建應用,自建應用收到消息后會自動推送我們定義的內容給用戶。上面的代碼演示了發送文本信息,其它類型的消息可以參考企業微信文檔完成,都是類似的代碼。

 

參考資料:

1. 接收消息文檔 https://developer.work.weixin.qq.com/document/path/90238

2. 發送消息文檔 https://developer.work.weixin.qq.com/document/path/90236

3. 加解密庫下載與返回碼 https://developer.work.weixin.qq.com/document/path/95372


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM