ibms-dome/BackendWorkerService/Services/Implement/SendSMSService.cs
2022-10-14 16:08:54 +08:00

85 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Backend.Models;
using BackendWorkerService.Services.Interface;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
namespace BackendWorkerService.Services.Implement
{
class SendSMSService : ISendSMSService
{
private readonly ILogger<SendSMSService> logger;
private readonly IOptions<SMSConfig> _options;
private SMSConfig sms;
public SendSMSService(ILogger<SendSMSService> logger, IOptions<SMSConfig> options)
{
this.logger = logger;
sms = options.Value;
sms.Encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(sms.UserName + ":" + sms.Password));
}
public bool Send(int id, string phone, string content)
{
try
{
logger.LogError("【SendSMSService】【SMS開始寄送】[任務編號]{0}", id);
//設定傳送的Request
HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(sms.Api);
Postrequest.Method = "POST";
Postrequest.Headers.Add("Authorization", "Basic " + sms.Encoded);
Postrequest.PreAuthenticate = true;
using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream()))
{
string json = string.Format("<real val=\"{0},{1}\"/>", phone, content);
streamWriter.Write(json);
}
//設定回傳的Request
HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseString);
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc);
JObject resultVal = (JObject)JsonConvert.DeserializeObject(jsonText);
if (resultVal.ContainsKey("obj"))
{
var display_split = resultVal["obj"]["@display"].ToString().Split(' ');
var responseStatus = display_split[display_split.Length - 1];
if (responseStatus == "{ok}")
{
logger.LogInformation("【SendSMSService】【SMS寄送成功】[任務編號]{0}", id);
return true;
}
}
else
{
logger.LogError("【SendSMSService】【SMS寄送失敗】[任務編號]{0}", id);
logger.LogError("【SendSMSService】【SMS寄送失敗】[失敗內容]{0}", resultVal);
return false;
}
return false;
}
catch (Exception exception)
{
logger.LogError("【SendSMSService】【SMS寄送失敗】[任務編號]{0}", id);
logger.LogError("【SendSMSService】【SMS寄送失敗】[Exception]{0}", exception.ToString());
throw;
//return false;
}
}
}
}