钉钉事件回调c#测试完成
做钉钉事件回调,来监测单据审批状况,钉钉给的真是一个垃圾demo,打开就报错,提交工单上去,给的也是没用的回复
折腾了好久,我终于做好了。
先说下操作流程:
网站向钉钉发出注册信息(包含相关数据,及回调的Url地址)
钉钉服务器会访问该地址,并传递相关数据,
本地网站解密数据,并返回加密的“success”
注册成功,之后可以一直接收到相关的事件信息
先注册:
protected void Button1_Click(object sender, EventArgs e) { Token _t = new Token(); string _token = _t.GetTokens(); //获取Token DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/register_call_back"); OapiCallBackRegisterCallBackRequest request = new OapiCallBackRegisterCallBackRequest(); request.Url = "http://www.xxx.com/receive.ashx"; //回调Url request.AesKey = "45skhqweass5232345IUJKWEDL5251054DSFdsuhfW2"; //随机43位字符串 request.Token = ""; //随机填写 List<string> _arr = new List<string>(); _arr.Add("bpms_task_change"); //填写要监控的信息,具体填写方法看这里 https://open-doc.dingtalk.com/microapp/serverapi2/skn8ld _arr.Add("bpms_instance_change"); request.CallBackTag =_arr; OapiCallBackRegisterCallBackResponse response = client.Execute(request, _token); string _str = response.Body; Response.Write(_str); }
[HttpPost] public JsonResult Receive(string signature, string timestamp, string nonce, PostBody body) { //接收encrypt参数 string encryptStr = body.encrypt.Replace("{\"encrypt\":\"", "").Replace("\"}",""); //注册时填写的token、aes_key、suitekey string token = ConfigurationManager.AppSettings["SuiteToken"]; //token = "123456";//钉钉测试文档中的token string aes_key = ConfigurationManager.AppSettings["Suiteaes_key"]; //aes_key = "4g5j64qlyl3zvetqxz5jiocdr586fn2zvjpa8zls3ij";//钉钉测试文档中的aes_key string suitekey = ConfigurationManager.AppSettings["DD_corpid"]; //suitekey = "suite4xxxxxxxxxxxxxxx";//钉钉测试文档中的suitekey #region 验证回调的url DingTalkCrypt dingTalk = new DingTalkCrypt(token, aes_key, suitekey); string sEchoStr = ""; int ret = dingTalk.VerifyURL(signature, timestamp, nonce, encryptStr, ref sEchoStr); #endregion #region 解密接受信息,进行事件处理 string plainText = ""; ret = dingTalk.DecryptMsg(signature, timestamp, nonce, encryptStr, ref plainText); Hashtable tb = (Hashtable)JsonConvert.DeserializeObject(plainText, typeof(Hashtable)); string eventType = tb["EventType"].ToString(); string res = "success"; switch (eventType) { case "user_modify_org"://用户信息修改,执行代码 #region 用户信息修改,执行代码 #endregion break; default: break; } timestamp = DateTime.Now.GetTimeStamp().ToString(); string encrypt = ""; string signature2 = ""; dingTalk = new DingTalkCrypt(token, aes_key, suitekey); ret = dingTalk.EncryptMsg(res, timestamp, nonce, ref encrypt, ref signature2); Hashtable jsonMap = new Hashtable { {"msg_signature", signature2}, {"encrypt", encrypt}, {"timeStamp", timestamp}, {"nonce", nonce} }; return Json(jsonMap); #endregion }