WeChatPayNotifyController.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Essensoft.AspNetCore.Payment.WeChatPay;
  5. using Essensoft.AspNetCore.Payment.WeChatPay.V2;
  6. using Essensoft.AspNetCore.Payment.WeChatPay.V2.Notify;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Extensions.Options;
  10. namespace WebApplicationSample.Controllers
  11. {
  12. [Route("wechatpay/notify")]
  13. public class WeChatPayNotifyController : Controller
  14. {
  15. private readonly IWeChatPayNotifyClient _client;
  16. private readonly IOptions<WeChatPayOptions> _optionsAccessor;
  17. public WeChatPayNotifyController(IWeChatPayNotifyClient client, IOptions<WeChatPayOptions> optionsAccessor)
  18. {
  19. _client = client;
  20. _optionsAccessor = optionsAccessor;
  21. }
  22. /// <summary>
  23. /// 统一下单支付结果通知
  24. /// </summary>
  25. [Route("unifiedorder")]
  26. [HttpPost]
  27. public async Task<IActionResult> Unifiedorder()
  28. {
  29. try
  30. {
  31. Request.EnableBuffering();
  32. Request.Body.Seek(0, SeekOrigin.Begin);
  33. var notify = await _client.ExecuteAsync<WeChatPayUnifiedOrderNotify>(Request, _optionsAccessor.Value);
  34. if (notify.ReturnCode == WeChatPayCode.Success)
  35. {
  36. if (notify.ResultCode == WeChatPayCode.Success)
  37. {
  38. Console.WriteLine("OutTradeNo: " + notify.OutTradeNo);
  39. return WeChatPayNotifyResult.Success;
  40. }
  41. }
  42. return WeChatPayNotifyResult.Failure;
  43. }
  44. catch (WeChatPayException ex)
  45. {
  46. Console.WriteLine("出现异常: " + ex.Message);
  47. return WeChatPayNotifyResult.Failure;
  48. }
  49. }
  50. /// <summary>
  51. /// 退款结果通知
  52. /// </summary>
  53. [Route("refund")]
  54. [HttpPost]
  55. public async Task<IActionResult> Refund()
  56. {
  57. try
  58. {
  59. Request.EnableBuffering();
  60. var notify = await _client.ExecuteAsync<WeChatPayRefundNotify>(Request, _optionsAccessor.Value);
  61. if (notify.ReturnCode == WeChatPayCode.Success)
  62. {
  63. if (notify.RefundStatus == WeChatPayCode.Success)
  64. {
  65. Console.WriteLine("OutTradeNo: " + notify.OutTradeNo);
  66. return WeChatPayNotifyResult.Success;
  67. }
  68. }
  69. return WeChatPayNotifyResult.Failure;
  70. }
  71. catch (WeChatPayException ex)
  72. {
  73. Console.WriteLine("出现异常: " + ex.Message);
  74. return WeChatPayNotifyResult.Failure;
  75. }
  76. }
  77. }
  78. }