C# Web Mvc 企业微信 回调

徐安康
2023-12-01

说明

本测试环境为.Net Core 6
其他环境自行发挥,但步骤是大差不差的。

1.安装NuGet包

using SKIT.FlurlHttpClient;
using SKIT.FlurlHttpClient.Wechat.Work;

不得不说这个包还是很好用的,又不大,也不用做多余的配置,很多东西人家已经封装好了。使用又简单。感谢大神 fudiwei
Github项目地址(开发文档):DotNetCore.SKIT.FlurlHttpClient.Wechat

2.控制器代码

 public class QywxController : Controller
    {
        [HttpGet]	//Get请求验证URL有效性
        public async Task<IActionResult> CallBackAsync(string msg_signature, string timestamp, string nonce, string echostr)
        {
        
            var options = new WechatWorkClientOptions()
            {
                CorpId = "ww3d026b63sff33261",
                AgentId = 1000001,
                AgentSecret = "oBaqtqq51YuK1n_APzY_aTpMxjVCP3sk9CdWiJ-5xT8",
                PushToken = "e5T3ibfDszKVXJpg76JjJniYJkR",	//回调接口的约定Token(必填)
                PushEncodingAESKey = "WwH1Sa6L7fesOKspGDoG51EKD3rqOTskm53osi12kJx"	//回调接口的解密密钥(必填)
            };
            var client = new WechatWorkClient(options);
            client.VerifyEventSignatureForEcho(timestamp, nonce, echostr, msg_signature, out string msg);	//验证连接有效性
            return Content(msg);	//返回解析结果
        }
        [HttpPost]	//Post请求接收业务数据
        public async Task<IActionResult> CallBackAsync(string msg_signature, string timestamp, string nonce)
        {
            var options = new WechatWorkClientOptions()
            {
                CorpId = "ww3d026b63sff33261",
                AgentId = 1000001,
                AgentSecret = "oBaqtqq51YuK1n_APzY_aTpMxjVCP3sk9CdWiJ-5xT8",
                PushToken = "e5T3ibfDszKVXJpg76JjJniYJkR",	//回调接口的约定Token(必填)
                PushEncodingAESKey = "WwH1Sa6L7fesOKspGDoG51EKD3rqOTskm53osi12kJx"	//回调接口的解密密钥(必填)
            };
            var client = new WechatWorkClient(options);
            var data = "";
            
            Request.EnableBuffering();	//net core启用缓冲 不启用的话读取不到Body内容
            							//framework 中好像没这步
            using (var reader = new StreamReader(Request.Body))
            {
                data = await reader.ReadToEndAsync();	//读取Body内容
            }
            try
            {
            	//解析Body中XML字符串
                WechatWorkEvent msg = client.DeserializeEventFromXml<TextMessageEvent>(data);
                //可以根据msg.MessageType消息类型重新再解析一遍
				//如果是image类型 可以试试 msg = client.DeserializeEventFromXml<ImageMessageEvent>(data);
                if (msg?.MessageType != null)
                {
                	//组装被动响应包的数据格式
                	//这里我组装的是文本类型的被动回复格式
                    var xml = client.SerializeEventToXml<TextMessageReply>(new TextMessageReply()
                    {
                        ToUserName = msg.ToUserName,
                        FromUserName = msg.FromUserName,
                        MessageType = msg.MessageType,
                        Content = ((TextMessageEvent)msg).Content,//这样做相当于用户发啥文本,app就回什么文本
                        CreateTimestamp = msg.CreateTimestamp
                    });
                    //做任何你想要做的事情
                    //TODO
                    return Content(xml);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return Content("OK");
        }
    }

最后

以上仅供参考,希望对你有帮助!
 类似资料: