QiYiWeiXinGlobalContext.cs
4.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using HHECS.Infrastructure.LogHelper;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace HHECS.Infrastructure.QiYeWeiXin
{
/// <summary>
/// 企业微信消息推送 上下文
/// </summary>
public class QiYiWeiXinGlobalContext
{
public static IConfiguration Configuration { get; set; }
public static IHttpClientFactory HttpClientFactory { get; set; }
/// <summary>
/// 过期时间
/// </summary>
public static DateTime TimeOutDate { get; set; }
/// <summary>
/// Token
/// </summary>
public static string Token { get; set; }
/// <summary>
/// 获取Token
/// </summary>
/// <returns>Item1 Token;Item2 true 成功 false 失败</returns>
private static Tuple<string, bool> GetToken()
{
//判断Token是否存在 以及Token是否在有效期内
if (string.IsNullOrEmpty(Token) || TimeOutDate > DateTime.Now)
{
//构造请求链接
var requestBuild = Configuration["Wx:TokenUrl"];
using (var wxClient = HttpClientFactory.CreateClient("WxClient"))
{
var httpResponse = wxClient.GetAsync(requestBuild).Result;
var dynamic = JsonConvert.DeserializeObject<QiYeWeiXinGetTokenResult>( httpResponse.Content.ReadAsStringAsync().Result );
if (dynamic.errcode == 0)
{
Token = dynamic.access_token;
//过期5分钟前刷新Token
var expires_in = Convert.ToDouble(dynamic.expires_in - 5 * 60);
TimeOutDate = DateTime.Now.AddSeconds(expires_in);
return Tuple.Create(Token, true);
}
else
{
var msg = $"获取Token失败,错误:{dynamic.errmsg}";
Log4NetHelper.Instance.Error(msg);
return Tuple.Create(msg, false);
}
}
}
else
{
return Tuple.Create(Token, true);
}
}
/// <summary>
/// 推送 msg
/// </summary>
/// <returns>Item1 Token;Item2 是否成功</returns>
public static Tuple<bool, string> SendMsg(string content)
{
//构造请求链接
var requestBuild = Configuration["Wx:PushUrl"];
var (token, issuccess) = GetToken();
if (!issuccess) throw new Exception(token);
requestBuild = string.Format(requestBuild, token);
//建立HttpClient
using (var wxClient = HttpClientFactory.CreateClient("WxClient"))
{
byte[] data = Encoding.UTF8.GetBytes(content);
var bytearray = new ByteArrayContent(data);
var httpResponse = wxClient.PostAsync(requestBuild, bytearray).Result;
var dynamic = JsonConvert.DeserializeObject<dynamic>(httpResponse.Content.ReadAsStringAsync().Result);
if (dynamic.errcode == 0) return Tuple.Create(true, "ok");
var msg = $"推送失败,原因:{JsonConvert.SerializeObject(dynamic)}";
Log4NetHelper.Instance.Error(msg);
return Tuple.Create(false, msg);
}
}
/// <summary>
/// 获取发送内容
/// </summary>
/// <param name="userId"></param>
/// <param name="Msg"></param>
/// <returns></returns>
public static string GetContent(int agentid ,string userId , string msg )
{
if (string.IsNullOrEmpty(userId)) userId = "@all";
var tempContent = new { content = msg };
var obj = new
{
touser = userId,
toparty = "",
totag = "",
msgtype = "text",
agentid = agentid,//应用id
text = tempContent,
safe = 0,
enable_id_trans = 0,
enable_duplicate_check = 0,
duplicate_check_interval = 1800
};
string strJson = JsonConvert.SerializeObject(obj);
return strJson;
}
/// <summary>
/// 获取 AgentId
/// </summary>
/// <returns></returns>
public static int GetAgentId()
{
var agentId = Configuration["Wx:AgentId"].ToString();
return int.Parse(agentId);
}
}
}