首页 > 其他分享 >获取微信支付码url

获取微信支付码url

时间:2023-01-02 17:11:06浏览次数:34  
标签:return string url 微信 获取 WxPayData new inputObj public

(1)获取微信支付码url主方法

        /// <summary>
        /// 获取微信支付二维码
        /// </summary>
        /// <param name="log">日志</param>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public static string GetPayUrl(string orderId, decimal totalPrice)
        {
            //errMsg = "";
            //Log4Net.Log4Net.Info(log, "订单号:" + orderId + "发起Native的第二种支付方式");
            WxPayData data = new WxPayData();
            data.SetValue("body", "");//商品描述
            data.SetValue("attach", "");//附加数据
            data.SetValue("out_trade_no", orderId);//随机字符串
            data.SetValue("total_fee", Convert.ToInt32(totalPrice * 100));//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间,前端二维码有效期半小时
            data.SetValue("goods_tag", "");//商品标记(可根据业务随便填)
            data.SetValue("trade_type", "NATIVE");//交易类型
            data.SetValue("product_id", orderId);//商品ID
            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string url = string.Empty;
            if (result.GetValue("return_code").ToString() == "SUCCESS")
            {
                if (result.GetValue("result_code").ToString() == "SUCCESS")
                {
                    url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
                }
                else
                {
                    //errMsg = result.GetValue("err_code_des").ToString();
                }
            }
            else
            {
                //errMsg = result.GetValue("return_msg").ToString();
            }

            //Log4Net.Log4Net.Info(log, "订单号:" + orderId + "发起Native的第二种支付方式,生成支付链接:" + url);
            return url;

        }
(2)支付辅助类
/**
        * 
        * 统一下单
        * @param WxPaydata inputObj 提交给统一下单API的参数
        * @param int timeOut 超时时间
        * @throws WxPayException
        * @return 成功时返回,其他抛异常
        */
        public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //检测必填参数
            if (!inputObj.IsSet("out_trade_no"))
            {
                throw new Exception("缺少统一支付接口必填参数out_trade_no!");
            }
            else if (!inputObj.IsSet("body"))
            {
                throw new Exception("缺少统一支付接口必填参数body!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new Exception("缺少统一支付接口必填参数total_fee!");
            }
            else if (!inputObj.IsSet("trade_type"))
            {
                throw new Exception("缺少统一支付接口必填参数trade_type!");
            }

            //关联参数
            if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
            {
                throw new Exception("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
            }
            if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
            {
                throw new Exception("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
            }

            //异步通知url未设置,则使用配置文件中的url
            if (!inputObj.IsSet("notify_url"))
            {
                inputObj.SetValue("notify_url", WxPayConfig.GetConfig().GetNotifyUrl());//异步通知url
            }

            inputObj.SetValue("appid", WxPayConfig.GetConfig().GetAppID());//公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID());//商户号
            inputObj.SetValue("spbill_create_ip", WxPayConfig.GetConfig().GetIp());//终端ip              
            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;
            //Log4Net.Log4Net.Info(log, "WX UnfiedOrder request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);
            //Log4Net.Log4Net.Info(log, "WX UnfiedOrder 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;
        }
 
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)
            {
                throw new Exception("WxPayData数据为空!");
            }

            string xml = "<xml>";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                //字段值不能为null,会影响后续流程
                if (pair.Value == null)
                {
                    throw new Exception("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 Exception("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 Exception("将空的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 (Exception ex)
            {
                throw new Exception(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 Exception("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;
            return "";
        }

        /**
        * @values格式化成能在Web页面上显示的结果(因为web页面上不能直接输出xml格式的字符串)
        */
        public string ToPrintStr()
        {
            string str = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value == null)
                {
                    throw new Exception("WxPayData内部含有值为null的字段!");
                }


                str += string.Format("{0}={1}\n", pair.Key, pair.Value.ToString());
            }
            str = HttpUtility.HtmlEncode(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 Exception("sign_type 不合法");
            }
        }

        /**
        * @生成签名,详见签名生成算法
        * @return 签名, sign字段不参加签名 SHA256
        */
        public string MakeSign()
        {
            return MakeSign(SIGN_TYPE_HMAC_SHA256);
        }



        /**
        * 
        * 检测签名是否正确
        * 正确返回true,错误抛异常
        */
        public bool CheckSign(string signType)
        {
            //如果没有设置签名,则跳过检测
            if (!IsSet("sign"))
            {
                throw new Exception("WxPayData签名存在但不合法!");
            }
            //如果设置了签名但是签名为空,则抛异常
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                throw new Exception("WxPayData签名存在但不合法!");
            }

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

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

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

            throw new Exception("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;
        }




    }
 
 /**
        * 生成随机串,随机串包含字母或数字
        * @return 随机串
        */
        public static string GenerateNonceStr()
        {
            RandomGenerator randomGenerator = new RandomGenerator();
            return randomGenerator.GetRandomUInt().ToString();
        }
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;
        }
    }

 

标签:return,string,url,微信,获取,WxPayData,new,inputObj,public
From: https://www.cnblogs.com/cby-love/p/17020194.html

相关文章

  • Apache和Nginx设置伪静态(URL Rewrite)的方法
    在Apache中有两种方法配置,一是通过httpd.conf文件,二是通过.htaccess文件。 使用httpd.conf来配置rewrite策略。 要使用httpd.conf文件来设置伪静态策略,我们可以......
  • C# Senparc.Weixin Winform微信扫码支付
    微信扫码支付引用的是第三方的:Senparc.Weixin引用:usingSenparc.Weixin.MP.TenPayLibV3;首先,在Form_Load里面调用生成支付二维码的方法:///<summary>///Fo......
  • curl命令常见用法汇总 good
     ​​curl​​是一种命令行工具,作用是发出网络请求,然后得到和提取数据,显示在"标准输出"(stdout)上面。curl是一个强大的命令行工具,它可以通过网络将信息传递给服务器或者从服......
  • 获取证书SHA1
    AndroidStudio获取SHA1值强大的AndroidStudio为我们提供了Terminal这个工具,我们可以通过他进行相应命令从而获取所需内容。Java中提供了Keytool工具去让我们管理证书,那......
  • 请求的参数的获取与校验(基本流程)
    请求的参数的获取与校验(基本流程)models/params.gopackagemodels//定义请求的参数typeParamSignUpstruct{ Usernamestring`json:"username"` Password......
  • 不封号PC微信协议
    最近在研究一个购物的小程序,HOOK的方式取Code发现异地封号问题真的好严重,所以研究了下PC脱机协议版本,发现脱机的协议真的不错,异地不封号,探讨交流请加varqq=‘2974520......
  • 微信通讯录一键导出的方法在这里
    6-2​有过一段时间,有一些做网销的朋友经常问我,如何导出微信的通讯录联系人,他们说在网上找了一些工具,使用非常繁琐,并且很慢。​我了解到原来是他们有些业务员或者销售离职,经......
  • 电脑版微信dat文件用什么软件打开
    一般来说,凡是说到微信电脑版的DAT文件,指的都是聊天过程中收发的图片,加密保存在电脑里。​这些文件正常情况下也只能在微信登录后,在微信里查看,因为微信加密的当然只有微信才......
  • 一键批量导出微信通讯录
    6-3​微信是我们常用的即时通信APP,除了日常生活使用外,还有一个重要的使用场景,就是日常工作也是用微信。​这样就有了个问题,几乎所有的客服、服务商、供应商等,都是用微信沟通......
  • javascript-数据类型-数据类型,获取数据变量的类型,数据类型的转换
    javascript-数据类型-数据类型,获取数据变量的类型,数据类型的转换目录javascript-数据类型-数据类型,获取数据变量的类型,数据类型的转换学习目标:1.数据类型简介1.1为什么......