目录
1.钉钉接口文档及SDK
- 完整发起审批流程实例的步骤:https://open.dingtalk.com/document/orgapp/tutorial-creating-or-updating-an-approval-template
- 调用本接口创建审批实例:https://open.dingtalk.com/document/isvapp/initiate-an-approval-process-without-a-process
- SDK下载:https://open.dingtalk.com/document/resourcedownload/download-server-sdk?spm=ding_open_doc.document.0.0.72fb3336BiUuCT#title-dyi-gqb-z18
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