前端代码:
<script type="text/javascript">
var _config = <%= GetConfig() %>;
</script>
<script type="text/javascript" src="../javascripts/zepto.min.js">
</script>
<script type="text/javascript" src="https://g.alicdn.com/ilw/ding/0.9.2/scripts/dingtalk.js" ></script>
<script type="text/javascript">
dd.config({ //实现验证
agentId : _config.agentId,
corpId : _config.corpId,
timeStamp : _config.timeStamp,
nonceStr : _config.nonceStr,
signature : _config.signature,
jsApiList : [
'runtime.info',
'biz.contact.choose',
'device.notification.confirm',
'device.notification.alert',
'device.notification.prompt',
'biz.ding.post',
'biz.util.openLink' ]
});
dd.ready(function() { //验证成功
dd.runtime.permission.requestAuthCode({ //获取code码值
corpId : _config.corpId,
onSuccess : function(info) {
alert('authcode: ' + info.code);
$.ajax({
url : 'userinfo?code=' + info.code + '&corpid=' //请求后台通过code值获得userId
+ _config.corpId,
type : 'GET',
success : function(data, status, xhr) {
var info = JSON.parse(data);
document.getElementById("userName").innerHTML = info.name;
document.getElementById("userId").innerHTML = info.userid;
},
error : function(xhr, errorType, error) {
logger.e("yinyien:" + _config.corpId);
alert(errorType + ', ' + error);
}
});
},
onFail : function(err) {
alert('fail: ' + JSON.stringify(err));
}
});
});
dd.error(function(err) { //验证失败
alert("进入到error中");
document.getElementById("userName").innerHTML = "验证出错";
alert('dd error: ' + JSON.stringify(err));
});
</script>
后台:
public partial class Enterprise_JsAPI : System.Web.UI.Page
{
public string agentId = string.Empty;
public string corpId = string.Empty;
public string timestamp = string.Empty;
public string nonceStr = string.Empty;
public string signature = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//this.GetConfig();
}
public string GetConfig()
{
agentId = Config.EAgentID;
corpId = Config.ECorpId;
string corpSecret = Config.ECorpSecret;
nonceStr = Helper.randNonce();
timestamp = Helper.timeStamp();
string url = Request.Url.ToString();
//这里重新实现
string accessToken = EnterpriseBusiness.GetToken(corpId,corpSecret).access_token;
string ticket = EnterpriseBusiness.GetTickets(accessToken);
string string1 = "ticket={0}&nonceStr={1}&timeStamp={2}&url={3}";
string1 = string.Format(string1, ticket, nonceStr, timestamp, url);
string signature = FormsAuthentication.HashPasswordForStoringInConfigFile(string1, "SHA1").ToLower();
return "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'"
+ timestamp + "',corpId:'" + corpId + "',agentId:'" + agentId + "'}";
}
}
using System;
using System.Security.Cryptography;
using System.Text;
namespace DingTalkApp.Services
{
public class DingTalkEncrypt
{
public static string GetSwcSH1(string value)
{
SHA1 algorithm = SHA1.Create();
byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
string sh1 = "";
for (int i = 0; i < data.Length; i++)
{
sh1 += data.ToString("x2").ToUpperInvariant();
}
return sh1;
}
/// <summary>
/// 创建随机字符串
/// </summary>
/// <returns></returns>
public static string createNonceStr()
{
int length = 16;
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string str = "";
Random rad = new Random();
for (int i = 0; i < length; i++)
{
str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
}
return str;
}
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>double</returns>
public static int ConvertDateTimeInt(System.DateTime time)
{
int intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = Convert.ToInt32((time - startTime).TotalSeconds);
return intResult;
}
}
}
使用时如下
[HttpGet]
public System.Collections.IEnumerable GetDtConfig(string userid, string corpid)
{
if (!string.IsNullOrEmpty(corpid) && _context.DT_CorpTbs.Where(p => p.CorpID == corpid).Count() > 0)
{
try
{
string jsurl;
var corptbid = _context.DT_CorpTbs.Where(p => p.CorpID == corpid).First();
DT_AppTb da = _context.DT_AppTbs.Where(p => p.DT_CorpTbCorpID == corpid).First();
jsurl = da.Url;
int timestamp = Services.DingTalkEncrypt.ConvertDateTimeInt(DateTime.Now);
string nonceStr = Services.DingTalkEncrypt.createNonceStr();
string[] paramArr = new String[] { "jsapi_ticket=" + _context.DT_TicketTbs.Where(p => p.DT_TokenTb.DT_CorpTbCorpID == corpid).Select(p => p.ticket).First(), "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + jsurl };
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
Array.Sort(paramArr);
// 将排序后的结果拼接成一个字符串
string content = string.Concat(paramArr[0], "&", paramArr[1], "&", paramArr[2], "&", paramArr[3]);
string signature = Services.DingTalkEncrypt.GetSwcSH1(content).ToLower();
ViewData["access_token"] = _context.DT_TokenTbs.Where(p => p.DT_CorpTbCorpID == corpid).Select(p => p.access_token).First();
ViewData["agentId"] = da.AgentID;
ViewData["corpId"] = corptbid.CorpID;
ViewData["timeStamp"] = timestamp;
ViewData["nonceStr"] = nonceStr;
ViewData["signature"] = signature;
ViewData["corpName"] = corptbid.CorpName;
ViewData["url"] = da.Url;
ViewData["dd_nav_bgcolor"] = da.Dd_nav_bgcolor;
return ViewData;
}
catch
{
return null;
}
}
else
{
return null;
}
}
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。