Browse Source

微信订阅号消息发送接口添加

develop-lawyerExampaper
liujiaqiang 2 years ago
parent
commit
4d60cd0546
  1. 1
      24Hour/24Hour.csproj
  2. 28
      24Hour/Controllers/Common/CommonController.cs
  3. 24
      24Hour/Controllers/Common/WebSocketController.cs
  4. 173
      24Hour/WechatMessagerClient.cs
  5. 6
      24Hour/appsettings.json
  6. 12
      Elight.Utility/Extensions/StringExtension.cs

1
24Hour/24Hour.csproj

@ -18,6 +18,7 @@
<PackageReference Include="Quartz" Version="3.6.3" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.83" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="System.Runtime.Caching" Version="7.0.0" />
</ItemGroup>
<ItemGroup>

28
24Hour/Controllers/Common/CommonController.cs

@ -38,10 +38,11 @@ namespace _24Hour.Controllers.Common
App_Sys_UserModel _userdata = new App_Sys_UserModel();//当前用户
private readonly List<App_Sys_UnitModel> _Unitdata;//当前用户
private readonly ILogger<LoginController> _logger;//日志
private readonly WechatMessagerClient _wechatMessagerClient;
private readonly IMapper _mapper;
DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
Result result = new Result();
public CommonController(IMapper mapper,ILogger<LoginController> logger, SqlSugarClient db, WriteSysLog logs, User user, WebSocketController SocketCon)
public CommonController(IMapper mapper, ILogger<LoginController> logger, SqlSugarClient db, WriteSysLog logs, User user, WebSocketController SocketCon, WechatMessagerClient wechatMessagerClient)
{
_logger = logger;
_db = db;
@ -50,6 +51,7 @@ namespace _24Hour.Controllers.Common
_SocketCon = SocketCon;
_Unitdata = _db.Queryable<App_Sys_UnitModel>().Where(q => q.IsDelete == 0).ToList();
_mapper = mapper;
_wechatMessagerClient = wechatMessagerClient;
}
#endregion
@ -1334,12 +1336,34 @@ namespace _24Hour.Controllers.Common
Lawyerbol.FirstOrDefault().receptionuser = dto.userId;
Lawyerbol.FirstOrDefault().receptionusername = dto.username;
}
var userdata = await _db.Queryable<App_Sys_UserModel>()
.Where(q => q.Id == Lawyerbol.FirstOrDefault().createuserId).ToArrayAsync();
_db.BeginTran();
var num = await _db.Updateable(Lawyerbol.FirstOrDefault()).UpdateColumns(it => new { it.receptionuser, it.receptionusername, it.acceptancetime, it.reason, it.state, it.operatorId, it.operatorName }).ExecuteCommandAsync();
_db.CommitTran();
if (num > 0)
{
_SocketCon.system(dto.userId);
var Lawyerboldata = Lawyerbol.FirstOrDefault();
//获取单位信息
var unitname = _Unitdata.FirstOrDefault(q => q.unitCode == Lawyerboldata.unitCode)?.unitname;
await _SocketCon.system(dto.userId);
if (dto.Type == 1)
{
if (Convert.ToInt32(dto.state) == 1)
{
//判单预约人是否有微信openId
if (!string.IsNullOrEmpty(userdata.FirstOrDefault()?.wechatId))
//发送晨成功订阅号消息
_wechatMessagerClient.wxts(userdata.FirstOrDefault()?.wechatId, Lawyerboldata?.operatorName, unitname, Lawyerboldata?.receptiontime, Lawyerboldata?.objectstr +"-"+ Lawyerboldata?.matter, Lawyerboldata?.reason);
}
else
{
//判单预约人是否有微信openId
if (!string.IsNullOrEmpty(userdata.FirstOrDefault()?.wechatId))
//发送拒绝订阅号消息
_wechatMessagerClient.sbwxts(userdata.FirstOrDefault()?.wechatId, Lawyerboldata?.operatorName, unitname, Lawyerboldata?.receptiontime, Lawyerboldata?.matter);
}
}
result.IsSucceed = true;
result.result = "修改成功";
}

24
24Hour/Controllers/Common/WebSocketController.cs

@ -28,17 +28,19 @@ namespace _24Hour.Controllers.Common
private readonly ILogger<LoginController> _logger;//日志
private readonly IConfiguration _configuration;
private static object obj = new object();
private readonly WechatMessagerClient _wechatMessagerClient;
Result result = new Result();
private static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();//用户连接池
private static Dictionary<string, Addressda> meeting_pool = new Dictionary<string, Addressda>();//会议连接池
private static Dictionary<string, string> userzx = new Dictionary<string, string>();//检察官在线池
//private static Dictionary<string, List<MessageInfo>> MESSAGE_POOL = new Dictionary<string, List<MessageInfo>>();//离线消息池
public WebSocketController(ILogger<LoginController> logger, SqlSugarClient db, User userdata, IConfiguration configuration)
public WebSocketController(ILogger<LoginController> logger, SqlSugarClient db, User userdata, WechatMessagerClient wechatMessagerClient, IConfiguration configuration)
{
_logger = logger;
_db = db;
_userdata = userdata.Userdata();
_configuration = configuration;
_wechatMessagerClient = wechatMessagerClient;
}
[HttpGet("/ws")]
public async Task WebSocketServer()
@ -543,6 +545,26 @@ namespace _24Hour.Controllers.Common
}
return true;
}
///// <summary>
///// 微信推送
///// </summary>
///// <param name="Id"></param>
///// <returns></returns>
//[HttpGet]
//[Route("wxts")]
//public async Task<bool> wxts()
//{
// try
// {
// _wechatMessagerClient.wxts();
// }
// catch (Exception)
// {
// }
// return true;
//}
}
/// <summary>

173
24Hour/WechatMessagerClient.cs

@ -2,7 +2,12 @@
using com.sun.xml.@internal.xsom;
using Elight.Utility;
using Elight.Utility.Code;
using Elight.Utility.Extensions;
using java.lang.annotation;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.Caching;
namespace _24Hour
{
@ -10,23 +15,34 @@ namespace _24Hour
public class WechatMessagerClient
{
private readonly HttpClient httpCliet;
public WechatMessagerClient(HttpClient _httpCliet)
// 实例化MemoryCache对象
MemoryCache cache = MemoryCache.Default;
private readonly IConfiguration _configuration;
/// <summary>
/// 小程序AppID
/// </summary>
private string appid = "wx48108a0c98a3dab0";
/// <summary>
/// 小程序AppID
/// </summary>
private string secret = "wx48108a0c98a3dab0";
/// <summary>
/// 小程序secretID
/// </summary>
private string secid = "e752e4fba67526eca21313a18c96a58f";
public WechatMessagerClient(HttpClient _httpCliet, IConfiguration configuration)
{
this.httpCliet = _httpCliet;
httpCliet.DefaultRequestHeaders.Add("Accept", "application/json");
httpCliet.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
httpCliet.DefaultRequestHeaders.ConnectionClose = true;
}
_configuration = configuration;
/// <summary>
/// 小程序AppID
/// </summary>
private const string appid = "wx48108a0c98a3dab0";
/// <summary>
/// 小程序secretID
/// </summary>
private const string secid = "e752e4fba67526eca21313a18c96a58f";
appid = $"{configuration.GetSection("Wechat:appid").Value}";
secret = $"{configuration.GetSection("Wechat:secret").Value}";
secid = $"{configuration.GetSection("Wechat:secid").Value}";
}
public async Task<Result> GetOpenId(string code)
{
var ret = new Result();
@ -53,5 +69,142 @@ namespace _24Hour
return ret;
}
/// <summary>
/// 律师预约微信消息提醒,成功
/// </summary>
/// <returns></returns>
public bool wxts(string? useropenId, string? name, string? unit, DateTime? datetime, string? matter,string? attention)
{
try
{
var token = "";
// 获取缓存
token = cache.Get("token")?.ToString();
if (string.IsNullOrEmpty(token))
{
string geturl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
var re1 = HttpHelper.Get(geturl);
if (re1.Jsonstr("errcode") == null)
{
token = re1.Jsonstr("access_token");
// 移除缓存
cache.Remove("token");
// 添加缓存
cache.Add("token", token, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(120) });
}
}
string url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";//发送地址
try
{
object msg = null;
string posturl = $"{url}{token}";//发送地址
var thing4 = matter;
var thing5 = attention;
if (matter.Length>20)
thing4 = matter.Substring(0, 17)+"...";
if (attention.Length>20)
thing5 = attention.Substring(0, 17)+"...";
msg = new
{
touser = useropenId,
template_id = "mRfzPnc_3JuV9cPhjKrRL3jX1C_JJoBGYtqEnbfadRM",
page= "pages/selfService/reception/reception",
miniprogram_state= $"{_configuration.GetSection("Wechat:miniprogram_state").Value}",
lang ="zh_CN",
data = new
{
//name1 = new { value = $"{name}"},//
thing2 = new { value = $"{unit}"},//
date3 = new { value = $"{datetime:yyyy年MM月dd日 HH:mm}"},//
thing4 = new { value = $"{thing4}"},//
thing5 = new { value = $"{thing5}", color = "#173177" },//
},
};
var re = HttpHelper.Post(posturl, msg);
if (re.Jsonstr("errcode") == "0")
return true;
return false;
}
catch (Exception ex)
{
}
return true;
}
catch (Exception ex)
{
}
return false;
}
/// <summary>
/// 律师预约微信消息提醒,失败
/// </summary>
/// <returns></returns>
public bool sbwxts(string? useropenId,string? name,string? unit,DateTime? datetime,string? matter)
{
try
{
var token = "";
// 获取缓存
var tokenss = cache.Get("token");
if (string.IsNullOrEmpty(token))
{
string geturl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx48108a0c98a3dab0&secret=e752e4fba67526eca21313a18c96a58f";
var re1 = HttpHelper.Get(geturl);
if (re1.Jsonstr("errcode") == null)
{
token = re1.Jsonstr("access_token");
// 移除缓存
cache.Remove("token");
// 添加缓存
cache.Add("token", token, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(120) });
}
}
string url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";//发送地址
try
{
object msg = null;
string posturl = $"{url}{token}";//发送地址
var thing4 = matter;
if (matter.Length > 20)
thing4 = matter.Substring(0, 17) + "...";
msg = new
{
touser = useropenId,
template_id = "sPbZd6ro14L4uCR_TyDlB4g-sR20zzqcvb-c6QkV3U4",
page = "pages/selfService/reception/reception",
miniprogram_state = $"{_configuration.GetSection("Wechat:miniprogram_state").Value}",
lang = "zh_CN",
data = new
{
thing1 = new { value = $"{name}" },//访问人
thing2 = new { value = $"{unit}" },//访问单位
time3 = new { value = $"{datetime:yyyy年MM月dd日 HH:mm}" },//预约时间
thing4 = new { value = $"{thing4}" },//事由
},
};
var re = HttpHelper.Post(posturl, msg);
if (re.Jsonstr("errcode") == "0")
return true;
return false;
}
catch (Exception ex)
{
}
return true;
}
catch (Exception ex)
{
}
return false;
}
}
}

6
24Hour/appsettings.json

@ -44,5 +44,11 @@
"Videoaddress": {
"rtmp": "rtmp://192.168.0.24:1935/live/",
"rtsp": "rtsp://192.168.0.24:8554/live/"
},
"Wechat": {
"appid": "wx48108a0c98a3dab0",
"secret": "e752e4fba67526eca21313a18c96a58f",
"secid": "e752e4fba67526eca21313a18c96a58f",
"miniprogram_state": "trial"
}
}

12
Elight.Utility/Extensions/StringExtension.cs

@ -1,4 +1,5 @@
using System;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
@ -61,6 +62,15 @@ namespace Elight.Utility.Extensions
string str = string.Concat(s.First().ToString().ToLower(), s.AsSpan(1));
return str;
}
public static string Jsonstr(this string str, string key)
{
JObject esult = JObject.Parse(str);
if (esult != null && esult[key] != null)
{
return $"{esult[key]}";
}
return null;
}
/// <summary>
/// 首字母转大写

Loading…
Cancel
Save