C# 钉钉企业应用鉴权

首先在前端添加以下代码

dd.config({
    agentId: '', // 必填,微应用ID
    corpId: '',//必填,企业ID
    timeStamp: '与服务器端代码一致', // 必填,生成签名的时间戳
    nonceStr: '与服务器端代码一致', // 必填,生成签名的随机串,这个位置随便填写,记得要跟后台生成签名时的随机串要一致
    signature: '服务器端生成', // 必填,签名
    type: 0,   //选填。0表示微应用的jsapi,1表示服务窗的jsapi;不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
    jsApiList: [
        'biz.telephone.call',
    ]
});
dd.ready(function () {});

获取 access_token 代码

DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest tokenRequest = new OapiGettokenRequest()
{
    Appkey = 钉钉管理后台获取,
    Appsecret = 钉钉管理后台获取,
};
tokenRequest.SetHttpMethod("GET");
OapiGettokenResponse tokenResponse = client.Execute(tokenRequest);

获取 jsapi_ticket 代码

DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
OapiGetJsapiTicketRequest jsapiTicketRequest = new OapiGetJsapiTicketRequest();
jsapiTicketRequest.SetHttpMethod("GET");
OapiGetJsapiTicketResponse jsapiTicketResponse = client.Execute(jsapiTicketRequest, access_token);

获取 noncestr

public string GetTicketRandomStr(int count)
{
    string seed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < count; i++)
    {
        int number = random.Next(0, seed.Length);
        stringBuilder.Append(seed[number]);
    }
    return stringBuilder.ToString();
}

获取 timeStamp

public long GetTimeStamp() 
{
    TimeSpan timteSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return Convert.ToInt64(timteSpan.TotalSeconds);
}

SHA1 加密方法

public static string Sha1(string text)
{
    byte[] bytes = Encoding.UTF8.GetBytes(text);
    byte[] dataList = SHA1.Create().ComputeHash(bytes);
    StringBuilder stringBuilder = new StringBuilder();
    foreach (byte data in dataList)
    {
        stringBuilder.Append(data.ToString("X2"));
    }
    return stringBuilder.ToString();
}

最后在服务器端生成前端页面需要的参数信息

string noncestr = GetTicketRandomStr(20);
long timeStamp =GetTimeStamp();
string url = HttpUtility.UrlDecode(当前页面的 URL 地址,与点开的 URL 地址完全一样);
string plainTex = "jsapi_ticket=" + jsapiTicketResponse.ticket + "&noncestr=" + noncestr + "&timestamp=" + timeStamp.ToString() + "&url=" + url;
string signature = DingTalkHelper.Sha1(plainTex).ToLower();

管理员

转载请注明出处!如果本博文或者本站对您(网站)的内容/素材构成侵权,请第一时间与本博主联系!

Press ESC to close