1. 程式人生 > >C#微信支付(一)—— 基礎幫助類

C#微信支付(一)—— 基礎幫助類

最近做了下微信支付,坑好多了,最終還是做完了,避免下次再走坑,在此總結一下

配置類

public class Config
    {
        //=======【基本資訊設定】=====================================
        /* 微信公眾號資訊配置
        * APPID:繫結支付的APPID(必須配置)
        * MCHID:商戶號(必須配置)
        * KEY:商戶支付金鑰,參考開戶郵件設定(必須配置),請妥善保管,避免金鑰洩露
        * APPSECRET:公眾帳號secert(僅JSAPI支付的時候需要配置),請妥善保管,避免金鑰洩露
        */
public static string AppID { get { return ConfigurationManager.AppSettings["AppID"]; } } public static string MchID { get { return ConfigurationManager.AppSettings["MchID"]; } } public static string Key { get
{ return ConfigurationManager.AppSettings["Key"]; } } public static string AppSecret { get { return ConfigurationManager.AppSettings["AppSecret"]; } } //=======【證書路徑設定】===================================== /* 證書路徑,注意應該填寫絕對路徑(僅退款、撤銷訂單時需要) * 1.證書檔案不能放在web伺服器虛擬目錄,應放在有訪問許可權控制的目錄中,防止被他人下載; * 2.建議將證書檔名改為複雜且不容易猜測的檔案 * 3.商戶伺服器要做好病毒和木馬防護工作,不被非法侵入者竊取證書檔案。 */
public static string SSlCertPath { get { return ConfigurationManager.AppSettings["SSlCertPath"]; } } public static string SSlCertPassword { get { return ConfigurationManager.AppSettings["SSlCertPassword"]; } } //=======【支付結果通知url】===================================== /* 支付結果通知回撥url,用於商戶接收支付結果 */ public static string NotifyUrl { get { return ConfigurationManager.AppSettings["NotifyUrl"]; } } //=======【商戶系統後臺機器IP】===================================== /* 此引數可手動配置也可在程式中自動獲取 */ public static string Ip { get { return ConfigurationManager.AppSettings["Ip"]; } } //=======【代理伺服器設定】=================================== /* 預設IP和埠號分別為0.0.0.0和0,此時不開啟代理(如有需要才設定) */ public static string ProxyUrl { get { return ConfigurationManager.AppSettings["ProxyUrl"]; } } //=======【上報資訊配置】=================================== /* 測速上報等級,0.關閉上報; 1.僅錯誤時上報; 2.全量上報 */ public static int ReportLevel { get { int rl = 0; int.TryParse(ConfigurationManager.AppSettings["ReportLevel"], out rl); return rl; } } }

介面資料處理幫助類

    /// <summary>
    /// 微信支付協議介面資料類,所有的API介面通訊都依賴這個資料結構,
    /// 在呼叫介面之前先填充各個欄位的值,然後進行介面通訊,
    /// 這樣設計的好處是可擴充套件性強,使用者可隨意對協議進行更改而不用重新設計資料結構,
    /// 還可以隨意組合出不同的協議資料包,不用為每個協議設計一個數據包結構
    /// </summary>
    public class WxPayData
    {
        public  const string SIGN_TYPE_MD5 = "MD5";
        public  const string SIGN_TYPE_HMAC_SHA256 = "HMAC-SHA256";
        public WxPayData()
        {

        }

        //採用排序的Dictionary的好處是方便對資料包進行簽名,不用再簽名之前再做一次排序
        private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();

        /**
        * 設定某個欄位的值
        * @param key 欄位名
         * @param value 欄位值
        */
        public void SetValue(string key, object value)
        {
            m_values[key] = value;
        }

        /**
        * 根據欄位名獲取某個欄位的值
        * @param key 欄位名
         * @return key對應的欄位值
        */
        public object GetValue(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            return o;
        }

        /**
         * 判斷某個欄位是否已設定
         * @param key 欄位名
         * @return 若欄位key已被設定,則返回true,否則返回false
         */
        public bool IsSet(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            if (null != o)
                return true;
            else
                return false;
        }

        /**
        * @將Dictionary轉成xml
        * @return 經轉換得到的xml串
        * @throws WxPayException
        **/
        public string ToXml()
        {
            //資料為空時不能轉化為xml格式
            if (0 == m_values.Count)
            {
                Log.Error(this.GetType().ToString(), "WxPayData資料為空!");
                throw new WxPayException("WxPayData資料為空!");
            }

            string xml = "<xml>";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                //欄位值不能為null,會影響後續流程
                if (pair.Value == null)
                {
                    Log.Error(this.GetType().ToString(), "WxPayData內部含有值為null的欄位!");
                    throw new WxPayException("WxPayData內部含有值為null的欄位!");
                }

                if (pair.Value.GetType() == typeof(int))
                {
                    xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
                }
                else if (pair.Value.GetType() == typeof(string))
                {
                    xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
                }
                else//除了string和int型別不能含有其他資料型別
                {
                    Log.Error(this.GetType().ToString(), "WxPayData欄位資料型別錯誤!");
                    throw new WxPayException("WxPayData欄位資料型別錯誤!");
                }
            }
            xml += "</xml>";
            return xml;
        }

        /**
        * @將xml轉為WxPayData物件並返回物件內部的資料
        * @param string 待轉換的xml串
        * @return 經轉換得到的Dictionary
        * @throws WxPayException
        */
        public SortedDictionary<string, object> FromXml(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                Log.Error(this.GetType().ToString(), "將空的xml串轉換為WxPayData不合法!");
                throw new WxPayException("將空的xml串轉換為WxPayData不合法!");
            }


            SafeXmlDocument xmlDoc = new SafeXmlDocument();
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//獲取到根節點<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//獲取xml的鍵值對到WxPayData內部的資料中
            }

            try
            {
                //2015-06-29 錯誤是沒有簽名
                if(m_values["return_code"] != "SUCCESS")
                {
                    return m_values;
                }
                CheckSign();//驗證簽名,不通過會拋異常
            }
            catch(WxPayException ex)
            {
                throw new WxPayException(ex.Message);
            }

            return m_values;
        }

        /**
        * @Dictionary格式轉化成url引數格式
        * @ return url格式串, 該串不包含sign欄位值
        */
        public string ToUrl()
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value == null)
                {
                    Log.Error(this.GetType().ToString(), "WxPayData內部含有值為null的欄位!");
                    throw new WxPayException("WxPayData內部含有值為null的欄位!");
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    buff += pair.Key + "=" + pair.Value + "&";
                }
            }
            buff = buff.Trim('&');
            return buff;
        }


        /**
        * @Dictionary格式化成Json
         * @return json串資料
        */
        public string ToJson()
        {
            string jsonStr = JsonMapper.ToJson(m_values);
            return jsonStr;

        }

        /**
        * @values格式化成能在Web頁面上顯示的結果(因為web頁面上不能直接輸出xml格式的字串)
        */
        public string ToPrintStr()
        {
            string str = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value == null)
                {
                    Log.Error(this.GetType().ToString(), "WxPayData內部含有值為null的欄位!");
                    throw new WxPayException("WxPayData內部含有值為null的欄位!");
                }


                str += string.Format("{0}={1}\n", pair.Key, pair.Value.ToString());
            }
            str = HttpUtility.HtmlEncode(str);
            Log.Debug(this.GetType().ToString(), "Print in Web Page : " + str);
            return str;
        }


        /**
        * @生成簽名,詳見簽名生成演算法
        * @return 簽名, sign欄位不參加簽名
        */
        public string MakeSign(string signType){
            //轉url格式
            string str = ToUrl();
            //在string後加入API KEY
            str += "&key=" + WxPayConfig.GetConfig().GetKey();
            if (signType == SIGN_TYPE_MD5)
            {
                var md5 = MD5.Create();
                var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                var sb = new StringBuilder();
                foreach (byte b in bs)
                {
                    sb.Append(b.ToString("x2"));
                }
                //所有字元轉為大寫
                return sb.ToString().ToUpper();
            }
            else if(signType==SIGN_TYPE_HMAC_SHA256)
            {
                return CalcHMACSHA256Hash(str, WxPayConfig.GetConfig().GetKey());
            }else{
                throw new WxPayException("sign_type 不合法");
            }
        }

        /**
        * @生成簽名,詳見簽名生成演算法
        * @return 簽名, sign欄位不參加簽名 SHA256
        */
        public string MakeSign()
        {
            return MakeSign(SIGN_TYPE_HMAC_SHA256);
        }



        /**
        * 
        * 檢測簽名是否正確
        * 正確返回true,錯誤拋異常
        */
        public bool CheckSign(string signType)
        {
            //如果沒有設定簽名,則跳過檢測
            if (!IsSet("sign"))
            {
                Log.Error(this.GetType().ToString(), "WxPayData簽名存在但不合法!");
                throw new WxPayException("WxPayData簽名存在但不合法!");
            }
            //如果設定了簽名但是簽名為空,則拋異常
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                Log.Error(this.GetType().ToString(), "WxPayData簽名存在但不合法!");
                throw new WxPayException("WxPayData簽名存在但不合法!");
            }

            //獲取接收到的簽名
            string return_sign = GetValue("sign").ToString();

            //在本地計算新的簽名
            string cal_sign = MakeSign(signType);

            if (cal_sign == return_sign)
            {
                return true;
            }

            Log.Error(this.GetType().ToString(), "WxPayData簽名驗證錯誤!");
            throw new WxPayException("WxPayData簽名驗證錯誤!");
        }



        /**
        * 
        * 檢測簽名是否正確
        * 正確返回true,錯誤拋異常
        */
        public bool CheckSign()
        {
            return CheckSign(SIGN_TYPE_HMAC_SHA256);
        }

        /**
        * @獲取Dictionary
        */
        public SortedDictionary<string, object> GetValues()
        {
            return m_values;
        }


        private  string CalcHMACSHA256Hash(string plaintext, string salt)
        {
            string result = "";
            var enc = Encoding.Default;
            byte[]
            baText2BeHashed = enc.GetBytes(plaintext),
            baSalt = enc.GetBytes(salt);
            System.Security.Cryptography.HMACSHA256 hasher = new HMACSHA256(baSalt);
            byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
            result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
            return result;
        }




    }

底層通訊類

/// <summary>
    /// http連線基礎類,負責底層的http通訊
    /// </summary>
    public class HttpService
    {
        private static string USER_AGENT = string.Format("WXPaySDK/{3} ({0}) .net/{1} {2}", Environment.OSVersion, Environment.Version, Config.MchID, typeof(HttpService).Assembly.GetName().Version);

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接確認,否則打不開    
            return true;
        }

        public static string Post(string xml, string url, bool isUseCert, int timeout)
        {
            System.GC.Collect();//垃圾回收,回收沒有正常關閉的http連線

            string result = "";//返回結果

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;

            try
            {
                //設定最大連線數
                ServicePointManager.DefaultConnectionLimit = 200;
                //設定https驗證方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面設定HttpWebRequest的相關屬性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = USER_AGENT;
                request.Method = "POST";
                request.Timeout = timeout * 1000;

                //設定代理伺服器
                if (!string.IsNullOrEmpty(Config.ProxyUrl))
                {
                    WebProxy proxy = new WebProxy();                          //定義一個閘道器物件
                    proxy.Address = new Uri(Config.ProxyUrl);              //閘道器伺服器埠:埠
                    request.Proxy = proxy;
                }

                //設定POST的資料型別和長度
                request.ContentType = "text/xml";
                byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
                request.ContentLength = data.Length;

                //是否使用證書
                if (isUseCert)
                {
                    string path = HttpContext.Current.Request.PhysicalApplicationPath;
                    X509Certificate2 cert = new X509Certificate2(path + Config.SSlCertPath, Config.SSlCertPassword);
                    request.ClientCertificates.Add(cert);
                    //Log.Debug("WxPayApi", "PostXml used cert");
                }

                //往伺服器寫入資料
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                //獲取服務端返回
                response = (HttpWebResponse)request.GetResponse();

                //獲取服務端返回資料
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                //Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
                //Log.Error("Exception message: {0}", e.Message);
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                //Log.Error("HttpService", e.ToString());
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    //Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                    //Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                //Log.Error("HttpService", e.ToString());
                throw new Exception(e.ToString());
            }
            finally
            {
                //關閉連線和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        /// <summary>
        /// 處理http GET請求,返回資料
        /// </summary>
        /// <param name="url">請求的url地址</param>
        /// <returns>http GET成功後返回的資料,失敗拋WebException異常</returns>
        public static string Get(string url)
        {
            System.GC.Collect();
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //請求url以獲取資料
            try
            {
                //設定最大連線數
                ServicePointManager.DefaultConnectionLimit = 200;
                //設定https驗證方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面設定HttpWebRequest的相關屬性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = USER_AGENT;
                request.Method = "GET";

                //獲取伺服器返回
                response = (HttpWebResponse)request.GetResponse();

                //獲取HTTP返回資料
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                //Log.Error("HttpService","Thread - caught ThreadAbortException - resetting.");
                //Log.Error("Exception message: {0}", e.Message);
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                //Log.Error("HttpService", e.ToString());
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    // Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                    //Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                //Log.Error("HttpService", e.ToString());
                throw new Exception(e.ToString());
            }
            finally
            {
                //關閉連線和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }
    }

回撥處理類,這裡加了相容H5支付的情況,spbill_create_ip H5要求傳支付使用者的真實IP

/// <summary>
    /// 回撥處理基類
    /// 主要負責接收微信支付後臺傳送過來的資料,對資料進行簽名驗證
    /// 子類在此類基礎上進行派生並重寫自己的回撥處理過程
    /// </summary>
    public class Notify
    {
        /// <summary>
        /// 接收從微信支付後臺傳送過來的資料並驗證簽名
        /// </summary>
        /// <returns>微信支付後臺返回的資料</returns>
        public WxPayData GetNotifyData(HttpContext context)
        {
            //接收從微信後臺POST過來的資料
            System.IO.Stream s = context.Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            //Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());

            //轉換資料格式, 取消簽名校驗,簽名呼叫方自己呼叫,相容支付和退款
            WxPayData data = new WxPayData();
            try
            {
                //FormXML會校驗簽名
                data.FromXmlNoCheck(builder.ToString());
            }
            catch (Exception ex)
            {
                //若簽名錯誤,則立即返回結果給微信支付後臺
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                //Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                context.Response.Write(res.ToXml());
                context.Response.End();
            }

            //Log.Info(this.GetType().ToString(), "Check sign success");
            return data;
        }

        //派生類需要重寫這個方法,進行不同的回撥處理
        public virtual WxPayData ProcessNotify(HttpContext context)
        {
            return null;
        }
    }

隨機數

public class RandomGenerator
    {
        readonly RNGCryptoServiceProvider csp;

        public RandomGenerator()
        {
            csp = new RNGCryptoServiceProvider();
        }

        public int Next(int minValue, int maxExclusiveValue)
        {
            if (minValue >= maxExclusiveValue)
                throw new ArgumentOutOfRangeException("minValue must be lower than maxExclusiveValue");

            long diff = (long)maxExclusiveValue - minValue;
            long upperBound = uint.MaxValue / diff * diff;

            uint ui;
            do
            {
                ui = GetRandomUInt();
            } while (ui >= upperBound);
            return (int)(minValue + (ui % diff));
        }

        public uint GetRandomUInt()
        {
            var randomBytes = GenerateRandomBytes(sizeof(uint));
            return BitConverter.ToUInt32(randomBytes, 0);
        }

        private byte[] GenerateRandomBytes(int bytesNumber)
        {
            byte[] buffer = new byte[bytesNumber];
            csp.GetBytes(buffer);
            return buffer;
        }
    }

底層方法,這裡跟微信原始碼有點不一樣,多加了H5支付的相容程式碼

 public class WxPayApi
    {
        /**
        * 提交被掃支付API
        * 收銀員使用掃碼裝置讀取微信使用者刷卡授權碼以後,二維碼或條碼資訊傳送至商戶收銀臺,
        * 由商戶收銀臺或者商戶後臺呼叫該介面發起支付。
        * @param WxPayData inputObj 提交給被掃支付API的引數
        * @param int timeOut 超時時間
        * @throws WxPayException
        * @return 成功時返回呼叫結果,其他拋異常
        */
        public static WxPayData Micropay(WxPayData inputObj, int timeOut = 10)
        {
            string url = "https://api.mch.weixin.qq.com/pay/micropay";
            //檢測必填引數
            if (!inputObj.IsSet("body"))
            {
                throw new Exception("提交被掃支付API介面中,缺少必填引數body!");
            }
            else if (!inputObj.IsSet("out_trade_no"))
            {
                throw new Exception("提交被掃支付API介面中,缺少必填引數out_trade_no!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new Exception("提交被掃支付API介面中,缺少必填引數total_fee!");
            }
            else if (!inputObj.IsSet("auth_code"))
            {
                throw new Exception("提交被掃支付API介面中,缺少必填引數auth_code!");
            }

            inputObj.SetValue("spbill_create_ip", Config.Ip);//終端ip
            inputObj.SetValue("appid", Config.AppID);//公眾賬號ID
            inputObj.SetValue("mch_id", Config.MchID);//商戶號
            inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//隨機字串
            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//簽名型別
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;//請求開始時間

            //Log.Debug("WxPayApi", "MicroPay request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);//呼叫HTTP通訊介面以提交資料到API
            //Log.Debug("WxPayApi", "MicroPay response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//獲得介面耗時

            //將xml格式的結果轉換為物件以返回
            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }


        /**
        *    
        * 查詢訂單
        * @param WxPayData inputObj 提交給查詢訂單API的引數
        * @param int timeOut 超時時間
        * @throws WxPayException
        * @return 成功時返回訂單查詢結果,其他拋異常
        */
        public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/orderquery";
            //檢測必填引數
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new Exception("訂單查詢介面中,out_trade_no、transaction_id至少填一個!");
            }

            inputObj.SetValue("appid", Config.AppID);//公眾賬號ID
            inputObj.SetValue("mch_id", Config.MchID);//商戶號
            inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//隨機字串
            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//簽名型別
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名


            string xml = inputObj.ToXml();

            var start = DateTime.Now;

            //Log.Debug("WxPayApi", "OrderQuery request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);//呼叫HTTP通訊介面提交資料
            //Log.Debug("WxPayApi", "OrderQuery response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//獲得介面耗時

            //將xml格式的資料轉化為物件以返回
            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }


        /**
        * 
        * 撤銷訂單API介面
        * @param WxPayData inputObj 提交給撤銷訂單API介面的引數,out_trade_no和transaction_id必填一個
        * @param int timeOut 介面超時時間
        * @throws WxPayException
        * @return 成功時返回API呼叫結果,其他拋異常
        */
        public static WxPayData Reverse(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
            //檢測必填引數
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new Exception("撤銷訂單API介面中,引數out_trade_no和transaction_id必須填寫一個!");
            }

            inputObj.SetValue("appid", Config.AppID);//公眾賬號ID
            inputObj.SetValue("mch_id", Config.MchID);//商戶號
            inputObj.SetValue("nonce_str", GenerateNonceStr());//隨機字串
            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//簽名型別
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;//請求開始時間

            //Log.Debug("WxPayApi", "Reverse request : " + xml);

            string response = HttpService.Post(xml, url, true, timeOut);

            //Log.Debug("WxPayApi", "Reverse response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }


        /**
        * 
        * 申請退款
        * @param WxPayData inputObj 提交給申請退款API的引數
        * @param int timeOut 超時時間
        * @throws WxPayException
        * @return 成功時返回介面呼叫結果,其他拋異常
        */
        public static WxPayData Refund(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //檢測必填引數
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new Exception("退款申請介面中,out_trade_no、transaction_id至少填一個!");
            }
            else if (!inputObj.IsSet("out_refund_no"))
            {
                throw new Exception("退款申請介面中,缺少必填引數out_refund_no!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new Exception("退款申請介面中,缺少必填引數total_fee!");
            }
            else if (!inputObj.IsSet("refund_fee"))
            {
                throw new Exception("退款申請介面中,缺少必填引數refund_fee!");
            }
            else if (!inputObj.IsSet("op_user_id"))
            {
                throw new Exception("退款申請介面中,缺少必填引數op_user_id!");
            }

            inputObj.SetValue("appid", Config.AppID);//公眾賬號ID
            inputObj.SetValue("mch_id", Config.MchID);//商戶號
            inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//隨機字串

            //非同步通知url未設定,則使用配置檔案中的url
            if (!inputObj.IsSet("notify_url"))
            {
                inputObj.SetValue("notify_url", Config.NotifyUrl);//非同步通知url
            }

            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//簽名型別
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名

            string xml = inputObj.ToXml();
            var start = DateTime.Now;

            //Log.Debug("WxPayApi", "Refund request : " + xml);
            string response = HttpService.Post(xml, url, true, timeOut);//呼叫HTTP通訊介面提交資料到API
            //Log.Debug("WxPayApi", "Refund response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//獲得介面耗時

            //將xml格式的結果轉換為物件以返回
            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }


        /**
        * 
        * 查詢退款
        * 提交退款申請後,通過該介面查詢退款狀態。退款有一定延時,
        * 用零錢支付的退款20分鐘內到賬,銀行卡支付的退款3個工作日後重新查詢退款狀態。
        * out_refund_no、out_trade_no、transaction_id、refund_id四個引數必填一個
        * @param WxPayData inputObj 提交給查詢退款API的引數
        * @param int timeOut 介面超時時間
        * @throws WxPayException
        * @return 成功時返回,其他拋異常
        */
        public static WxPayData RefundQuery(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/refundquery";
            //檢測必填引數
            if (!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") &&
                !inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id"))
            {
                throw new Exception("退款查詢介面中,out_refund_no、out_trade_no、transaction_id、refund_id四個引數必填一個!");
            }

            inputObj.SetValue("appid", Config.AppID);//公眾賬號ID
            inputObj.SetValue("mch_id", Config.MchID);//商戶號
            inputObj.SetValue("nonce_str", GenerateNonceStr());//隨機字串
            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//簽名型別
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名

            string xml = inputObj.ToXml();

            var start = DateTime.Now;//請求開始時間

            //Log.Debug("WxPayApi", "RefundQuery request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);//呼叫HTTP通訊介面以提交資料到API
            //Log.Debug("WxPayApi", "RefundQuery response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//獲得介面耗時

            //將xml格式的結果轉換為物件以返回
            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }


        /**
        * 下載對賬單
        * @param WxPayData inputObj 提交給下載對賬單API的引數
        * @param int timeOut 介面超時時間
        * @throws WxPayException
        * @return 成功時返回,其他拋異常
        */
        public static WxPayData DownloadBill(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/downloadbill";
            //檢測必填引數
            if (!inputObj.IsSet("bill_date"))
            {