4. .net 注册回调

回调概念

回调是开发者在钉钉开放平台注册一个HTTP接口,并订阅相关的事件,当事件发生时,钉钉会主动调用开发者注册的HTTP接口,推送对应的事件信息。比如订阅审批事件回调后,当审批状态变更时,会向注册的HTTP接口推送事件信息。

针对所有的回调事件,在收到事件推送后,务必返回包含经过加密的字符串“success”的json数据,只有返回了对应的json数据,钉钉才会判断此事件推送成功。具体返回的数据格式为:

{
  "msg_signature":"111108bb8e6dbce3c9671d6fdb69d15066227608",
  "timeStamp":"1783610513",
  "nonce":"123456",
  "encrypt":"1ojQf0NSvw2WPvW7LijxS8UvISr8pdDP+rXpPbcLGOmIBNbWetRg7IP0vdhVgkVwSoZBJeQwY2zhROsJq/HJ+q6tp1qhl9L1+ccC9ZjKs1wV5bmA9NoAWQiZ+7MpzQVq+j74rJQljdVyBdI/dGOvsnBSCxCVW0ISWX0vn9lYTuuHSoaxwCGylH9xRhYHL9bRDskBc7bO0FseHQQasdfghjkl"
}

参数说明:

参数 说明
msg_signature 消息体签名
timeStamp 时间戳
nonce 随机字符串
encrypt “success”加密字符串

成功注册回调需要关注事项

  • 时间戳和随机数取从钉钉服务器传递过来的参数,签名取新值
  • 返回的数据格式 需要继承DingTalkResponse,ErrCode按照建议写“0”

不然可能会遇到:

errcode 71009 返回文本非success

源码


        [HttpPost]
        public DingTalkCallBack callback(string signature = "", string timestamp = "", string nonce = "", [FromBody] DingTalkEventType dingTalkEvent = null)
        {
            DingTalkCrypt dingTalk = new DingTalkCrypt(DingTalkConst.TOKEN, DingTalkConst.AESKEY, MyConfigManager.GetValueByName<string>("SyncExpenseTest:corpid"));

            string l_strPlainText = "";// 解密后的数据
            dingTalk.DecryptMsg(signature, timestamp, nonce, dingTalkEvent.encrypt, ref l_strPlainText);
            //测试解密数据是否为   "EventType" : "check_url"
            //Console.WriteLine(l_strDecryptMsg);

            string l_strEncryptMsg = "";
            string l_strSignMsg = "";

            int result = dingTalk.EncryptMsg(DingTalkConst.SUCCESS, timestamp, nonce, ref l_strEncryptMsg, ref l_strSignMsg);
            if (result != 0)
            {
                Log.Error("加密过程中出现失败!");
            }

            //自己测试加密 l_strDecryptMsg  看看跟它发过来的是否一致
            //string aaa = "";
            //dingTalk.DecryptMsg(signature, timestamp,nonce,l_strPlainText, ref aaa);
            //Console.WriteLine(aaa);

            JObject jObject = JObject.Parse(l_strPlainText);
            string eventtype = jObject.GetValue("EventType")?.ToString();
            DingTalkCallBack model = new DingTalkCallBack();
            if (eventtype == "check_url")
            { //校验地址是否有效
                model.msg_signature = l_strSignMsg;
                model.encrypt = l_strEncryptMsg;
                model.timeStamp = timestamp;
                model.nonce = nonce;
                model.ErrCode = "0";
                return model;
            }

            return Handle(jObject);
        }

需要引用的DLL

我是.net core 项目,所以需要引用 dingtalk-sdk-netCore 中的topsdk-net-core.dll

http://open-dev.dingtalk.com/download/openSDK/netCore

别的可以在下面的地址中查找

https://ding-doc.dingtalk.com/doc#/faquestions/vzbp02/8DMhu

posted @ 2020-07-31 13:46  maanshancss  阅读(318)  评论(0编辑  收藏  举报