我把官方的代碼,打包成了 an.wxapi.dll。javascript
裏面主要替換了下注釋。呵呵。而後修改了幾個地方。html
1 namespace an.wxapi 2 { 3 public class WxPayConfig 4 { 5 6 public static string AppKey(string key) 7 { 8 return System.Configuration.ConfigurationManager.AppSettings[key]; 9 } 10 11 /// <summary> 12 /// APPID:綁定支付的APPID(必須配置) 13 /// </summary> 14 public static string APPID { 15 get 16 { 17 return AppKey("wx_appid"); 18 } 19 } 20 21 /// <summary> 22 /// KEY:商戶支付密鑰,參考開戶郵件設置(必須配置) 23 /// </summary> 24 public static string KEY 25 { 26 get { 27 return AppKey("wx_key"); 28 } 29 } 30 /// <summary> 31 /// 商戶號(必須配置) 32 /// </summary> 33 public static string MCHID 34 { 35 get { 36 return AppKey("wx_mchid"); 37 } 38 } 39 /// <summary> 40 /// APPSECRET:公衆賬號secert(僅JSAPI支付的時候須要配置) 41 /// </summary> 42 public static string APPSECRET 43 { 44 get { 45 return AppKey("wx_appsecret"); 46 } 47 } 48 /// <summary> 49 /// 證書路徑,注意應該填寫絕對路徑(僅退款、撤銷訂單時須要) 50 /// </summary> 51 public static string SSLCERT_PATH 52 { 53 get 54 { 55 return AppKey("wx_sslcert_path"); 56 } 57 } 58 /// <summary> 59 /// 證書密碼,默認商戶號爲密碼 60 /// </summary> 61 public static string SSLCERT_PASSWORD 62 { 63 get 64 { 65 return AppKey("wx_sslcert_password"); 66 } 67 } 68 69 /// <summary> 70 /// 支付結果通知回調url,用於商戶接收支付結果 71 /// </summary> 72 public static string NOTIFY_URL 73 { 74 get 75 { 76 return AppKey("wx_notify_url"); 77 } 78 } 79 80 /// <summary> 81 /// 商戶系統後臺機器IP,此參數可手動配置也可在程序中自動獲取 82 /// </summary> 83 public static string IP = "8.8.8.8"; 84 85 /// <summary> 86 /// 代理服務器設置,默認IP和端口號分別爲0.0.0.0和0,此時不開啓代理(若有須要才設置) 87 /// </summary> 88 public static string PROXY_URL = "http://10.152.18.220:8080"; 89 90 /// <summary> 91 ///上報信息配置,測速上報等級,0.關閉上報; 1.僅錯誤時上報; 2.全量上報 92 /// </summary> 93 public static int REPORT_LEVENL = 1; 94 95 /// <summary> 96 /// 日誌等級,0.不輸出日誌;1.只輸出錯誤信息; 2.輸出錯誤和正常信息; 3.輸出錯誤信息、正常信息和調試信息 97 /// </summary> 98 99 public static int LOG_LEVENL 100 { 101 get 102 { 103 string log_levenl = "0"; 104 if(AppKey("log_leven")!="") 105 { 106 log_levenl = AppKey("log_leven"); 107 } 108 return Convert.ToInt32(log_levenl); 109 } 110 } 111 112 } 113 }
只是把靜態的替換成能夠從web.config裏面調用的。java
1 namespace an.wxapi 2 { 3 /// <summary> 4 /// http鏈接基礎類,負責底層的http通訊 5 /// </summary> 6 public class HttpService 7 { 8 9 public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 10 { 11 //直接確認,不然打不開 12 return true; 13 } 14 15 public static string Post(string xml, string url, bool isUseCert, int timeout) 16 { 17 System.GC.Collect();//垃圾回收,回收沒有正常關閉的http鏈接 18 19 string result = "";//返回結果 20 21 HttpWebRequest request = null; 22 HttpWebResponse response = null; 23 Stream reqStream = null; 24 25 try 26 { 27 //設置最大鏈接數 28 ServicePointManager.DefaultConnectionLimit = 200; 29 //設置https驗證方式 30 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 31 { 32 ServicePointManager.ServerCertificateValidationCallback = 33 new RemoteCertificateValidationCallback(CheckValidationResult); 34 } 35 36 /*************************************************************** 37 * 下面設置HttpWebRequest的相關屬性 38 * ************************************************************/ 39 request = (HttpWebRequest)WebRequest.Create(url); 40 41 request.Method = "POST"; 42 request.Timeout = timeout * 1000; 43 44 //設置代理服務器 45 //WebProxy proxy = new WebProxy(); //定義一個網關對象 46 //proxy.Address = new Uri(WxPayConfig.PROXY_URL); //網關服務器端口:端口 47 //request.Proxy = proxy; 48 49 //設置POST的數據類型和長度 50 request.ContentType = "text/xml"; 51 byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); 52 request.ContentLength = data.Length; 53 54 //是否使用證書 55 if (isUseCert) 56 { 57 string path = HttpContext.Current.Request.PhysicalApplicationPath; 58 X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD); 59 request.ClientCertificates.Add(cert); 60 Log.Debug("WxPayApi", "PostXml used cert"); 61 } 62 63 //往服務器寫入數據 64 reqStream = request.GetRequestStream(); 65 reqStream.Write(data, 0, data.Length); 66 reqStream.Close(); 67 68 //獲取服務端返回 69 response = (HttpWebResponse)request.GetResponse(); 70 71 //獲取服務端返回數據 72 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 73 result = sr.ReadToEnd().Trim(); 74 sr.Close(); 75 } 76 catch (System.Threading.ThreadAbortException e) 77 { 78 Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting."); 79 Log.Error("Exception message: {0}", e.Message); 80 System.Threading.Thread.ResetAbort(); 81 } 82 catch (WebException e) 83 { 84 Log.Error("HttpService", e.ToString()); 85 if (e.Status == WebExceptionStatus.ProtocolError) 86 { 87 Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode); 88 Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription); 89 } 90 throw new WxPayException(e.ToString()); 91 } 92 catch (Exception e) 93 { 94 Log.Error("HttpService", e.ToString()); 95 throw new WxPayException(e.ToString()); 96 } 97 finally 98 { 99 //關閉鏈接和流 100 if (response != null) 101 { 102 response.Close(); 103 } 104 if (request != null) 105 { 106 request.Abort(); 107 } 108 } 109 return result; 110 } 111 112 /// <summary> 113 /// 處理http GET請求,返回數據 114 /// </summary> 115 /// <param name="url">請求的url地址</param> 116 /// <returns>http GET成功後返回的數據,失敗拋WebException異常</returns> 117 public static string Get(string url) 118 { 119 System.GC.Collect(); 120 string result = ""; 121 122 HttpWebRequest request = null; 123 HttpWebResponse response = null; 124 125 //請求url以獲取數據 126 try 127 { 128 //設置最大鏈接數 129 ServicePointManager.DefaultConnectionLimit = 200; 130 //設置https驗證方式 131 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 132 { 133 ServicePointManager.ServerCertificateValidationCallback = 134 new RemoteCertificateValidationCallback(CheckValidationResult); 135 } 136 137 /*************************************************************** 138 * 下面設置HttpWebRequest的相關屬性 139 * ************************************************************/ 140 request = (HttpWebRequest)WebRequest.Create(url); 141 142 request.Method = "GET"; 143 144 //設置代理 145 //WebProxy proxy = new WebProxy(); 146 //proxy.Address = new Uri(WxPayConfig.PROXY_URL); 147 //request.Proxy = proxy; 148 149 //獲取服務器返回 150 response = (HttpWebResponse)request.GetResponse(); 151 152 //獲取HTTP返回數據 153 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 154 result = sr.ReadToEnd().Trim(); 155 sr.Close(); 156 } 157 catch (System.Threading.ThreadAbortException e) 158 { 159 Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting."); 160 Log.Error("Exception message: {0}", e.Message); 161 System.Threading.Thread.ResetAbort(); 162 } 163 catch (WebException e) 164 { 165 Log.Error("HttpService", e.ToString()); 166 if (e.Status == WebExceptionStatus.ProtocolError) 167 { 168 Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode); 169 Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription); 170 } 171 throw new WxPayException(e.ToString()); 172 } 173 catch (Exception e) 174 { 175 Log.Error("HttpService", e.ToString()); 176 throw new WxPayException(e.ToString()); 177 } 178 finally 179 { 180 //關閉鏈接和流 181 if (response != null) 182 { 183 response.Close(); 184 } 185 if (request != null) 186 { 187 request.Abort(); 188 } 189 } 190 return result; 191 } 192 } 193 }
主要註釋掉了設置代理服務器,基本上就註釋掉這個就能夠用了。web
由於我只須要作微信裏面的網頁支付,其餘不少功能我都不須要。因此。BIN文件夾,也只須要LitJSON.dll,RestSharp.dll,an.wxapi.dll(我上面打包的)api
1 <%@ Page Language="C#" Inherits="an.web" %> 2 <%@ Import Namespace="an.wxapi" %> 3 <script runat="server"> 4 protected override void OnLoad(EventArgs e) 5 { 6 JsApiPay jsApiPay = new JsApiPay(this); 7 jsApiPay.GetOpenidAndAccessToken(); 8 wx_openid = jsApiPay.openid; 9 } 10 </script> 11 <!DOCTYPE html> 12 <html xmlns="http://www.w3.org/1999/xhtml"> 13 <head> 14 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 15 <title></title> 16 </head> 17 <body> 18 <h2>商品一:價格爲:1分</h2> 19 <p><a href="JsApiPayPage.aspx?openid=<%=wx_openid %>&total_fee=1&showwxpaytitle=1">去支付</a></p> 20 </body> 21 </html>
我比較懶,因此,我通常不用.cs文件,我喜歡寫到一塊兒。呵呵,(這樣有個好處,不須要編譯,便可運行。)服務器
基本上是拿官方的過來,沒怎麼修改。微信
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 Log.Info(this.GetType().ToString(), "page load"); 4 if (!IsPostBack) 5 { 6 JsApiPay jsApiPay = new JsApiPay(this); 7 try 8 { 9 //調用【網頁受權獲取用戶信息】接口獲取用戶的openid和access_token 10 jsApiPay.GetOpenidAndAccessToken(); 11 12 //獲取收貨地址js函數入口參數 13 //wxEditAddrParam = jsApiPay.GetEditAddressParameters(); 14 ViewState["openid"] = jsApiPay.openid; 15 } 16 catch (Exception ex) 17 { 18 Response.Write("<span style='color:#FF0000;font-size:20px'>" + "頁面加載出錯,請重試" +ex.Message +"</span>"); 19 //Button1.Visible = false; 20 //Button2.Visible = false; 21 //Label1.Visible = false; 22 //Label2.Visible = false; 23 } 24 } 25 }
官方用的是ViewState這玩意,會產生龐大的垃圾代碼,(反正我也不知道這玩意,有啥子用)app
個人作法是:ide
1 namespace an 2 { 3 public class web : System.Web.UI.Page 4 { 5 public string wx_openid { get; set; } 6 public string wxJsApiParam { get; set; } 7 } 8 }
直接在an.web裏面定義下屬性,不完啦。函數
1 <%@ Page Language="C#" Inherits="an.web" %> 2 <%@ Import Namespace="an.wxapi" %> 3 <script runat="server"> 4 protected override void OnLoad(EventArgs e) 5 { 6 string openid = Request.QueryString["openid"]; 7 string total_fee = Request.QueryString["total_fee"]; 8 9 JsApiPay jsApiPay = new JsApiPay(this); 10 jsApiPay.openid = openid; 11 jsApiPay.total_fee = int.Parse(total_fee); 12 13 WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(); 14 wxJsApiParam = jsApiPay.GetJsApiParameters();//獲取H5調起JS API參數 15 } 16 </script> 17 <!DOCTYPE html> 18 <html xmlns="http://www.w3.org/1999/xhtml"> 19 <head> 20 <meta http-equiv="content-type" content="text/html;charset=utf-8"/> 21 <meta name="viewport" content="width=device-width, initial-scale=1"/> 22 <title>微信支付樣例-JSAPI支付</title> 23 </head> 24 25 <script type="text/javascript"> 26 27 //調用微信JS api 支付 28 function jsApiCall() 29 { 30 WeixinJSBridge.invoke( 31 'getBrandWCPayRequest', 32 <%=wxJsApiParam%>,//josn串 33 function (res) 34 { 35 WeixinJSBridge.log(res.err_msg); 36 alert(res.err_code + res.err_desc + res.err_msg); 37 } 38 ); 39 } 40 41 function callpay() 42 { 43 if (typeof WeixinJSBridge == "undefined") 44 { 45 if (document.addEventListener) 46 { 47 document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); 48 } 49 else if (document.attachEvent) 50 { 51 document.attachEvent('WeixinJSBridgeReady', jsApiCall); 52 document.attachEvent('onWeixinJSBridgeReady', jsApiCall); 53 } 54 } 55 else 56 { 57 jsApiCall(); 58 } 59 } 60 61 </script> 62 63 <body> 64 <input type="button" onclick="callpay()" value="馬上支付" /> 65 </body> 66 </html>
1 <%@ Page Language="C#" Inherits="an.web" %> 2 <%@ Import Namespace="an.wxapi" %> 3 <script runat="server"> 4 protected override void OnLoad(EventArgs e) 5 { 6 ResultNotify resultNotify = new ResultNotify(this); 7 resultNotify.ProcessNotify(); 8 } 9 </script> 10 <!DOCTYPE html> 11 <html xmlns="http://www.w3.org/1999/xhtml"> 12 <head> 13 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 14 <title></title> 15 </head> 16 <body> 17 18 </body> 19 </html>
很簡單咯...
an.wxapi.dll 下載地址:http://files.cnblogs.com/files/ancms/an.wxapi.rar
本人很菜,但願以微薄之力幫助你們。
再次感謝:smallerpig