微信小程序支付功能 C# .NET开发

时间:2025-03-04 10:37:55
  • <%@ WebHandler Language="C#" Class="jiesuan" %>  
  •   
  • using System;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using ;  
  • using .X509Certificates;  
  • using ;  
  • using ;  
  •   
  • public class jiesuan : IHttpHandler  
  • {  
  •   
  •     public void ProcessRequest(HttpContext context)  
  •     {  
  •          = "text/plain";  
  •         // string openid = ["openid"];  
  •         // string ordertime = ["ordertime"];  
  •         string orderid = ["order_id"];  
  •         string appid = ["appid"];  
  •         string secret = ["secret"];  
  •         string key = ["key"];  
  •         string mch_id = ["mch_id"];  
  •         string ip = ["ip"];  
  •         string PayResulturl = ["PayResulturl"];  
  •         //string roomid = ["roomid"];  
  •         string aa = "私密自助棋牌室-退款";商品描述交易字段格式根据不同的应用场景按照以下格式:APP——需传入应用市场上的APP名字-实际商品名称,天天爱消除-游戏充值。  
  •   
  •         string strcode = aa;  
  •         byte[] buffer = Encoding.(strcode);  
  •         string body = Encoding.(buffer, 0, );  
  •         DateTime timestart;  
  •         int totalhour;  
  •         float totalfee;  
  •         float pay_price;  
  •         float refund_fee;  
  •         string out_refund_no;  
  •         int roomid;  
  •         string openid;  
  •         //string totalfee = ["totalfee"];  
  •         string output = "";  
  •         string signapp;  
  •         DataSet orderhistory;  
  •         if ((["order_id"] != null) && (["order_id"] != ""))  
  •         {  
  •             .order_history oh = new .order_history();  
  •             orderhistory = (" order_margin:0px; padding:0px; border:none; background-color:inherit"> + orderid + "");  
  •             pay_price = ([0].Rows[0]["pay_price"]);  
  •             roomid = Convert.ToInt32([0].Rows[0]["room_id"]);  
  •             openid = [0].Rows[0]["openid"].ToString();  
  •              Random = new ();  
  •   
  •   
  •             timestart = ([0].Rows[0]["order_timestart"]);//订单开始时间  
  •   
  •             TimeSpan ts =  - timestart; //时间差的绝对值    
  •             totalhour = Convert.ToInt32();//间隔小时数  
  •   
  •             totalfee = totalhour * ([0].Rows[0]["price"]);  
  •             out_refund_no = roomid + ("yyyyMMddHHmmssfff") + (999).ToString();  
  •             refund_fee = totalfee - pay_price;  
  •             var dic = new Dictionary<stringstring>  
  • {  
  •     {"appid", appid},  
  •     {"mch_id", mch_id},  
  •     {"nonce_str", GetRandomString(20)/*().ToString()*/},  
  •      {"op_user_id",mch_id},  
  •       {"out_refund_no",out_refund_no},//商户退款号  
  •     {"out_trade_no",[0].Rows[0]["out_trade_no"].ToString()},//商户自己的订单号码  
  •     {"refund_fee",/*refund_fee.ToString()*/"1"},//退款金额  
  •     {"total_fee",[0].Rows[0]["pay_price"].ToString()},//订单金额  
  •     
  •   
  • };  
  •   
  •             //加入签名  
  •             ("sign", GetSignString(dic));  
  •   
  •             var sb = new StringBuilder();  
  •             ("<xml>");  
  •   
  •   
  •             foreach (var d in dic)  
  •             {  
  •                 ("<" +  + ">" +  + "</" +  + ">");  
  •             }  
  •             ("</xml>");  
  •             var xml = new XmlDocument();  
  •             //  (GetPostString("/pay/unifiedorder", ()));  
  •             CookieCollection coo = new CookieCollection();  
  •             Encoding en = ("UTF-8");  
  •   
  •             HttpWebResponse response = CreatePostHttpResponse("/secapi/pay/refund", (), en);  
  •             //打印返回值  
  •             Stream stream = ();   //获取响应的字符串流  
  •             StreamReader sr = new StreamReader(stream); //创建一个stream读取流  
  •             string html = ();   //从头读到尾,放到字符串html  
  •                                             //(html);  
  •             (html);  
  •             //对请求返回值 进行处理  
  •   
  •             var root = ;  
  •   
  •             DataSet ds = new DataSet();  
  •             StringReader stram = new StringReader(html);  
  •             XmlTextReader reader = new XmlTextReader(stram);  
  •             (reader);  
  •             string return_code = [0].Rows[0]["return_code"].ToString();  
  •             string return_mesage = [0].Rows[0]["return_msg"].ToString();  
  •             if (return_code.ToUpper() == "SUCCESS")  
  •             {  
  •                 //通信成功  
  •                 string result_code = [0].Rows[0]["result_code"].ToString();//业务结果  
  •                 if (result_code.ToUpper() == "SUCCESS")  
  •                 {  
  •                     if ((["order_id"] != null) && (["order_id"] != ""))  
  •                     {  
  •                         //更新订单信息  
  •                          model = new ();  
  •   
  •                         .order_history oh1 = new .order_history();  
  •                          b = new ();  
  •   
  •                         .order_history bll = new .order_history();  
  •                         model = (roomid);  
  •                         oh1 = (Convert.ToInt32(orderid));  
  •   
  •                         oh1.order_timeend = ;  
  •                         oh1.out_refund_no = out_refund_no;  
  •                         oh1.refund_fee = (refund_fee);  
  •   
  •                         (oh1);  
  •   
  •                         model.attribute1 = "0";//0空闲  1 使用中  
  •                         model.room_id =Convert.ToInt32(oh1.room_id);  
  •   
  •                         (model);//更新棋牌室使用状态  
  •                         var res = new Dictionary<stringstring>  
  • {  
  •     {"out_refund_no", out_refund_no},  
  •     {"return_mesage", return_mesage},  
  •     {"return_code", return_code},  
  •     {"refund_fee",refund_fee.ToString() },  
  •     {"order_timeend", oh1.order_timeend.ToString() },  
  •     {"order_id", oh1.order_id.ToString() }  
  •   
  • };  
  •                         signapp = (res);  
  •                         (signapp);  
  •                     }  
  •   
  •                 }  
  •             }  
  •   
  •   
  •   
  •   
  •         }  
  •       //  (output);  
  •     }  
  •   
  •     public bool IsReusable  
  •     {  
  •         get  
  •         {  
  •             return false;  
  •         }  
  •     }  
  •   
  •     public string GetMd5Hash(String input)  
  •     {  
  •         if (input == null)  
  •         {  
  •             return null;  
  •         }  
  •   
  •         MD5 md5Hash = ();  
  •   
  •         // 将输入字符串转换为字节数组并计算哈希数据    
  •         byte[] data = (Encoding.(input));  
  •   
  •         // 创建一个 Stringbuilder 来收集字节并创建字符串    
  •         StringBuilder sBuilder = new StringBuilder();  
  •   
  •         // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串    
  •         for (int i = 0; i < ; i++)  
  •         {  
  •             (data[i].ToString());  
  •         }  
  •   
  •         // 返回十六进制字符串    
  •         return ();  
  •     }  
  •     /// <summary>    
  •     /// 对象序列化成 XML String    
  •     /// </summary>    
  •     public static string XmlSerialize<T>(T obj)  
  •     {  
  •         string xmlString = string.Empty;  
  •         XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));  
  •         using (MemoryStream ms = new MemoryStream())  
  •         {  
  •             (ms, obj);  
  •             xmlString = Encoding.(());  
  •         }  
  •         return xmlString;  
  •     }  
  •     /// <summary>  
  •     /// 从字符串里随机得到,规定个数的字符串.  
  •     /// </summary>  
  •     /// <param name="allChar"></param>  
  •     /// <param name="CodeCount"></param>  
  •     /// <returns></returns>  
  •     public static string GetRandomString(int CodeCount)  
  •     {  
  •         string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";  
  •         string[] allCharArray = (',');  
  •         string RandomCode = "";  
  •         int temp = -1;  
  •         Random rand = new Random();  
  •         for (int i = 0; i < CodeCount; i++)  
  •         {  
  •             if (temp != -1)  
  •             {  
  •                 rand = new Random(temp * i * ((int)));  
  •             }  
  •             int t = ( - 1);  
  •             while (temp == t)  
  •             {  
  •                 t = ( - 1);  
  •             }  
  •             temp = t;  
  •             RandomCode += allCharArray[t];  
  •         }  
  •   
  •         return RandomCode;  
  •     }  
  •   
  •   
  •     public static string GetWebClientIp()  
  •     {  
  •         string userIP = "IP";  
  •   
  •         try  
  •         {  
  •             if ( == null  
  •         ||  == null  
  •         ||  == null)  
  •                 return "";  
  •   
  •             string CustomerIP = "";  
  •   
  •             //CDN加速后取到的IP     
  •             CustomerIP = ["Cdn-Src-Ip"];  
  •             if (!string.IsNullOrEmpty(CustomerIP))  
  •             {  
  •                 return CustomerIP;  
  •             }  
  •   
  •             CustomerIP = ["HTTP_X_FORWARDED_FOR"];  
  •   
  •   
  •             if (!(CustomerIP))  
  •                 return CustomerIP;  
  •   
  •             if (["HTTP_VIA"] != null)  
  •             {  
  •                 CustomerIP = ["HTTP_X_FORWARDED_FOR"];  
  •                 if (CustomerIP == null)  
  •                     CustomerIP = ["REMOTE_ADDR"];  
  •             }  
  •             else  
  •             {  
  •                 CustomerIP = ["REMOTE_ADDR"];  
  •   
  •             }  
  •   
  •             if (string.Compare(CustomerIP, "unknown"true) == 0)  
  •                 return ;  
  •             return CustomerIP;  
  •         }  
  •         catch { }  
  •   
  •         return userIP;  
  •     }  
  •   
  •   
  •   
  •   
  •     private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)  
  •     {  
  •         return true//总是接受     
  •     }  
  •   
  •     public static HttpWebResponse CreatePostHttpResponse(string url, string datas, Encoding charset)  
  •     {  
  •        // string cert = @"C:\apiclient_cert.p12";  
  •        string cert =("/apiclient_cert.p12");  //证书已上传到网站根目录,注意安全性问题  
  •         string password = ["mch_id"];  
  •        
  •      //   X509Certificate cer = new X509Certificate(cert, password);//经过测试,这个发布到IIS后,发起微信退款时会引起<span style="color:rgb(255,0,0);font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;font-size:13px;">"基础连接已经关闭: 连接被意外关闭"</span>  
  •           
  •   
  •             X509Certificate2 cer = new X509Certificate2(cert, password,  | );  
  •   
  •    
  •   
  •         HttpWebRequest request = null;  
  •         //HTTPSQ请求  
  •          = new RemoteCertificateValidationCallback(CheckValidationResult);  
  •         request = (url) as HttpWebRequest;  
  •   
  •          = HttpVersion.Version10;  
  •         (cer);//add by sui 20170505  
  •          = "POST";  
  •          = "application/x-www-form-urlencoded";  
  •   
  •   
  •         //如果需要POST数据     
  •         //if (!(parameters == null ||  == 0))  
  •         //{  
  •         StringBuilder buffer = new StringBuilder();  
  •         //int i = 0;  
  •         //foreach (string key in )  
  •         //{  
  •         //    if (i > 0)  
  •         //    {  
  •         //        ("&{0}={1}", key, parameters[key]);  
  •         //    }  
  •         //    else  
  •         //    {  
  •         //        ("{0}={1}", key, parameters[key]);  
  •         //    }  
  •         //    i++;  
  •         //}  
  •         (datas);  
  •         byte[] data = (());  
  •         using (Stream stream = ())  
  •         {  
  •             (data, 0, );  
  •         }  
  •         //}  
  •   
  •         return () as HttpWebResponse;  
  •   
  •   
  •     }  
  •   
  •   
  •     public string GetSignString(Dictionary<stringstring> dic)  
  •     {  
  •         string key = ["key"].ToString();//商户平台 API安全里面设置的KEY  32位长度  
  •                                                                                                     //排序  
  •         dic = (d => ).ToDictionary(d => , d => );  
  •         //连接字段  
  •         var sign = ("", (current, d) => current + ( + "=" +  + "&"));  
  •         sign += "key=" + key;  
  •         //MD5  
  •         // sign = (sign, "MD5").ToUpper();  
  •         .MD5 md5 = .();  
  •         sign = ((Encoding.(sign))).Replace("-"null);  
  •         return sign;  
  •     }  
  •   
  •   
  •     /// <summary>    
  •     /// 获取时间戳    
  •     /// </summary>    
  •     /// <returns></returns>    
  •     public static string GetTimeStamp()  
  •     {  
  •         TimeSpan ts =  - new DateTime(1970, 1, 1, 0, 0, 0, 0);  
  •         return Convert.ToInt64().ToString();  
  •     }  
  •   
  • }