移动系统liao
2024-05-21 b8836eb74c397300d72b4ffed09ab36b1c4c4339
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.Configuration;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.WeChat.Service.Enums;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Models;
using InitQ.Abstractions;
using InitQ.Attributes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
 
namespace CoreCms.Net.RedisMQ
{
    /// <summary>
    /// 微信模板消息【小程序,公众号都走这里】
    /// </summary>
    public class SendWxTemplateMessageSubscribe : IRedisSubscribe
    {
        private readonly ICoreCmsUserWeChatInfoServices _userWeChatInfoServices;
        private readonly ICoreCmsUserWeChatMsgSubscriptionServices _userWeChatMsgSubscriptionServices;
        private readonly ICoreCmsUserWeChatMsgTemplateServices _userWeChatMsgTemplateServices;
        private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
 
 
        public SendWxTemplateMessageSubscribe(ICoreCmsUserWeChatInfoServices userWeChatInfoServices, ICoreCmsUserWeChatMsgSubscriptionServices userWeChatMsgSubscriptionServices, ICoreCmsUserWeChatMsgTemplateServices userWeChatMsgTemplateServices, IWeChatApiHttpClientFactory weChatApiHttpClientFactory)
        {
            _userWeChatInfoServices = userWeChatInfoServices;
            _userWeChatMsgSubscriptionServices = userWeChatMsgSubscriptionServices;
            _userWeChatMsgTemplateServices = userWeChatMsgTemplateServices;
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
        }
 
        /// <summary>
        /// 微信模板消息【小程序,公众号都走这里】
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        [Subscribe(RedisMessageQueueKey.SendWxTemplateMessage)]
        private async Task SendWxTemplateMessage(string msg)
        {
            try
            {
                var request = JsonConvert.DeserializeObject<SendWxTemplateMessage>(msg);
                if (request != null)
                {
                    if (!request.parameters.ContainsKey("parameters"))
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "参数获取失败");
 
                        return;
                    }
                    var parameters = (JObject)request.parameters["parameters"];
 
                    if (parameters == null)
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "参数实例化失败");
                        return;
                    }
                    else if (string.IsNullOrEmpty(request.code))
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "消息类型获取失败");
                        return;
                    }
 
                    if (request.code == GlobalEnumVars.PlatformMessageTypes.SellerOrderNotice.ToString())
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "商家不通知");
                        return;
                    }
 
                    if (request.userId == 0 || string.IsNullOrEmpty(request.code))
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "用户编码获取失败");
                        return;
                    }
 
                    var templateData = await GetUserIsTip(request.userId, request.code);
                    if (templateData == null)
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "未查询到订阅编码");
                        return;
                    }
                    var weChatUserInfo = await _userWeChatInfoServices.QueryByClauseAsync(p => p.userId == request.userId);
                    if (weChatUserInfo == null)
                    {
                        NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "微信用户数据查询失败");
                        return;
                    }
 
 
                    var templateMessageData = new Dictionary<string, CgibinMessageSubscribeSendRequest.Types.DataItem>();
                    var pageUrl = string.Empty;
 
                    if (request.code == GlobalEnumVars.PlatformMessageTypes.CreateOrder.ToString())
                    {
                        if (!string.IsNullOrEmpty(parameters["orderId"]!.ToString()))
                        {
                            templateMessageData[templateData.data01] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["orderAmount"]!.ToString()))
                        {
                            templateMessageData[templateData.data02] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderAmount"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["shipName"]!.ToString()))
                        {
                            templateMessageData[templateData.data03] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["shipName"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["shipMobile"]!.ToString()))
                        {
                            templateMessageData[templateData.data04] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["shipMobile"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["orderAmount"]!.ToString()))
                        {
                            templateMessageData[templateData.data05] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderAmount"].ToString() };
                        }
                        pageUrl = "/pages/member/order/detail/detail?orderId=" + parameters["orderId"];
                    }
                    else if (request.code == GlobalEnumVars.PlatformMessageTypes.RemindOrderPay.ToString())
                    {
                        if (!string.IsNullOrEmpty(parameters["orderId"]!.ToString()))
                        {
                            templateMessageData[templateData.data01] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["orderAmount"]!.ToString()))
                        {
                            templateMessageData[templateData.data02] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderAmount"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["createTime"]!.ToString()))
                        {
                            templateMessageData[templateData.data03] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = Convert.ToDateTime(parameters["createTime"].ToString()).ToString("yyyy年MM月dd日 HH:mm") };
                        }
                        templateMessageData[templateData.data04] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = "订单即将失效,请及时付款!" };
                        pageUrl = "/pages/member/order/detail/detail?orderId=" + parameters["orderId"];
                    }
                    else if (request.code == GlobalEnumVars.PlatformMessageTypes.OrderPayed.ToString())
                    {
                        if (!string.IsNullOrEmpty(parameters["orderId"]!.ToString()))
                        {
                            templateMessageData[templateData.data01] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["orderAmount"]!.ToString()))
                        {
                            templateMessageData[templateData.data02] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderAmount"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["paymentTime"]!.ToString()))
                        {
                            templateMessageData[templateData.data03] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = Convert.ToDateTime(parameters["paymentTime"].ToString()).ToString("yyyy年MM月dd日 HH:mm") };
                        }
                        pageUrl = "/pages/member/order/detail/detail?orderId=" + parameters["orderId"];
                    }
                    else if (request.code == GlobalEnumVars.PlatformMessageTypes.DeliveryNotice.ToString())
                    {
                        if (!string.IsNullOrEmpty(parameters["orderId"]!.ToString()))
                        {
                            templateMessageData[templateData.data01] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["logiName"]!.ToString()))
                        {
                            templateMessageData[templateData.data02] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["logiName"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["logiNo"]!.ToString()))
                        {
                            templateMessageData[templateData.data03] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["logiNo"].ToString() };
                        }
                        pageUrl = "/pages/member/order/detail/detail?orderId=" + parameters["orderId"];
                    }
                    else if (request.code == GlobalEnumVars.PlatformMessageTypes.AfterSalesPass.ToString())
                    {
                        if (!string.IsNullOrEmpty(parameters["orderId"]!.ToString()))
                        {
                            templateMessageData[templateData.data01] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["orderAmount"]!.ToString()))
                        {
                            templateMessageData[templateData.data02] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["orderAmount"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["aftersalesId"]!.ToString()))
                        {
                            templateMessageData[templateData.data03] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["aftersalesId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["aftersalesStatus"]!.ToString()))
                        {
                            templateMessageData[templateData.data04] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["aftersalesStatus"].ToString() };
                        }
                        pageUrl = "/pages/member/order/detail/detail?orderId=" + parameters["orderId"];
                    }
                    else if (request.code == GlobalEnumVars.PlatformMessageTypes.RefundSuccess.ToString())
                    {
                        if (!string.IsNullOrEmpty(parameters["sourceId"]!.ToString()))
                        {
                            templateMessageData[templateData.data01] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["sourceId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["aftersalesId"]!.ToString()))
                        {
                            templateMessageData[templateData.data02] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["aftersalesId"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["money"]!.ToString()))
                        {
                            templateMessageData[templateData.data03] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["money"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["paymentCode"]!.ToString()))
                        {
                            templateMessageData[templateData.data04] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = parameters["paymentCode"].ToString() };
                        }
                        if (!string.IsNullOrEmpty(parameters["createTime"]!.ToString()))
                        {
                            templateMessageData[templateData.data05] = new CgibinMessageSubscribeSendRequest.Types.DataItem() { Value = Convert.ToDateTime(parameters["createTime"].ToString()).ToString("yyyy年MM月dd日 HH:mm") };
                        }
                    }
                    var result = await Send(weChatUserInfo.openid, templateData.templateId, templateMessageData, pageUrl);
 
                    NLogUtil.WriteAll(NLog.LogLevel.Info, LogType.RedisMessageQueue, "微信模板消息", JsonConvert.SerializeObject(result));
                }
                else
                {
                    NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", "模板消息推送数据为空");
                }
            }
            catch (Exception ex)
            {
                NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.RedisMessageQueue, "微信模板消息", msg, ex);
                throw;
            }
            await Task.CompletedTask;
        }
 
 
        #region 判断是否需要通知用户返回 null或者 模板数据
        /// <summary>
        /// 判断是否需要通知用户返回 null或者 模板数据
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<CoreCmsUserWeChatMsgTemplate> GetUserIsTip(int userId, string code)
        {
            string newCode;
            if (code == GlobalEnumVars.PlatformMessageTypes.CreateOrder.ToString())
            {
                newCode = GlobalEnumVars.WeChatMsgTemplateType.order.ToString();
            }
            else if (code == GlobalEnumVars.PlatformMessageTypes.RemindOrderPay.ToString())
            {
                newCode = GlobalEnumVars.WeChatMsgTemplateType.cancel.ToString();
            }
            else if (code == GlobalEnumVars.PlatformMessageTypes.OrderPayed.ToString())
            {
                newCode = GlobalEnumVars.WeChatMsgTemplateType.pay.ToString();
            }
            else if (code == GlobalEnumVars.PlatformMessageTypes.DeliveryNotice.ToString())
            {
                newCode = GlobalEnumVars.WeChatMsgTemplateType.ship.ToString();
            }
            else if (code == GlobalEnumVars.PlatformMessageTypes.AfterSalesPass.ToString())
            {
                newCode = GlobalEnumVars.WeChatMsgTemplateType.aftersale.ToString();
            }
            else if (code == GlobalEnumVars.PlatformMessageTypes.RefundSuccess.ToString())
            {
                newCode = GlobalEnumVars.WeChatMsgTemplateType.refund.ToString();
            }
            else
            {
                return null;
            }
 
            var info = await _userWeChatMsgSubscriptionServices.QueryByClauseAsync(p => p.userId == userId && p.type == newCode);
            if (info != null)
            {
                return await _userWeChatMsgTemplateServices.QueryByClauseAsync(p => p.templateId == info.templateId);
            }
            return await _userWeChatMsgTemplateServices.QueryByClauseAsync(p => p.templateTitle == newCode);
            //return null;
        }
 
        #endregion
 
        #region 异步发送微信模板消息
        /// <summary>
        /// 异步发送微信模板消息
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="templateId">模板编号</param>
        /// <param name="tmpData">发送数据</param>
        /// <param name="pageUrl">路径(如:pages/index/index)</param>
        /// <returns></returns>
        private async Task<WebApiCallBack> Send(string openId, string templateId, Dictionary<string, CgibinMessageSubscribeSendRequest.Types.DataItem> tmpData, string pageUrl)
        {
            var jm = new WebApiCallBack();
            var accessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();
            var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
            var request = new CgibinMessageSubscribeSendRequest();
 
            request.AccessToken = accessToken;
            request.MiniProgramPagePath = pageUrl;
            request.TemplateId = templateId;
            request.ToUserOpenId = openId;
            request.Data = tmpData;
            request.MiniProgramState = "formal";
 
            var response = await client.ExecuteCgibinMessageSubscribeSendAsync(request);
            if (response.IsSuccessful())
            {
                jm.status = true;
                jm.msg = "消息已发送,请注意查收";
                jm.otherData = new
                {
                    openId,
                    templateId,
                    tmpData,
                    pageUrl
                };
            }
            else
            {
                jm.status = false;
                jm.msg = response.ErrorMessage;
                jm.otherData = new
                {
                    openId,
                    templateId,
                    tmpData,
                    pageUrl
                };
            }
 
            return jm;
        }
        #endregion
 
 
    }
}