using BBWY.Common.Extensions; using BBWY.Common.Http; using BBWY.Common.Models; using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Cryptography; using System.Text; using Yitter.IdGenerator; namespace BBWY.Server.Business { public class DingDingBusiness : BaseBusiness, IDenpendency { private RestApiService restApiService; public DingDingBusiness(IFreeSql fsql, NLogManager nLogManager, IIdGenerator idGenerator, RestApiService restApiService, IEnumerable platformSDKBusinessList) : base(fsql, nLogManager, idGenerator, platformSDKBusinessList) { 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}"); } /// /// Base64 SHA256 /// /// 待加密数据 /// 密钥 /// 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); } } } }