/// <summary> /// 发送消息 /// </summary> public void SendMsg() { /* *发送信息,需要注意的是它可以共用一个client, * 但是在一定的时间段内是不能发送同样的信息内容的 */ var bodies = new List <string>(); if (_list != null && _list.Count > 0) { string token = base.AccessToken; //实例化dingtalk对象 var client = new DefaultDingTalkClient(API); if (!_isQueue) { var rsp = client.Execute(_list.First(), token); bodies.Add(rsp.Body); } else { foreach (var item in _list) { var rsp = client.Execute(item, token); bodies.Add(rsp.Body); } } } this._body = bodies; }
/// <summary> /// 发送审批请求 /// </summary> /// <param name="items"></param> /// <returns></returns> public string SendApprove(List <ApproveItem> items) { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create"); OapiProcessinstanceCreateRequest request = new OapiProcessinstanceCreateRequest(); request.AgentId = long.Parse(_oper.AgentID); request.ProcessCode = ProcessCode; List <OapiProcessinstanceCreateRequest.FormComponentValueVoDomain> formComponentValues = new List <OapiProcessinstanceCreateRequest.FormComponentValueVoDomain>(); items.ForEach(p => { OapiProcessinstanceCreateRequest.FormComponentValueVoDomain vo = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain(); vo.Name = p.Name; vo.Value = p.Value; vo.ExtValue = p.ExtValue; formComponentValues.Add(vo); }); request.FormComponentValues_ = formComponentValues; request.OriginatorUserId = User.DdId; request.DeptId = JsonHelper.JsonToList <long>(User.DeptId).First(); OapiProcessinstanceCreateResponse response = client.Execute(request, _oper.AccessToken); if (response.Errcode == 0) { return(response.ProcessInstanceId); } return(""); }
public static void SetAccessToken(CacheItemRemovedReason reason) { //企业内部开发 var accessToken = HttpRuntime.Cache.Get("Dingtalk_AccessToken"); if (accessToken == null) { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); OapiGettokenRequest request = new OapiGettokenRequest(); request.Appkey = Allocation.Appkey; request.Appsecret = Allocation.Appsecret; request.SetHttpMethod("GET"); OapiGettokenResponse response = client.Execute(request); HttpRuntime.Cache.Insert("Dingtalk_AccessToken", response.AccessToken, null, DateTime.Now.AddSeconds(3600), Cache.NoSlidingExpiration); } //定制服务商 //var accessToken = HttpRuntime.Cache.Get("Dingtalk_AccessToken"); //if (accessToken == null) //{ // DefaultDingTalkClient client = new DefaultDingTalkClient(Config.ServerUrl); // OapiServiceGetCorpTokenRequest req = new OapiServiceGetCorpTokenRequest(); // req.AuthCorpid = "ding0f2ae4da768e493235c2f4657eb6378f"; // OapiServiceGetCorpTokenResponse execute = client.Execute(req, "suitev6ajx5rbjrfqph0m", "y26DwWRab7il6nEe_oE9ib0xjwzPsG83KWyZBuS2ONVxTHZlk1spWyyec27m-Avw", Config.SuiteTicket); // Access_Token access_Token = JsonConvert.DeserializeObject<Access_Token>(execute.Body); // HttpRuntime.Cache.Insert("Dingtalk_AccessToken", access_Token.access_token, null, DateTime.Now.AddSeconds(3600), Cache.NoSlidingExpiration); //} }
protected override AuthUser GetUserInfo(AuthToken authToken) { var client = new DefaultDingTalkClient(source.UserInfo()); OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest(); req.TmpAuthCode = authToken.AccessCode; OapiSnsGetuserinfoBycodeResponse response = client.Execute(req, config.ClientId, config.ClientSecret); if (response.IsError) { throw new Exception(response.Errmsg); } var userObj = response.UserInfo; authToken.OpenId = userObj.Openid; authToken.UnionId = userObj.Unionid; var authUser = new AuthUser(); authUser.Uuid = userObj.Unionid; authUser.Username = userObj.Nick; authUser.Nickname = userObj.Nick; authUser.Gender = AuthUserGender.Unknown; authUser.Token = authToken; authUser.Source = source.GetName(); authUser.OriginalUser = response; authUser.OriginalUserStr = JsonConvert.SerializeObject(response); return(authUser); }
/// <summary> /// 批量获取审批实例id /// </summary> /// <param name="accessToken">accessToken</param> /// <param name="processCode">审批流的唯一码</param> /// <param name="useridlist">发起人用户id列表</param> /// <param name="starttime">查询开始时间</param> /// <returns></returns> public static List <string> GetListIds(string accessToken, string processCode, string useridlist, DateTime starttime) { try { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/listids"); OapiProcessinstanceListidsRequest request = new OapiProcessinstanceListidsRequest(); request.ProcessCode = processCode; request.StartTime = DingTalkUtils.DateTimeToTimeStamp(starttime); //开始时间。Unix时间戳 request.EndTime = DingTalkUtils.DateTimeToTimeStamp(DateTime.Now); //结束时间,默认取当前时间。Unix时间戳 request.Size = 10L; //分页参数,每页大小,最多传10,默认值:10 request.Cursor = 0L; //分页查询的游标,最开始传0,后续传返回参数中的next_cursor值,默认值:0 request.UseridList = useridlist; //发起人用户id列表,用逗号分隔,最大列表长度:10 OapiProcessinstanceListidsResponse response = client.Execute(request, accessToken); if (response.Errcode == 0) { return(response.Result.List); } else { throw new Exception(response.Errcode.ToString()); } } catch (Exception ex) { throw new Exception(ex.Message); } }
//获取排班 public static void GetScheduleList(string work_date, string corpid, string corpsecret, int offset, int size) { try { GetToken(corpid, corpsecret); IDingTalkClient client = new DefaultDingTalkClient(AttendListScheduleURI, Constants.FORMAT_JSON); SmartworkAttendsListscheduleRequest req = new SmartworkAttendsListscheduleRequest { WorkDate = DateTime.Parse(work_date), Offset = offset, Size = size }; SmartworkAttendsListscheduleResponse rsp = client.Execute(req, _Token); string content = rsp.Body; byte[] outBlock = Encoding.UTF8.GetBytes(content); using (FileStream fs = new FileStream(GetDataPath(string.Format(@"ScheduleListData{0}.json", DateTime.Now.ToString("yyyyMMddHHmmssfff"))), FileMode.Create)) { fs.Write(outBlock, 0, outBlock.Length); } } catch (Exception ex) { using (FileStream fs = new FileStream(Path.Combine(ErrorFloder, "error.log"), FileMode.Append)) { Message msg = new Message(ex.Message); fs.Write(msg.bMsg, 0, msg.Length); } } }
/// <summary> /// 发送自定义机器人消息(Actioncard类型) /// </summary> /// <param name="access_token"></param> /// <param name="title"></param> /// <param name="content"></param> /// <param name="linkUrl"></param> /// <param name="picUrl"></param> /// <param name="mobiles"></param> /// <returns></returns> public static bool SendActionCardMsg(string access_token, string title, string content, string linkUrl, string picUrl, List <string> mobiles) { IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=" + access_token); OapiRobotSendRequest request = new OapiRobotSendRequest(); request.Msgtype = "actionCard"; OapiRobotSendRequest.ActioncardDomain actionCard = new OapiRobotSendRequest.ActioncardDomain(); actionCard.Title = title; actionCard.Text = content; actionCard.SingleTitle = "查看详情"; actionCard.SingleURL = linkUrl; actionCard.BtnOrientation = "1"; //0-按钮竖直排列,1-按钮横向排列 actionCard.HideAvatar = "1"; //0-正常发消息者头像,1-隐藏发消息者头像 request.ActionCard_ = actionCard; if (mobiles != null && mobiles.Count > 0) { OapiRobotSendRequest.AtDomain at = new OapiRobotSendRequest.AtDomain(); at.AtMobiles = mobiles; request.At_ = at; } OapiRobotSendResponse response = client.Execute(request); if (response.Errcode == 0) { return(true); } return(false); }
/// <summary> /// 人员删除 /// </summary> /// <returns></returns> public static OapiUserDeleteResponse DeleteUser(OapiUserDeleteRequest deptinfo) { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/delete"); OapiUserDeleteResponse response = client.Execute(deptinfo, AccessToken); return(response); }
/// <summary> ///获取所有的部门列表信息 /// </summary> /// <param name="repuestParams"></param> /// <returns></returns> public List <Department> GetAllDepIds(RequestParams repuestParams) { List <Department> depList = new List <Department>(); IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list"); OapiDepartmentListRequest request = new OapiDepartmentListRequest(); request.Id = "1";//如果不传,默认为1表示根部门id request.SetHttpMethod("GET"); OapiDepartmentListResponse response = client.Execute(request, TooUtil.GetAccessToken()); if (response.Errcode == 0 && response.Department.Count > 0) { response.Department.ForEach(u => { Department department = new Department(); department.DepId = u.Id; department.ParentId = u.Parentid; department.DepName = u.Name; department.CreateDeptGroup = u.CreateDeptGroup; department.AutoAddUser = u.AutoAddUser; depList.Add(department); }); } return(depList); }
public string GetLogin(string code) { if (!string.IsNullOrEmpty(code)) { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); OapiGettokenRequest request = new OapiGettokenRequest(); request.Appkey = "dingjl4zohfnzjnpqudc"; request.Appsecret = "38H3T-CatuPEwnZOXq5ZhDIwqDFGye4vrxc36yLVZx7pfAumOmZBN0WSgbZB-A0-"; request.SetHttpMethod("GET"); OapiGettokenResponse response = client.Execute(request); string token = response.AccessToken; client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo"); OapiUserGetuserinfoRequest request1 = new OapiUserGetuserinfoRequest(); request1.Code = code; request1.SetHttpMethod("GET"); OapiUserGetuserinfoResponse response1 = client.Execute(request1, token); String userId = response1?.Userid ?? null; client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); OapiUserGetRequest request2 = new OapiUserGetRequest(); request2.Userid = userId; request2.SetHttpMethod("GET"); OapiUserGetResponse response2 = client.Execute(request2, token); string str = JsonConvert.SerializeObject(new { response2.Jobnumber, response2.ManagerUserId, response2.Name, response2.Roles, response2.Userid }); return(response2.Body); } else { return("0"); } }
private List <UserlistDomain> PrepareDingdingUsers(OapiUserListRequest request) { var list = new List <UserlistDomain>(); var client = new DefaultDingTalkClient(_domain + "/user/list"); client.SetDisableParser(false); var accesstoken = GetAccessTokenAsync().AccessToken; request.SetHttpMethod("GET"); var res = client.Execute(request, accesstoken); if (!res.IsError) { if (res.Userlist != null) { list.AddRange(res.Userlist); } if (res.HasMore) { request.Offset += request.Size; list.AddRange(PrepareDingdingUsers(request)); } } return(list); }
/// <summary> /// 根据code获取客户ID /// </summary> /// <returns></returns> public static Result GetFailCallBackList() { Result result = new Result() { Code = 1 }; string accessToken = GetDingToken(); IDingTalkClient client = new DefaultDingTalkClient(dingUrl + "/call_back/get_call_back_failed_result"); OapiCallbackFailrecordListRequest req = new OapiCallbackFailrecordListRequest { }; req.SetHttpMethod("GET"); OapiCallbackFailrecordListResponse rsp = client.Execute(req, accessToken); if (rsp != null && rsp.Errcode == 0) { result.Obj = rsp; } else if (rsp != null && rsp.Errcode != 0) { result.Code = 0; result.Obj = rsp; result.Message = rsp.Errmsg; } else { result.Code = 0; result.Message = "获取钉钉回调失败列表有误"; } return(result); }
/// <summary> /// 获取钉钉token /// </summary> /// <returns></returns> public static string GetDingToken() { token = RedisHelper.Get("DingToken"); if (!string.IsNullOrWhiteSpace(token)) { return(token); } IDingTalkClient client = new DefaultDingTalkClient(dingUrl + "/gettoken"); OapiGettokenRequest req = new OapiGettokenRequest { Appkey = appkey, Appsecret = appsecret }; req.SetHttpMethod("GET"); OapiGettokenResponse rsp = client.Execute(req); if (rsp.Body != null) { token = rsp.AccessToken; RedisHelper.Set("DingToken", token, expireSeconds: 7200); return(token); } return(token); }
/// <summary> /// 根据code获取客户ID /// </summary> /// <returns></returns> public static Result GetDingUserIDByMobile(string Mobile) { Result result = new Result() { Code = 1 }; string accessToken = GetDingToken(); IDingTalkClient client = new DefaultDingTalkClient(dingUrl + "/user/get_by_mobile"); OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest { Mobile = Mobile }; req.SetHttpMethod("GET"); OapiUserGetByMobileResponse rsp = client.Execute(req, accessToken); if (rsp != null && rsp.Errcode == 0) { result.StrOjb = rsp.Userid; } else if (rsp != null && rsp.Errcode != 0) { result.Code = 0; result.Obj = rsp; result.Message = rsp.Errmsg; } else { result.Code = 0; result.Message = "获取钉钉客户ID有误"; } return(result); }
static int ApprovalDetails(string Id) { IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get"); OapiProcessinstanceGetRequest request = new OapiProcessinstanceGetRequest(); request.ProcessInstanceId = Id; string token = AccessToken.GetAccessToken(); OapiProcessinstanceGetResponse response = client.Execute(request, token); if (response.Errcode == 0) { if (response.ProcessInstance.Status == "COMPLETED") { return(1); } else { return(0); } } else { return(2); } }
protected void Button1_Click(object sender, EventArgs e) { //1,获取ucml端发送人信息(姓名,对应钉钉userID,部门ID) //2,获取钉钉的AccessToken string CorpId = "ding6756aeeb5450e16935c2f4657eb6378f"; string CorpSecret = "ZiSJ4vH63JBbOYmv-qoyrwRftZydIiIqV4dXdCjfFUh5UFpNrt17pVHisHcXVIHL"; string AccessToken = ""; string AccessUrl = string.Format("https://oapi.dingtalk.com/gettoken?corpid={0}&corpsecret={1}", CorpId, CorpSecret); Newtonsoft.Json.Linq.JToken json = Newtonsoft.Json.Linq.JToken.Parse(HttpSender.Sender.Get(AccessUrl)); AccessToken = json["access_token"].ToString(); /* * //3,发送信息 * DingTalk.Api.IDingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest"); * DingTalk.Api.Request.CorpMessageCorpconversationAsyncsendRequest req = new DingTalk.Api.Request.CorpMessageCorpconversationAsyncsendRequest(); * req.Msgtype = "oa";//发送消息是以oa的形式发送的,其他的还有text,image等形式 * req.AgentId = 194755687;//微应用ID * req.UseridList = "0753662464750225";//收信息的userId,这个是by公司来区分,在该公司内这是一个唯一标识符 * req.DeptIdList = "82249101";//部门ID * req.ToAllUser = false;//是否发给所有人 * req.Msgcontent = "{\"message_url\": \"http://dingtalk.com\",\"head\": {\"bgcolor\": \"FFBBBBBB\",\"text\": \"八堡船闸PC版流程提示\"},\"body\": {\"title\": \"测试文本\",\"form\": [{\"key\": \"姓名:\",\"value\": \"张三\"},{\"key\": \"爱好:\",\"value\": \"打球、听音乐\"}],\"rich\": {\"num\": \"15.6\",\"unit\": \"元\"},\"content\": \"大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本\"}}"; * DingTalk.Api.Response.CorpMessageCorpconversationAsyncsendResponse rsp = client.Execute(req, AccessToken);//发送消息 */ //查看信息发送情况 DingTalk.Api.IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/getsendresult"); OapiMessageCorpconversationGetsendresultRequest request = new OapiMessageCorpconversationGetsendresultRequest(); request.AgentId = 194755687; //request.TaskId = ""; OapiMessageCorpconversationGetsendresultResponse response = client.Execute(request, AccessToken); Label1.Text = response.ToString(); }
/// <summary> /// 部门创建 /// </summary> /// <returns></returns> public static OapiDepartmentCreateResponse CreateDep(OapiDepartmentCreateRequest deptinfo) { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/create"); OapiDepartmentCreateResponse response = client.Execute(deptinfo, AccessToken); return(response); }
/// <summary> /// 获取 access_token /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { string access_token = string.Empty; if (rad_SDK.Checked) { IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); OapiGettokenRequest req = new OapiGettokenRequest(); req.Appkey = txt_appkey.Text; req.Appsecret = txt_appsecret.Text; req.SetHttpMethod("GET"); OapiGettokenResponse rsp = client.Execute(req, access_token); var obj = JsonConvert.DeserializeObject <JObject>(rsp.Body); access_token = obj["access_token"].ToString(); } else { string url = string.Format("https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}", txt_appkey.Text, txt_appsecret.Text); var result = HttpHelper.Get(url, Encoding.UTF8); var obj = JsonConvert.DeserializeObject <JObject>(result); if (obj != null) { if (obj["errcode"].ToString().Trim() == "0") { access_token = obj["access_token"].ToString(); } else { access_token = obj["errmsg"].ToString(); } } } txt_access_token.Text = access_token; }
private static string SendDingDingMsg(RobotSetting setting, string content) { long timestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; string strSign = timestamp + "\n" + setting.Secret; string sign = string.Empty; using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(setting.Secret))) { byte[] hashmessage = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(strSign)); sign = HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage), Encoding.UTF8); } IDingTalkClient client = new DefaultDingTalkClient($"{setting.SendUrl}×tamp={timestamp}&sign={sign}"); OapiRobotSendRequest.TextDomain text = new OapiRobotSendRequest.TextDomain() { Content = content }; OapiRobotSendRequest request = new OapiRobotSendRequest() { Msgtype = "text", Text_ = text }; OapiRobotSendResponse response = client.Execute(request); return(response.Body); }
public string DingLogin(string code, string state) { //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。 OapiSnsGetuserinfoBycodeResponse response = new OapiSnsGetuserinfoBycodeResponse(); try { string qrAppId = AppConfigurtaionHelper.Configuration["DingDing:QrAppId"]; string qrAppSecret = AppConfigurtaionHelper.Configuration["DingDing:QrAppSecret"]; if (string.IsNullOrWhiteSpace(qrAppId) || string.IsNullOrWhiteSpace(qrAppSecret)) { throw new Exception("请先配置钉钉扫码登录信息!"); } DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode"); OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest(); req.TmpAuthCode = code; response = client.Execute(req, qrAppId, qrAppSecret); //获取到response后就可以进行自己的登录业务处理了 //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx //此处省略一万行代码 } catch (Exception e) { response.Errmsg = e.Message; } return(response.Body); }
/// <summary> /// 发送自定义机器人消息(FeedCard类型:公号文章列表) /// </summary> /// <param name="access_token"></param> /// <param name="title"></param> /// <param name="content"></param> /// <param name="linkUrl"></param> /// <param name="picUrl"></param> /// <param name="mobiles"></param> /// <returns></returns> public static bool SendFeedCardMsg(string access_token, string title, string content, List <FeedCard> feedcardList) { IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=" + access_token); OapiRobotSendRequest request = new OapiRobotSendRequest(); request.Msgtype = "feedCard"; OapiRobotSendRequest.FeedcardDomain feedCard = new OapiRobotSendRequest.FeedcardDomain(); List <OapiRobotSendRequest.LinksDomain> links = new List <OapiRobotSendRequest.LinksDomain>(); foreach (FeedCard card in feedcardList) { OapiRobotSendRequest.LinksDomain link = new OapiRobotSendRequest.LinksDomain(); link.Title = card.Title; link.MessageURL = card.MessageURL; link.PicURL = card.PicURL; links.Add(link); } feedCard.Links = links; OapiRobotSendResponse response = client.Execute(request); if (response.Errcode == 0) { return(true); } return(false); }
/// <summary> /// 更新一条待办事项,该待办事项在该用户的“待办事项”列表页面中消失 /// </summary> /// <param name="accessToken"></param> /// <param name="userId"></param> /// <param name="record_id"></param> /// <returns></returns> public static SendWorkRecordResult UpdateWorkRecord(string accessToken, string userId, string record_id) { SendWorkRecordResult result = new SendWorkRecordResult(); try { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long time = Convert.ToInt64(ts.TotalSeconds); IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/update"); OapiWorkrecordUpdateRequest req = new OapiWorkrecordUpdateRequest(); req.Userid = userId; req.RecordId = record_id;//待办时间。Unix时间戳,毫秒级 OapiWorkrecordUpdateResponse response = client.Execute(req, accessToken); if (response.Errcode == 0) { return(result = SendWorkRecordResult.CreateSuccessResult( response.Errcode, response.ErrMsg, response.Result )); } else { return(result = SendWorkRecordResult.CreateFailResult( response.Errcode, response.SubErrMsg )); } } catch { throw new Exception("发送出错"); } }
//获取考勤组 public static void GetAttendGroup(string corpid, string corpsecret, int offset = 0, int size = 10) { try { GetToken(corpid, corpsecret); IDingTalkClient client = new DefaultDingTalkClient(AttendSimpleGroupURI, Constants.FORMAT_JSON); SmartworkAttendsGetsimplegroupsRequest req = new SmartworkAttendsGetsimplegroupsRequest(); req.Offset = offset; req.Size = size; SmartworkAttendsGetsimplegroupsResponse rsp = client.Execute(req, _Token); string content = rsp.Body; byte[] outBlock = Encoding.UTF8.GetBytes(content); using (FileStream fs = new FileStream(GetDataPath(string.Format(@"AttendGroup{0}.json", DateTime.Now.ToString("yyyyMMddHHmmssfff"))), FileMode.Append)) { fs.Write(outBlock, 0, outBlock.Length); } } catch (Exception ex) { using (FileStream fs = new FileStream(Path.Combine(ErrorFloder, "error.log"), FileMode.Append)) { Message msg = new Message(ex.Message); fs.Write(msg.bMsg, 0, msg.Length); } } }
public JObject SendWorkRecord(string userid, long time, string title, string msgUrl, string Ltitle, string Lcontent) { var url = $"{m_host}/topapi/workrecord/add"; var client = new DefaultDingTalkClient(url); var request = new OapiWorkrecordAddRequest(); request.Userid = userid; request.CreateTime = time; request.Title = title; request.Url = msgUrl; var _list = new List <FormItemVoDomain>() { new FormItemVoDomain { Title = Ltitle, Content = Lcontent } }; request.FormItemList_ = _list; var response = client.Execute(request, access_token); var _json = JObject.Parse(response.Body); if (Convert.ToInt32(_json["errcode"].ToString()) != 0) { //LogService.AppendDebugLog(typeof(DingTalkService), $"请求地址[{url}]返回{_json.ToString()}"); } return(_json); }
public string SendOaMessage(string ApplyManIds, OATextModel oaTextModel) { IDingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest"); CorpMessageCorpconversationAsyncsendRequest req = new CorpMessageCorpconversationAsyncsendRequest(); req.Msgtype = "oa"; req.AgentId = long.Parse(DTConfig.AgentId); req.UseridList = ApplyManIds; //req.DeptIdList = "123,456"; req.ToAllUser = false; //req.Msgcontent = "{\"message_url\": \"http://dingtalk.com\",\"head\": {\"bgcolor\": \"FFBBBBBB\",\"text\": \"头部标题\"},\"body\": {\"title\": \"正文标题\",\"form\": [{\"key\": \"姓名:\",\"value\": \"张三\"},{\"key\": \"爱好:\",\"value\": \"打球、听音乐\"}],\"rich\": {\"num\": \"15.6\",\"unit\": \"元\"},\"content\": \"111大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本\",\"image\": \"@lADOADmaWMzazQKA\",\"file_count\": \"3\",\"author\": \"李四 \"}}"; req.Msgcontent = JsonConvert.SerializeObject(oaTextModel); CorpMessageCorpconversationAsyncsendResponse rsp = client.Execute(req, DDApiService.Instance.GetAccessToken()); int iResult = 0; return(JsonConvert.SerializeObject(new ErrorModel { IsError = rsp.IsError, errorCode = int.TryParse(rsp.ErrCode, out iResult) ? iResult : iResult, errorMessage = rsp.ErrMsg })); }
/// <summary> /// 企业内部通过本企业的CorpId和CorpSecret,来换取access_token /// </summary> /// <param name="corpId"></param> /// <param name="corpSecret"></param> /// <returns></returns> public static string GetAccessToken(string corpId, string corpSecret) { /* * https://oapi.dingtalk.com/gettoken?corpid={corpid}&corpsecret={corpSecret或开发授权码} * "errcode": 0, * "errmsg": "ok", * "access_token": "fw8ef8we8f76e6f7s8df8s" */ try { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); OapiGettokenRequest request = new OapiGettokenRequest(); request.Corpid = corpId; request.Corpsecret = corpSecret; request.SetHttpMethod("GET"); OapiGettokenResponse response = client.Execute(request); if (response != null && response.Errcode == 0) { return(response.AccessToken); } else { throw new Exception(response.ErrMsg); } } catch (Exception ex) { throw; } return(string.Empty); }
public User GetUserInfo(string DdId) { IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); OapiUserGetRequest request = new OapiUserGetRequest(); request.Userid = DdId; request.SetHttpMethod("GET"); OapiUserGetResponse response = client.Execute(request, DdOper.AccessToken); if (!response.IsError) { User u = new User { UserName = response.Name, DdId = response.Userid, DepartName = DdOper.GetDeptName(response.Department[0]), Avatar = response.Avatar, }; response.Department.ForEach(p => { if (u.DeptId == "") { u.DeptId = p.ToString(); u.DepartName = DdOper.GetDeptName(p); } else { u.DeptId += "," + p.ToString(); u.DepartName += "," + DdOper.GetDeptName(p); }; }); return(u); } return(null); }
/// <summary> /// 企业开发内部应用通过appkey和appsecret获取access_token /// </summary> /// <param name="corpId"></param> /// <param name="corpSecret"></param> /// <returns></returns> public static string GetAccessToken2(string appkey, string appsecret) { /* * https://oapi.dingtalk.com/gettoken?appkey=id&appsecret=secret * "errcode": 0, * "errmsg": "ok", * "access_token": "fw8ef8we8f76e6f7s8df8s" */ try { DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); OapiGettokenRequest request = new OapiGettokenRequest(); request.Appkey = appkey; request.Appsecret = appsecret; request.SetHttpMethod("GET"); OapiGettokenResponse response = client.Execute(request); if (response.Errcode == 0) { return(response.AccessToken); } } catch (Exception ex) { throw; } return(string.Empty); }
/// <summary> /// 钉钉OA模板发送推送消息 /// </summary> /// <param name="agentid">微应用Id</param> /// <param name="Userid">发送人员id-多个用,分隔</param> /// <param name="Token">token</param> /// <param name="MessageUrl">跳转url</param> /// <param name="keys">字典集合</param> public string OAMessage(long agentid, string Userid, string Token, string MessageUrl, Dictionary <string, string> keys) { Root root = new Root(); //默认头部 root.head = new Head(); //消息表体 Body body = new Body(); List <FormItem> forms = new List <FormItem>(); foreach (var item in keys) { forms.Add(new FormItem { key = item.Key, value = item.Value }); } body.form = forms; root.body = body; //跳转链接 root.message_url = MessageUrl; IDingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest"); CorpMessageCorpconversationAsyncsendRequest req = new CorpMessageCorpconversationAsyncsendRequest(); req.Msgtype = "oa"; req.AgentId = agentid; //微应用id req.UseridList = Userid; //接收者Userid列表 //req.DeptIdList = "";//接收部门列表(可不填) req.ToAllUser = false; //是否发送给企业全部用户 req.Msgcontent = JsonConvert.SerializeObject(root); CorpMessageCorpconversationAsyncsendResponse rsp = client.Execute(req, Token); return(JsonConvert.SerializeObject(rsp).ToString()); }
private DingUserinfo getDingUserInfo(string userid) { if (string.IsNullOrEmpty(userid)) { return(null); } IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); OapiUserGetRequest request = new OapiUserGetRequest(); request.Userid = userid; request.SetHttpMethod("GET"); OapiUserGetResponse response = client.Execute(request, getDingAccessToken()); // logger.LogInformation("OapiUserGetResponse:" + fastJSON.JSON.ToJSON(response)); if (response.IsError) { logger.LogError(response.Errmsg); return(null); } return(new DingUserinfo() { Userid = response.Userid, Username = response.Name, Avatar = response.Avatar, Email = response.Email, Openid = response.OpenId, Unionid = response.Unionid }); }