SysWechatNotifyService.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using SKIT.FlurlHttpClient.Wechat.Api.Events;
  2. namespace Admin.NET.Core.Service;
  3. /// <summary>
  4. /// 微信通知服务
  5. /// </summary>
  6. [ApiDescriptionSettings(Order = 250)]
  7. public class SysWechatNotifyService : IDynamicApiController, ITransient
  8. {
  9. private readonly SqlSugarRepository<SysWechatUser> _sysWechatUserRep;
  10. private readonly WechatApiClient _wechatApiClient;
  11. public SysWechatNotifyService(SqlSugarRepository<SysWechatUser> sysWechatUserRep,
  12. WechatApiHttpClient wechatApiHttpClient)
  13. {
  14. _sysWechatUserRep = sysWechatUserRep;
  15. _wechatApiClient = wechatApiHttpClient.CreateWxOpenClient();
  16. }
  17. public string VerifyMessage(string appId, string timestamp, string nonce, string signature, string echoString)
  18. {
  19. // 验证服务器推送
  20. // 文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
  21. bool valid = _wechatApiClient.VerifyEventSignatureForEcho(callbackTimestamp: timestamp, callbackNonce: nonce, callbackSignature: signature);
  22. if (!valid)
  23. {
  24. return "fail";
  25. }
  26. return echoString;
  27. }
  28. public async Task<string> ReceiveMessage(string appId)
  29. {
  30. // 接收服务器推送
  31. // 文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html
  32. using var reader = new StreamReader(App.HttpContext.Request.Body, Encoding.UTF8);
  33. string content = await reader.ReadToEndAsync();
  34. var msgType = _wechatApiClient.DeserializeEventFromXml(content).MessageType?.ToUpper();
  35. switch (msgType)
  36. {
  37. case "TEXT":
  38. {
  39. var eventModel = _wechatApiClient.DeserializeEventFromXml<TextMessageEvent>(content);
  40. //_logger.LogInformation("接收到微信推送的文本消息,消息内容:{0}", eventModel.Content);
  41. // 后续处理略
  42. }
  43. break;
  44. case "IMAGE":
  45. {
  46. var eventModel = _wechatApiClient.DeserializeEventFromXml<ImageMessageEvent>(content);
  47. //_logger.LogInformation("接收到微信推送的图片消息,图片链接:{0}", eventModel.PictureUrl);
  48. // 后续处理略
  49. }
  50. break;
  51. default:
  52. {
  53. // 其他情况略
  54. }
  55. break;
  56. }
  57. return "success";
  58. }
  59. }