Files
DbusSmsForward/DbusTest/Notifications/WeComApplicationNotificationSender.cs

38 lines
1.8 KiB
C#

using DbusSmsForward.Helper;
using DbusSmsForward.Services;
using DbusSmsForward.SettingModel;
using DbusSmsForward.SMSModel;
using System.Text.Json.Nodes;
namespace DbusSmsForward.Notifications;
public sealed class WeComApplicationNotificationSender(DbusSmsForwardOptions options) : NotificationSenderBase("wecom")
{
private readonly WeComApplicationConfig _config = options.Notifications.WeComApplication;
public override bool IsEnabled => _config.Enabled && !string.IsNullOrWhiteSpace(_config.CorpId) && !string.IsNullOrWhiteSpace(_config.AgentId) && !string.IsNullOrWhiteSpace(_config.ApplicationSecret);
public override async Task SendAsync(SmsContentModel sms, string body, string deviceName, CancellationToken cancellationToken)
{
string tokenUrl = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={Uri.EscapeDataString(_config.CorpId)}&corpsecret={Uri.EscapeDataString(_config.ApplicationSecret)}";
string tokenResponse = await HttpHelper.HttpGetAsync(tokenUrl, _config.SkipTlsValidation, cancellationToken);
JsonObject tokenJson = JsonNode.Parse(tokenResponse)?.AsObject() ?? throw new InvalidOperationException("Invalid WeCom token response.");
string accessToken = tokenJson["access_token"]?.ToString() ?? throw new InvalidOperationException("WeCom access_token missing.");
JsonObject payload = new()
{
["touser"] = "@all",
["msgtype"] = "text",
["agentid"] = _config.AgentId,
["text"] = new JsonObject
{
["content"] = body
},
["safe"] = 0
};
string sendUrl = $"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={Uri.EscapeDataString(accessToken)}";
await HttpHelper.PostAsync(sendUrl, payload, _config.SkipTlsValidation, cancellationToken);
}
}