c#微信掃碼支付,完整版。包括回調

  1、我們需要用到的類,下載一個微信sdk。sdk中有相關的工具類鏈接地址爲:

  https://pay.weixin.qq.com/wiki/doc/api/download/WxPayAPI_CS_v3.zip

  2、如果覺得不想下載沒有關係,我貼代碼

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace WxPayTest.WxHelper
{
    public class HttpService
    {
        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.Method = "POST";
                request.Timeout = timeout * 1000;

                //設置代理服務器
                WebProxy proxy = new WebProxy();                          //定義一個網關對象
                proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //網關服務器端口:端口
                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 + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);
                    request.ClientCertificates.Add(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)
            {
              
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
              
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                  
                }
                throw new WxPayException(e.ToString());
            }
            catch (Exception e)
            {
              
                throw new WxPayException(e.ToString());
            }
            finally
            {
                //關閉連接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }


        /// <summary>
        /// 請求Url,發送數據
        /// </summary>
        public static string PostUrl(string url, string postData)
        {
            byte[] data = Encoding.UTF8.GetBytes(postData);

            // 設置參數
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            Stream outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();

            //發送請求並獲取相應迴應數據
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序纔開始向目標網頁發送Post請求
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回結果網頁(html)代碼
            string content = sr.ReadToEnd();
            return content;
        }




        /// <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.Method = "GET";

                //設置代理
                WebProxy proxy = new WebProxy();
                proxy.Address = new Uri(WxPayConfig.PROXY_URL);
                request.Proxy = proxy;

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

                //獲取HTTP返回數據
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
               
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
               
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                   
                }
                throw new WxPayException(e.ToString());
            }
            catch (Exception e)
            {
              
                throw new WxPayException(e.ToString());
            }
            finally
            {
                //關閉連接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WxPayTest.WxHelper
{
    public class NativePay
    {
      
        /**
        * 生成直接支付url,支付url有效期爲2小時,模式二
        * @param productId 商品ID
        * @return 模式二URL
        */
        public string GetPayUrl(string productId)
        {
           

            WxPayData data = new WxPayData();
            data.SetValue("body", "test");//商品描述
            data.SetValue("attach", "test");//附加數據
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//隨機字符串
            data.SetValue("total_fee", 1);//總金額
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始時間
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易結束時間
            data.SetValue("goods_tag", "jjj");//商品標記
            data.SetValue("trade_type", "NATIVE");//交易類型
            data.SetValue("product_id", productId);//商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);//調用統一下單接口
            string url = result.GetValue("code_url").ToString();//獲得統一下單接口返回的二維碼鏈接

          
            return url;
        }

        /**
        * 參數數組轉換爲url格式
        * @param map 參數名與參數值的映射表
        * @return URL字符串
        */
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff;
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace WxPayTest.WxHelper
{
    public class WeiXinHelper
    {
        /**
       * 生成直接支付url,支付url有效期爲2小時,模式二
       * @param productId 商品ID
       * @return 模式二URL
       */
        public string GetPayUrl(string productId)
        {
           

            WxPayData data = new WxPayData();
            data.SetValue("body", "test");//商品描述
            data.SetValue("attach", "test");//附加數據
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//隨機字符串
            data.SetValue("total_fee", 1);//總金額
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始時間
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易結束時間
            data.SetValue("goods_tag", "jjj");//商品標記
            data.SetValue("trade_type", "NATIVE");//交易類型
            data.SetValue("product_id", productId);//商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);//調用統一下單接口
            string url = result.GetValue("code_url").ToString();//獲得統一下單接口返回的二維碼鏈接

          
            return url;
        }

        /**
        * 參數數組轉換爲url格式
        * @param map 參數名與參數值的映射表
        * @return URL字符串
        */
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WxPayTest.WxHelper
{
    public class WxPayApi
    {
        /**
        * 
        * 統一下單
        * @param WxPaydata inputObj 提交給統一下單API的參數
        * @param int timeOut 超時時間
        * @throws WxPayException
        * @return 成功時返回,其他拋異常
        */
        public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 600)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //檢測必填參數
            if (!inputObj.IsSet("out_trade_no"))
            {
                throw new WxPayException("缺少統一支付接口必填參數out_trade_no!");
            }
            else if (!inputObj.IsSet("body"))
            {
                throw new WxPayException("缺少統一支付接口必填參數body!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new WxPayException("缺少統一支付接口必填參數total_fee!");
            }
            else if (!inputObj.IsSet("trade_type"))
            {
                throw new WxPayException("缺少統一支付接口必填參數trade_type!");
            }

            //關聯參數
            if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
            {
                throw new WxPayException("統一支付接口中,缺少必填參數openid!trade_type爲JSAPI時,openid爲必填參數!");
            }
            if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
            {
                throw new WxPayException("統一支付接口中,缺少必填參數product_id!trade_type爲JSAPI時,product_id爲必填參數!");
            }

            //異步通知url未設置,則使用配置文件中的url
            if (!inputObj.IsSet("notify_url"))
            {
                inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//異步通知url
            }

            inputObj.SetValue("appid", WxPayConfig.APPID);//公衆賬號ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商戶號
            inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//終端ip	  	    
            inputObj.SetValue("nonce_str", GenerateNonceStr());//隨機字符串

            //簽名
            inputObj.SetValue("sign", inputObj.MakeSign());
            string xml = inputObj.ToXml();

            var start = DateTime.Now;

          
            //string response = HttpService.Post(xml, url, false, timeOut);
            string response = HttpService.PostUrl(url, xml);
           
            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

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

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

            return result;
        }


        /**
      * 
      * 測速上報
      * @param string interface_url 接口URL
      * @param int timeCost 接口耗時
      * @param WxPayData inputObj參數數組
      */
        private static void ReportCostTime(string interface_url, int timeCost, WxPayData inputObj)
        {
            //如果不需要進行上報
            if (WxPayConfig.REPORT_LEVENL == 0)
            {
                return;
            }

            //如果僅失敗上報
            if (WxPayConfig.REPORT_LEVENL == 1 && inputObj.IsSet("return_code") && inputObj.GetValue("return_code").ToString() == "SUCCESS" &&
             inputObj.IsSet("result_code") && inputObj.GetValue("result_code").ToString() == "SUCCESS")
            {
                return;
            }

            //上報邏輯
            WxPayData data = new WxPayData();
            data.SetValue("interface_url", interface_url);
            data.SetValue("execute_time_", timeCost);
            //返回狀態碼
            if (inputObj.IsSet("return_code"))
            {
                data.SetValue("return_code", inputObj.GetValue("return_code"));
            }
            //返回信息
            if (inputObj.IsSet("return_msg"))
            {
                data.SetValue("return_msg", inputObj.GetValue("return_msg"));
            }
            //業務結果
            if (inputObj.IsSet("result_code"))
            {
                data.SetValue("result_code", inputObj.GetValue("result_code"));
            }
            //錯誤代碼
            if (inputObj.IsSet("err_code"))
            {
                data.SetValue("err_code", inputObj.GetValue("err_code"));
            }
            //錯誤代碼描述
            if (inputObj.IsSet("err_code_des"))
            {
                data.SetValue("err_code_des", inputObj.GetValue("err_code_des"));
            }
            //商戶訂單號
            if (inputObj.IsSet("out_trade_no"))
            {
                data.SetValue("out_trade_no", inputObj.GetValue("out_trade_no"));
            }
            //設備號
            if (inputObj.IsSet("device_info"))
            {
                data.SetValue("device_info", inputObj.GetValue("device_info"));
            }

            try
            {
                Report(data);
            }
            catch (WxPayException ex)
            {
                //不做任何處理
            }
        }


        /**
	    * 
	    * 測速上報接口實現
	    * @param WxPayData inputObj 提交給測速上報接口的參數
	    * @param int timeOut 測速上報接口超時時間
	    * @throws WxPayException
	    * @return 成功時返回測速上報接口返回的結果,其他拋異常
	    */
        public static WxPayData Report(WxPayData inputObj, int timeOut = 1)
        {
            string url = "https://api.mch.weixin.qq.com/payitil/report";
            //檢測必填參數
            if (!inputObj.IsSet("interface_url"))
            {
                throw new WxPayException("接口URL,缺少必填參數interface_url!");
            }
            if (!inputObj.IsSet("return_code"))
            {
                throw new WxPayException("返回狀態碼,缺少必填參數return_code!");
            }
            if (!inputObj.IsSet("result_code"))
            {
                throw new WxPayException("業務結果,缺少必填參數result_code!");
            }
            if (!inputObj.IsSet("user_ip"))
            {
                throw new WxPayException("訪問接口IP,缺少必填參數user_ip!");
            }
            if (!inputObj.IsSet("execute_time_"))
            {
                throw new WxPayException("接口耗時,缺少必填參數execute_time_!");
            }

            inputObj.SetValue("appid", WxPayConfig.APPID);//公衆賬號ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商戶號
            inputObj.SetValue("user_ip", WxPayConfig.IP);//終端ip
            inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss"));//商戶上報時間	 
            inputObj.SetValue("nonce_str", GenerateNonceStr());//隨機字符串
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名
            string xml = inputObj.ToXml();

         

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

          

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

        /**
        * 根據當前系統時間加隨機序列來生成訂單號
         * @return 訂單號
        */
        public static string GenerateOutTradeNo()
        {
            var ran = new Random();
            return string.Format("{0}{1}{2}", WxPayConfig.MCHID, DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(999));
        }

        /**
        * 生成時間戳,標準北京時間,時區爲東八區,自1970年1月1日 0點0分0秒以來的秒數
         * @return 時間戳
        */
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /**<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WxPayTest.WxHelper
{
    /**
    * 	配置賬號信息
    */
    public class WxPayConfig
    {
        //=======【基本信息設置】=====================================
        /* 微信公衆號信息配置
        * APPID:綁定支付的APPID(必須配置)
        * MCHID:商戶號(必須配置)
        * KEY:商戶支付密鑰,參考開戶郵件設置(必須配置)
        * APPSECRET:公衆帳號secert(僅JSAPI支付的時候需要配置)
        */
        public const string APPID = "11111111111111"; //需要自己提供我就不提供
        public const string MCHID = "11111111111111";//需要自己提供我就不提供
        public const string KEY = "11111111111111";//需要自己提供我就不提供
        public const string APPSECRET = "11111111111111";//需要自己提供我就不提供

        //=======【證書路徑設置】===================================== 
        /* 證書路徑,注意應該填寫絕對路徑(僅退款、撤銷訂單時需要)
        */
        public const string SSLCERT_PATH = "cert/apiclient_cert.p12";
        public const string SSLCERT_PASSWORD = "1233410002";



        //=======【支付結果通知url】===================================== 
        /* 支付結果通知回調url,用於商戶接收支付結果
        */
        public const string NOTIFY_URL = "http://paysdk.weixin.qq.com/example/ResultNotifyPage.aspx";  //需要寫自己的回調地址,方便處理

        //=======【商戶系統後臺機器IP】===================================== 
        /* 此參數可手動配置也可在程序中自動獲取
        */
        public const string IP = "8.8.8.8";


        //=======【代理服務器設置】===================================
        /* 默認IP和端口號分別爲0.0.0.0和0,此時不開啓代理(如有需要才設置)
        */
        public const string PROXY_URL = "http://10.152.18.220:8080";

        //=======【上報信息配置】===================================
        /* 測速上報等級,0.關閉上報; 1.僅錯誤時上報; 2.全量上報
        */
        public const int REPORT_LEVENL = 1;

        //=======【日誌級別】===================================
        /* 日誌等級,0.不輸出日誌;1.只輸出錯誤信息; 2.輸出錯誤和正常信息; 3.輸出錯誤信息、正常信息和調試信息
        */
        public const int LOG_LEVENL = 0;
    }
}

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Xml;

namespace WxPayTest.WxHelper
{
    /// <summary>
    /// 微信支付協議接口數據類,所有的API接口通信都依賴這個數據結構,
    /// 在調用接口之前先填充各個字段的值,然後進行接口通信,
    /// 這樣設計的好處是可擴展性強,用戶可隨意對協議進行更改而不用重新設計數據結構,
    /// 還可以隨意組合出不同的協議數據包,不用爲每個協議設計一個數據包結構
    /// </summary>
    public class WxPayData
    {
        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)
            {
               
                throw new WxPayException("WxPayData數據爲空!");
            }

            string xml = "<xml>";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                //字段值不能爲null,會影響後續流程
                if (pair.Value == 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類型不能含有其他數據類型
                {
                   
                    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))
            {
               
                throw new WxPayException("將空的xml串轉換爲WxPayData不合法!");
            }

            XmlDocument xmlDoc = new XmlDocument();
            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)
                {
                  
                    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 =JsonConvert.SerializeObject(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)
                {
                  
                    throw new WxPayException("WxPayData內部含有值爲null的字段!");
                }

                str += string.Format("{0}={1}<br>", pair.Key, pair.Value.ToString());
            }
          
            return str;
        }

        /**
        * @生成簽名,詳見簽名生成算法
        * @return 簽名, sign字段不參加簽名
        */
        public string MakeSign()
        {
            //轉url格式
            string str = ToUrl();
            //在string後加入API KEY
            str += "&key=" + WxPayConfig.KEY;
            //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();
        }

        /**
        * 
        * 檢測簽名是否正確
        * 正確返回true,錯誤拋異常
        */
        public bool CheckSign()
        {
            //如果沒有設置簽名,則跳過檢測
            if (!IsSet("sign"))
            {
                //"WxPayData簽名存在但不合法!"
                return false;
            }
            //如果設置了簽名但是簽名爲空,則拋異常
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                //"WxPayData簽名存在但不合法!"
                return false;
            }

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

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

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WxPayTest.WxHelper
{
    public class WxPayException : Exception
    {
        public WxPayException(string msg)
            : base(msg)
        {

        }
    }
}

* 生成隨機串,隨機串包含字母或數字 * @return 隨機串 */ public static string GenerateNonceStr() { return Guid.NewGuid().ToString().Replace("-", ""); } }}


3、所有的工具類完成了,下面就開始調用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WxPayTest.WxHelper;

namespace WxPayTest.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/
        public ActionResult Index()
        {

            NativePay nativePay = new NativePay();
            //生成掃碼支付url
            string url2 = nativePay.GetPayUrl("123456789");
            ViewBag.url = url2;
            return View();
            
        }
	}
}

4、頁面操作,因爲之前的調用微信給我們有用的東西就是一個二維碼鏈接,我們還得把這個連接轉換爲二維碼。
jquery.qrcode.min.js 可以百度下載,我這裏提供一個連接:http://download.csdn.net/detail/zuozhiyoulaisam/8117785

    

@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.qrcode.min.js"></script>

<h2>Index</h2>
<div id="code"></div>
<script>
    var urlText = '@ViewBag.url';
    jQuery('#code').qrcode("" + urlText + "");
</script>




  5、ok你可以完整的使用微信掃碼支付了,回調操作後續在寫(回調鏈接地址)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章