You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. using System.Web.UI;
  5. using System.Web.UI.WebControls;
  6. using System.Text;
  7. namespace WxPayAPI
  8. {
  9. /// <summary>
  10. /// 回调处理基类
  11. /// 主要负责接收微信支付后台发送过来的数据,对数据进行签名验证
  12. /// 子类在此类基础上进行派生并重写自己的回调处理过程
  13. /// </summary>
  14. public class Notify
  15. {
  16. public Page page {get;set;}
  17. public Notify(Page page)
  18. {
  19. this.page = page;
  20. }
  21. /// <summary>
  22. /// 接收从微信支付后台发送过来的数据并验证签名
  23. /// </summary>
  24. /// <returns>微信支付后台返回的数据</returns>
  25. public WxPayData GetNotifyData()
  26. {
  27. //接收从微信后台POST过来的数据
  28. System.IO.Stream s = page.Request.InputStream;
  29. int count = 0;
  30. byte[] buffer = new byte[1024];
  31. StringBuilder builder = new StringBuilder();
  32. while ((count = s.Read(buffer, 0, 1024)) > 0)
  33. {
  34. builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
  35. }
  36. s.Flush();
  37. s.Close();
  38. s.Dispose();
  39. Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());
  40. //转换数据格式并验证签名
  41. WxPayData data = new WxPayData();
  42. try
  43. {
  44. data.FromXml(builder.ToString());
  45. }
  46. catch(WxPayException ex)
  47. {
  48. //若签名错误,则立即返回结果给微信支付后台
  49. WxPayData res = new WxPayData();
  50. res.SetValue("return_code", "FAIL");
  51. res.SetValue("return_msg", ex.Message);
  52. Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
  53. page.Response.Write(res.ToXml());
  54. page.Response.End();
  55. }
  56. Log.Info(this.GetType().ToString(), "Check sign success");
  57. return data;
  58. }
  59. //派生类需要重写这个方法,进行不同的回调处理
  60. public virtual void ProcessNotify()
  61. {
  62. }
  63. }
  64. }