zoukankan      html  css  js  c++  java
  • WechatHelper

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    using System.Web.Configuration;
    using System.Web.Mvc;
    using System.Web.Security;
    using System.Xml;
    using Newtonsoft.Json;
    using Travel.Business.Order;
    using Travel.WeChat.ViewModel.WeiPay;
    
    namespace Travel.WeChat.ToolClass
    {
        public class WeChatPayHelper
        {
            /// <summary>
            /// 微信客户端内部提交支付申请
            /// </summary>
            /// <param name="orderGuid"></param>
            /// <returns></returns>
            [HttpGet]
            public static  string GoToWeCharJSPay(Guid orderGuid, string token)
            {
                var weCharUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                var model = OrderInfoManager.Instance.GetById(orderGuid);
                unifiedorder unOrder = new unifiedorder();
                unOrder.appid = ConfigurationManager.AppSettings["wx_appid"];
                unOrder.mch_id = ConfigurationManager.AppSettings["wx_mch_id"];
                unOrder.nonce_str = Guid.NewGuid().ToString().Replace("-", "");
                unOrder.sign = "";
                unOrder.body = model.ProductName;
                unOrder.out_trade_no = model.OrderCode;
                //payAmountmodel.PayAmount
                unOrder.total_fee = Convert.ToInt32(model.PayAmount * 100);
                unOrder.spbill_create_ip = GetWebClientIp();
                unOrder.notify_url = ConfigurationManager.AppSettings["wechatUrl"] + "WeChatSite/WeChatPay/ProcessingCallback";
                unOrder.trade_type = "JSAPI";
                unOrder.openid = token;
                unOrder.device_info = "WEB";
                var dc = new Dictionary<string, object>()
                {
                    {"appid",unOrder.appid},
                    {"mch_id",unOrder.mch_id},
                    {"total_fee",unOrder.total_fee}, 
                    {"out_trade_no",unOrder.out_trade_no},
                    {"body",unOrder.body},
                    {"notify_url",unOrder.notify_url},
                    {"trade_type",unOrder.trade_type},
                    {"nonce_str",unOrder.nonce_str},
                    {"spbill_create_ip",unOrder.spbill_create_ip},
                    {"openid",unOrder.openid},
                    //{"scene_info","h5_info"}
                };
                dc.Add("sign", GetSignString(dc));//签名
                //2.将参数转换为xml格式
                var sb = new StringBuilder();
                sb.Append("<xml>");
                foreach (var d in dc)
                {
    
                    sb.Append("<" + d.Key + ">" + d.Value + "</" + d.Key + ">");
    
                }
                sb.Append("</xml>");
                //应用场景信息
                //1.创建请求连接
                var request = (HttpWebRequest)WebRequest.Create(weCharUrl);
                //2.设置参数
    
                var data = Encoding.UTF8.GetBytes(sb.ToString());
                //4.设置属性
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                //5.将转换后的参数以文件流的形式写入到请求中
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                //6.声明变量,获取响应
                var response = (HttpWebResponse)request.GetResponse();
                //7.以文件流的方式读取响应结果
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                //
                return responseString;
            }
    
            /// <summary>
            /// 获取客户端ip
            /// </summary>
            /// <returns>返回客户端IP地址</returns>
            public static string GetWebClientIp()
            {
                HttpRequest request = HttpContext.Current.Request;
                string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                string a = request.UserHostAddress;
                if (String.IsNullOrEmpty(result))
                {
                    result = request.ServerVariables["REMOTE_ADDR"];
                }
                if (String.IsNullOrEmpty(result))
                {
                    result = request.UserHostAddress;
                }
                if (String.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                return result;
    
    
    
                //string userIP = "IP";
    
                //try
                //{
                //    if (System.Web.HttpContext.Current == null
                //|| System.Web.HttpContext.Current.Request == null
                //|| System.Web.HttpContext.Current.Request.ServerVariables == null)
                //        return "";
    
                //    string CustomerIP = "";
    
                //    //CDN加速后取到的IP   
                //    CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                //    if (!string.IsNullOrEmpty(CustomerIP))
                //    {
                //        return CustomerIP;
                //    }
    
                //    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
    
                //    if (!String.IsNullOrEmpty(CustomerIP))
                //        return CustomerIP;
    
                //    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                //    {
                //        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                //        if (CustomerIP == null)
                //            CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                //    }
                //    else
                //    {
                //        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    
                //    }
    
                //    if (string.Compare(CustomerIP, "unknown", true) == 0)
                //        return System.Web.HttpContext.Current.Request.UserHostAddress;
                //    return CustomerIP;
                //}
                //catch { }
    
                //return userIP;
                string user_IP;
    
                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
    
                    user_IP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    
                }
    
                else
                {
    
                    user_IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
    
                }
                return user_IP;
            }
            /// <summary>
            /// 获取Sign签名
            /// </summary>
            /// <param name="dic">键值对集合</param>
            /// <returns>字符串类型的签名</returns>
            public static string GetSignString(Dictionary<string, object> dic)
            {
                string key = WebConfigurationManager.AppSettings["wx_key"].ToString(); ;//商户平台 API安全里面设置的KEY  32位长度
                //排序
                dic = dic.OrderBy(d => d.Key).ToDictionary(d => d.Key, d => d.Value);
                //连接字段
                var sign = dic.Aggregate("", (current, d) => current + (d.Key + "=" + d.Value + "&"));
                sign += "key=" + key;
                //MD5
                sign = FormsAuthentication.HashPasswordForStoringInConfigFile(sign, "MD5").ToUpper();
    
                return sign;
            }
            /// <summary>
            /// 时间格式化
            /// </summary>
            /// <param name="date"></param>
            /// <returns></returns>
            public static string Format(DateTime date)
            {
                var dates = "";
                dates += date.Year;
                dates += date.Month;
                dates += date.Date;
                dates += date.Hour;
                dates += date.Minute;
                dates += date.Second;
                return dates;
    
            }
            /// <summary>
            /// 获取时间戳
            /// </summary>
            /// <returns></returns>
            public static string GetTimeStamp()
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return Convert.ToInt64(ts.TotalSeconds).ToString();
            }
    
            #region 微信H5支付,外部浏览器调起支付
            /// <summary>
            /// 根据订单编号,提交订单到微信,获取跳转的地址
            /// </summary>
            /// <param name="OrderGuid">订单编号</param>
            /// <returns>要跳转的地址</returns>
            [HttpPost]
            public static  string PostToWeChar(Guid OrderGuid)
            {
                var model = OrderInfoManager.Instance.GetById(OrderGuid);
                var weCharUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                var si = new h5_info();
                si.type = "Wap";
                si.wap_url = ConfigurationManager.AppSettings["wechatUrl"];
                si.wap_name = "驿马旅行";
                var uo = new unifiedorder();
                uo.appid = ConfigurationManager.AppSettings["wx_appid"];
                uo.mch_id = ConfigurationManager.AppSettings["wx_mch_id"];
                uo.total_fee = Convert.ToInt32(model.PayAmount) * 100;//单位元转换为分
                uo.out_trade_no = model.OrderCode;
                uo.body = model.ProductName;
                uo.notify_url = ConfigurationManager.AppSettings["wechatUrl"] + "WeChatSite/Share/Pay";
                uo.trade_type = "MWEB";//h5的支付类型
                uo.nonce_str = Guid.NewGuid().ToString().Replace("-", ""); ;//随机字符串
                uo.spbill_create_ip = GetWebClientIp();
                var siJson = JsonConvert.SerializeObject(si);
                var dc = new Dictionary<string, object>()
                {
                    {"appid",uo.appid},
                    {"mch_id",uo.mch_id},
                    {"total_fee",uo.total_fee},
                    {"out_trade_no",uo.out_trade_no},
                    {"body",uo.body},
                    {"notify_url",uo.notify_url},
                    {"trade_type",uo.trade_type},
                    {"nonce_str",uo.nonce_str},
                    {"spbill_create_ip",uo.spbill_create_ip},
                    //{"scene_info","h5_info"}
                };
                dc.Add("sign", GetSignString(dc));//签名
                var sb = new StringBuilder();
                sb.Append("<xml>");
                foreach (var d in dc)
                {
                    if (d.Key == "scene_info")
                    {
                        sb.Append("<" + d.Key + ">{"h5_info":");
                        sb.Append(siJson);
                        sb.Append("}</" + d.Key + ">");
                    }
                    else
                    {
                        sb.Append("<" + d.Key + ">" + d.Value + "</" + d.Key + ">");
                    }
                }
                sb.Append("</xml>");
                //1.创建请求连接
                var request = (HttpWebRequest)WebRequest.Create(weCharUrl);
                //2.设置参数
                //var postData = "thing1=hello";
                //postData += "&thing2=world";
                //3.将参数转换编码格式
                var data = Encoding.UTF8.GetBytes(sb.ToString());
                //4.设置属性
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                //5.将转换后的参数以文件流的形式写入到请求中
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                //6.声明变量,获取响应
                var response = (HttpWebResponse)request.GetResponse();
                //7.以文件流的方式读取响应结果
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                var codeId = new XmlDocument();
    
                codeId.LoadXml(responseString);
                //8.读取xml节点的值
                XmlNode xn = codeId.SelectSingleNode("xml/mweb_url");
                var mweb_url = xn.InnerText;
                //9.返回要跳转的url
                return mweb_url;
            }
            #endregion
        }
    }
  • 相关阅读:
    解决Data truncation: Truncated incorrect DOUBLE value: 'xxxxxxx';
    免费LOGO在线生成+免费图床 (亲测可用)
    解决问题:bat脚本手动执行没问题,自动执行不成功
    flask上线部署————“WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.”
    钉钉机器人自动推送测试报告
    Python 自动化测试报告通过钉钉机器人推送通知
    转载:如何将新建的项目完整的提交到gitlab上?
    GIT推送时,空文件夹无法添加
    ddt+excel接口自动化测试-HtmlTestRunner报告中用例名称显示excel中自定义的名称
    Exp9 Web安全基础 20154301仉鑫烨
  • 原文地址:https://www.cnblogs.com/JueXiaoQiang/p/7905435.html
Copyright © 2011-2022 走看看