1,获取应用access_token
传递:appkey :应用的唯一标识key,appsecret:应用的密钥
获取:accessToken:应用 access_token
请求接口:
http://***/handler/User.ashx?action=accessToken&appkey=***&appsecret=***
代码:
private void AccessToken(HttpContext context)
{
string appkey = context.Request.QueryString["appkey"];
string appsecret = context.Request.QueryString["appsecret"];
string apiVersion = "1.0";
var url= "https://openplatform.dg-work.cn/gettoken.json";
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
设置请求方法
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
WebHeaderCollection headers = httpWebRequest.Headers;
//请求发出时间
string timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.sss+08:00");
//API的nonce
DateTime time = DateTime.Now;
double intResult = 0;
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
intResult = (time - startTime).TotalMilliseconds;
var nonceTime=Math.Round(intResult, 0).ToString();
Random ran = new Random();
var nonceNumber = ran.Next(1000, 9999).ToString();
var nonce = nonceTime + nonceNumber;
//获取客户端IP和MAC地址
//获取ip
string userip = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
{
userip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
userip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (userip == null || userip == "")
{
userip = HttpContext.Current.Request.UserHostAddress;
}
//获取mac地址
string mac = null;
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (mo["IPEnabled"].ToString() == "True")
mac = mo["MacAddress"].ToString();
}
//获取签名
//1,获取签名字符串的字节数组:请求Method+'\n'+请求Header中的Timestamp+'\n'+请求Header中的Nonce+'\n'+请求的的URL(不带域名)+'\n'+请求参数
string message = "POST" + "\n" + timestamp + "\n" + nonce + '\n' + "/gettoken.json";
//2,HmacSha256(SecretKey,签名字符串字节数组)
byte[] keyByte = Encoding.UTF8.GetBytes(appsecret);
byte[] messageByte = Encoding.UTF8.GetBytes(message);
var hmacsha256 = new HMACSHA256(keyByte);
byte[] HashMessage = hmacsha256.ComputeHash(messageByte);
//3,对第二步结果使用Base64,得到签名结果
var signature64 = Convert.ToBase64String(HashMessage);
//配置请求头
headers.Add("X-Hmac-Auth-IP: "+ userip); //用户的IP地址
headers.Add("X-Hmac-Auth-MAC: " + mac); //用户的MAC地址
headers.Add("X-Hmac-Auth-Timestamp: "+ timestamp); //请求发出时间,使用UTC时间,ISO8601格式为"yyyy-MM-ddTHH:mm:ss.sss+08:00"
headers.Add("X-Hmac-Auth-Version: "+apiVersion); //API的版本号,版本号目前值为1.0
headers.Add("X-Hmac-Auth-Nonce: "+ nonce); //API的nonce,使用13位时间毫秒数 + 4位随机数
headers.Add("apiKey: "+ appkey); //应用的appkey
headers.Add("X-Hmac-Auth-Signature: "+ signature64); //请求的签名
//请求超时时间
httpWebRequest.Timeout = 20000;
//发送请求
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
//利用Stream流读取返回数据
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
//获得最终数据
string responseContent = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
}
返回成功结果:
关于更多,参照 专有钉钉开放平台->工具与资源->附录->编写更多语言SDK
2,JSAPI鉴权(JsApi 获取 access_token)
和上一个相比,其实就多了一个请求参数accessToken
传递:appkey :应用的唯一标识key;appsecret:应用的密钥;accessToken:应用accessToken
获取:accessToken:jsApi鉴权token
请求接口:
http://***/handler/User.ashx?action=jsapiToken&appkey=***&appsecret=***&access_token=***
代码:
private void JsapiToken(HttpContext context)
{
string appkey = context.Request.QueryString["appkey"];
string appsecret = context.Request.QueryString["appsecret"];
string access_token = context.Request.QueryString["access_token"];
string apiVersion = "1.0";
var url = "https://openplatform.dg-work.cn/get_jsapi_token.json";
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
设置请求方法
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
WebHeaderCollection headers = httpWebRequest.Headers;
//请求发出时间
string timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.sss+08:00");
//API的nonce
DateTime time = DateTime.Now;
double intResult = 0;
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
intResult = (time - startTime).TotalMilliseconds;
var nonceTime = Math.Round(intResult, 0).ToString();
Random ran = new Random();
var nonceNumber = ran.Next(1000, 9999).ToString();
var nonce = nonceTime + nonceNumber;
//获取客户端IP和MAC地址
//获取ip
string userip = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
{
userip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
userip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (userip == null || userip == "")
{
userip = HttpContext.Current.Request.UserHostAddress;
}
//获取mac地址
string mac = null;
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (mo["IPEnabled"].ToString() == "True")
mac = mo["MacAddress"].ToString();
}
//拼接参数
IDictionary<String, String> param = new Dictionary<String, String>();
param.Add("accessToken", access_token);
StringBuilder paramString = new StringBuilder();
bool first = true;
string charset = "utf-8";
foreach (string key in param.Keys)
{
string value = param[key];
if (!first)
{
paramString.Append("&");
}
// URL编码每个请求参数
paramString.Append(DingTalkSignatureUtil.UrlEncode(key, charset));
if (value != null)
{
paramString.Append("=").Append(DingTalkSignatureUtil.UrlEncode(value, charset));
}
first = false;
}
//使用utf-8格式组装post参数
byte[] postData = Encoding.UTF8.GetBytes(paramString.ToString());
Stream reqStream = null;
reqStream = httpWebRequest.GetRequestStream();
//参数写入请求数据的 Stream 对象
reqStream.Write(postData, 0, postData.Length);
//获取签名
string method = "POST";
string uri = "/get_jsapi_token.json";
//1,获取签名字符串的字节数组:请求Method+'\n'+请求Header中的Timestamp+'\n'+请求Header中的Nonce+'\n'+请求的的URL(不带域名)+'\n'+请求参数
string message = method + "\n" + timestamp + "\n" + nonce + '\n' + uri+ "\n" + paramString.ToString();
//2,HmacSha256(SecretKey,签名字符串字节数组)
byte[] keyByte = Encoding.UTF8.GetBytes(appsecret);
byte[] messageByte = Encoding.UTF8.GetBytes(message);
var hmacsha256 = new HMACSHA256(keyByte);
byte[] HashMessage = hmacsha256.ComputeHash(messageByte);
//3,对第二步结果使用Base64,得到签名结果
var signature64 = Convert.ToBase64String(HashMessage);
//配置请求头
headers.Add("X-Hmac-Auth-IP: " + userip); //用户的IP地址
headers.Add("X-Hmac-Auth-MAC: " + mac); //用户的MAC地址
headers.Add("X-Hmac-Auth-Timestamp: " + timestamp); //请求发出时间,使用UTC时间,ISO8601格式为"yyyy-MM-ddTHH:mm:ss.sss+08:00"
headers.Add("X-Hmac-Auth-Version: " + apiVersion); //API的版本号,版本号目前值为1.0
headers.Add("X-Hmac-Auth-Nonce: " + nonce); //API的nonce,使用13位时间毫秒数 + 4位随机数
headers.Add("apiKey: " + appkey); //应用的appkey
headers.Add("X-Hmac-Auth-Signature: " + signature64); //请求的签名
//请求超时时间
httpWebRequest.Timeout = 20000;
//发送请求
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
//利用Stream流读取返回数据
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
//获得最终数据
string responseContent = streamReader.ReadToEnd();
//关闭流
streamReader.Close();
httpWebResponse.Close();
//返回值
context.Response.Write(responseContent);
}
返回成功结果: