首页 > 编程语言 >备忘录——C#创建钉钉OA审批实例

备忘录——C#创建钉钉OA审批实例

时间:2024-08-20 11:09:39浏览次数:15  
标签:OapiProcessinstanceCreateRequest string C# request OA Token 实例 new public

目录

1.钉钉接口文档及SDK

2.钉钉中创建应用

创建应用后,得到以下信息,添加到项目文件中

注意创建应用后,在开发配置->权限管理:获取用户个人信息的权限

	<appSettings>
		<add key="appKey" value="ding3jfjmdaXXXXXXXX"/>
		<add key="appSecret" value="Xlw9Z3_XXXXXXXXXXX-XXXXXXXX-XXXXXXXXXXX"/>
		<add key="agentId" value="XXXXXXX"/>
	</appSettings>

3.代码段

3.1 获取Token

    public class TokenModel
    {
        public DateTime CreateTime { get; set; }
        public string Token { get; set; }
        public int Expires { get; set; }
    }

    public static class TokenHelper
    {
        private static string _appKey = ConfigurationManager.AppSettings["appKey"];
        private static string _appSecret = ConfigurationManager.AppSettings["appSecret"];

        /// <summary>
        /// 从钉钉接口获取Token
        /// </summary>
        /// <returns></returns>
        private  static TokenModel PostApplyToken()
        {
            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);
            string token = response.AccessToken;
            int expires = Convert.ToInt16(response.ExpiresIn);
            TokenModel tokenModel = new TokenModel() { CreateTime = DateTime.Now, Token = token, Expires = expires };
            return tokenModel;
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        public static string  GetToken()
        {
            TokenModel tokenModel = new TokenModel ();
            MemoryCache tokenCache = MemoryCache.Default;
            CacheItemPolicy policy = new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddDays(1) };

            //缓存中存在Token
            if (tokenCache.Contains("token"))
            {
                TokenModel tempTokenModel = tokenCache["token"] as TokenModel;
                bool isValidity = IsBetweenTimeSpan(DateTime.Now, tempTokenModel.CreateTime.AddSeconds(tokenModel.Expires));
                //Token过期
                if (!isValidity)
                {
                    //缓存更新最新Token
                    tokenCache.Remove("token");
                    tokenModel = PostApplyToken();
                    tokenCache = MemoryCache.Default;
                    tokenCache.Add("token", tokenModel, policy);
                }

            }
            //缓存中不存在Token
            else
            {
                //缓存更新最新Token
                tokenModel = PostApplyToken();
                tokenCache = MemoryCache.Default;
                tokenCache.Add("token", tokenModel, policy);
            }
            TokenModel tokenModel1 = tokenCache["token"] as TokenModel;
            return tokenModel.Token;
        }

        /// <summary>
        /// datetime是否在endTime之前
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        private static bool IsBetweenTimeSpan(DateTime dateTime, DateTime endTime)
        {
            int compNum2 = DateTime.Compare(dateTime, endTime);
            return compNum2 < 0;
        }

    }

3.2 通过手机号获取钉钉UserID等信息


    public static class UserInfoHelper
    {

        /// <summary>
        /// 通过手机号查询UserId
        /// </summary>
        /// <param name="mobile">形如:18860912913</param>
        /// <returns>形如:17180664937558782</returns>
        public static string GetUserIdByPhone(string mobile = "18860912913")
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.Mobile = mobile;
            OapiV2UserGetbymobileResponse rsp = client.Execute(req, TokenHelper.GetToken());
            return rsp.Result.Userid;
        }

        /// <summary>
        /// 通过userId 查询 部门ID
        /// </summary>
        /// <param name="userId">形如:17180664937558782</param>
        /// <returns>形如:481091344</returns>
        public static long GetDepByUserId(string userId)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.Userid = userId;
            req.Language = "zh_CN";
            OapiV2UserGetResponse rsp = client.Execute(req, TokenHelper.GetToken());
            return Convert.ToInt64(rsp.Result.DeptOrderList[0].DeptId);
        }
    }

3.3 创建流程审批实例

  • 注意流程模板的ID在流程设计的基础设置界面的最下面,形如:"PROC-38313682-235A-496F-9B64-0FFE9D0C18DC"
  • 注意查看文档,流程中不是所有的的控件都支持通过接口创建
  • 注意明细行的表格是一行是一个数组,之后在嵌套在一个数组中
    public class ProcInstance
    {
        private static long _agentId = Convert.ToInt64(ConfigurationManager.AppSettings["agentId"]);
        public string processCode = "流程模板ID";

        /// <summary>
        /// 创建审批实例
        /// </summary>
        /// <returns></returns>
        public string CreateProcInstance()
        {
            try
            {
                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");

                OapiProcessinstanceCreateRequest request = new OapiProcessinstanceCreateRequest();
                request.OriginatorUserId = UserInfoHelper.GetUserIdByPhone("手机号");
                request.DeptId = UserInfoHelper.GetDepByUserId(request.OriginatorUserId.ToString());
                request.AgentId = _agentId;
                request.ProcessCode = processCode;
                request.CcPosition = "START";

                OapiProcessinstanceCreateRequest.FormComponentValueVoDomain a = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                a.Name = "单行输入框";
                a.Value = "123456789";

                OapiProcessinstanceCreateRequest.FormComponentValueVoDomain b = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                b.Name = "姓名";
                b.Value = "123456789";

                #region 表格
                OapiProcessinstanceCreateRequest.FormComponentValueVoDomain c = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                OapiProcessinstanceCreateRequest.FormComponentValueVoDomain item1 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                item1.Name = "检验项目";
                item1.Value = "啊啦啦啦啦";

                OapiProcessinstanceCreateRequest.FormComponentValueVoDomain item2 = new OapiProcessinstanceCreateRequest.FormComponentValueVoDomain();
                item2.Name = "类型";
                item2.Value = "啊啦啦啦啦";

                List<OapiProcessinstanceCreateRequest.FormComponentValueVoDomain> listItem = new List<OapiProcessinstanceCreateRequest.FormComponentValueVoDomain>() { item1, item2 };

                c.Name = "表格";
                c.Value = TopUtils.ObjectToJson(new List<List<OapiProcessinstanceCreateRequest.FormComponentValueVoDomain>>() { listItem });
                #endregion

                var d = new List<OapiProcessinstanceCreateRequest.FormComponentValueVoDomain>() { a, b, c };
                request.FormComponentValues = TopUtils.ObjectToJson(d);

                var token = TokenHelper.GetToken();
                OapiProcessinstanceCreateResponse rsp = client.Execute(request, token);
                if (rsp.IsError)
                {
                    return rsp.Errmsg;
                }
                else
                {
                    return rsp.ProcessInstanceId;
                }

            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }

        /// <summary>
        /// 通过审批实例ID查询审批流程的信息
        /// </summary>
        /// <param name="instanceId">流程实例ID,形如"OpYINCq5TUaKzy0MSfoIrg04411720693785"</param>
        /// <returns></returns>
        public string GetInstanceNoById(string instanceId)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
            //审批实例process_instance_id
            req.ProcessInstanceId = instanceId;
            OapiProcessinstanceGetResponse rsp = client.Execute(req, TokenHelper.GetToken());
            return rsp.ProcessInstance.BusinessId;
        }
    }

标签:OapiProcessinstanceCreateRequest,string,C#,request,OA,Token,实例,new,public
From: https://www.cnblogs.com/shanzhiming/p/18369020

相关文章

  • lit ace markdown编辑器
    src/components/AcrMarkdown.ts:import{LitElement,css,html}from"lit";import{customElement,property,query}from"lit/decorators.js";importacefrom"ace-builds/src-min-noconflict/ace.js";import{marked}from&q......
  • WPF中的视觉树(VisualTree)和逻辑树(LogicalTree)
    可视化树和逻辑树我们先来理解一下什么是可视化树和逻辑树。通俗点来说,可视化树就是在XAML中定义的或者代码添加的元素组成的树。就像下面这样1<Grid>2<ButtonHorizontalAlignment="Center"VerticalAlignment="Center"Content="点击我"Click="Button_Click"><......
  • calico
    tar-zxvfcalico-release-v3.28.0.tgz1.修改pod网络地址vim/apps/k8s/release-v3.28.0/manifests/calico.yaml2.镜像catcalico.yaml|grepimage:cd/apps/k8s/release-v3.28.0/images/nerdctlload-icalico-cni.tarnerdctlload-icalico-node.tarnerd......
  • 工厂锭编织机成缆机绕包机挤塑机绞线机PLC数据采集车间互联网方案
     车间设备编号PLC位置设备名称设备型号PLC型号采集方案具体位置橡缆车间 TC22052 TC22053-1 65挤橡生产线 XJWY-65 西门子S7-200 X300-WG2+LY 橡缆车间一楼半橡缆车间 TC22082 TC22082-10 120挤橡生产线 XJWY-120 西门子S7-200 X300-WG1+LY 橡缆车间一楼半裸铜车间 TC21......
  • 【Abaqus】Composite Layup建模
    abaqus的3个复合材料建模途径:传统的material->section->orientation->step->job的建模方式CompositeLayup建模方式CompositeModeler(CM)插件-建模方式本文是我对compositelayup复合材料建模的理解和回顾,仅供参考。compositelayupmanager支持三种单元类型:con......
  • 【pipenv】failed to create virtual enviroment: TypeError: canonicalize_version()
    环境:python--versionPython3.9.1pip--versionpip24.2pipshowpipenv2024.0.1pipshowsetuptools73.0.0未成功的解决方案:升级各个版本:pipinstall--upgradepipsetuptoolspipinstall--upgradepipenvpipenv--clearpipenvinstall--skip-lockpipinsta......
  • lcd屏幕显示jpeg图片,其中lcd每个像素占据4字节
    //编译//arm-openwrt-linux-muslgnueabi-gcc-o17_safe_lcd_camera_test./jpeg_show.c-L./lib/-ljpeg-I./include/#include<stdio.h>#include<stdlib.h>#include<jpeglib.h>#include<setjmp.h>#include<stdint.h>#includ......
  • 【第66课】Java安全&SPEL表达式&SSTI模版注入&XXE&JDBC&MyBatis注入
    免责声明本文发布的工具和脚本,仅用作测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关内容。文中所涉......
  • 【第67课】Java安全&JNDI&RMI&LDAP&五大不安全组件&RCE执行&不出网
    免责声明本文发布的工具和脚本,仅用作测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关内容。文中所涉......
  • 【第68课】Java安全&原生反序列化&SpringBoot攻防&heapdump提取&CVE
    免责声明本文发布的工具和脚本,仅用作测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关内容。文中所涉......