You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.1 KiB
62 lines
2.1 KiB
using BBWYB.Common.Extensions;
|
|
using BBWYB.Common.Http;
|
|
using BBWYB.Common.Models;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace BBWYB.Server.Business
|
|
{
|
|
public class DingDingBusiness : IDenpendency
|
|
{
|
|
private RestApiService restApiService;
|
|
|
|
public DingDingBusiness(RestApiService restApiService)
|
|
{
|
|
this.restApiService = restApiService;
|
|
}
|
|
|
|
public void SendDingDingBotMessage(string secret, string webHook, string content)
|
|
{
|
|
var timestamp = DateTime.Now.DateTimeToStamp();
|
|
var stringToSign = timestamp + "\n" + secret;
|
|
var sign = EncryptWithSHA256(stringToSign, secret);
|
|
var url = $"{webHook}×tamp={timestamp}&sign={sign}";
|
|
var result = restApiService.SendRequest(url, string.Empty, new
|
|
{
|
|
msgtype = "text",
|
|
text = new
|
|
{
|
|
content = content
|
|
}
|
|
}, null, HttpMethod.Post);
|
|
if (result.StatusCode != System.Net.HttpStatusCode.OK)
|
|
throw new Exception($"发送钉钉机器人消息失败 {result.Content}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Base64 SHA256
|
|
/// </summary>
|
|
/// <param name="data">待加密数据</param>
|
|
/// <param name="secret">密钥</param>
|
|
/// <returns></returns>
|
|
private string EncryptWithSHA256(string data, string secret)
|
|
{
|
|
secret = secret ?? "";
|
|
|
|
// 1、string 转换成 utf-8 的byte[]
|
|
var encoding = Encoding.UTF8;
|
|
byte[] keyByte = encoding.GetBytes(secret);
|
|
byte[] dataBytes = encoding.GetBytes(data);
|
|
|
|
// 2、 HMACSHA256加密
|
|
using (var hmac256 = new HMACSHA256(keyByte))
|
|
{
|
|
byte[] hashData = hmac256.ComputeHash(dataBytes);
|
|
// 3、转换成base64
|
|
var base64Str = Convert.ToBase64String(hashData);
|
|
// 4、urlEncode编码
|
|
return System.Web.HttpUtility.UrlEncode(base64Str, Encoding.UTF8);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|