码迷,mamicode.com
首页 > 微信 > 详细

微信支付--退款(支付金额原路退回)

时间:2020-06-03 20:15:21      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:print   stc   语言   网关   流程   alc   cos   guid   check   

内容摘要:用户支付完成后,凭商户订单号发起退款申请,微信处理后,将支付金额原路退回至用户支付账户。

服务端开发环境:.NET MVC 开发语言C#;

一、开发前准备(此处,前提默认条件为您已开通微信商户平台,且成功支付一笔订单)

  1、微信支付接口中,涉及资金回滚的接口会使用到API证书,包括退款、撤销接口等。证书下载及说明,您可参阅https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3,下载并将证书上传至目标服务器(本人为阿里云ECS服务器,IIS 10.0);

二、官方接口地址:https://api.mch.weixin.qq.com/secapi/pay/refund;

三、代码实现

  1、主体代码(调用日志请视业务情况自行添加,本文不再添加日志)

   public class Refund
    {
        /***
       * 申请退款完整业务流程逻辑
       * @param transaction_id 微信订单号(优先使用)
       * @param out_trade_no 商户订单号
       * @param refund_orderNo 订单退单号
       * @param total_fee 订单总金额
       * @param refund_fee 退款金额
       * @return 退款结果(xml格式)
       * @payType 2微信支付 3微信小程序支付
       */
        public void Run(string orderNo, string refund_orderNo, float total_fee, float refund_fee, int payType)
        {
            try
            {
                WxPayData data = new WxPayData();// 微信服务基础数据帮助类WxPayData请参阅代码块3

                data.SetValue("out_trade_no", orderNo);          // 支付订单单号
                data.SetValue("total_fee", total_fee * 100);      // 订单总金额,微信金额单位为分
                data.SetValue("refund_fee", refund_fee * 100);    // 退款金额,微信金额单位为分
                data.SetValue("out_refund_no", refund_orderNo);   // 随机生成商户退款单号 可参阅refund_orderNo = WxPayApi.GenerateOutTradeNo()生成唯一退款码
                data.SetValue("op_user_id", WxPayConfig.GetConfig().GetMchID()); // 资金流向的微信商户号
              
                WxPayData wxResult = WxPayApi.Refund(data, payType, 6);// 提交退款申请给API,接收返回数据 WxPayApi.Refund()方法请参阅代码块2

                if (wxResult.GetValue("return_code") + "" == "SUCCESS")
                {
                    if (wxResult.GetValue("result_code") + "" == "SUCCESS")
                    {
                        // ...退款成功的操作
                    }
                    else
                    {
                        // 退款失败的操作...

                        // 微信返回的退款失败码
                        string return_ero_des = wxResult.GetValue("err_code_des") + "";
                    }
                }
                else
                {
                    // 退款失败的操作...

                    // 退款失败原因
                    string return_msg = wxResult.GetValue("return_msg") + "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

  2、WxPayApi.Refund退款方法 

   public class WxPayApi
    {
        /**
        * 根据当前系统时间加随机序列来生成订单号
         * @return 订单号
        */
        public static string GenerateOutTradeNo()
        {
            var ran = new Random();
            return string.Format("{0}{1}{2}", WxPayConfig.GetConfig().GetMchID(), DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(999));
        }

        public static string GenerateNonceStr()
        {
            RandomGenerator randomGenerator = new RandomGenerator();
            return randomGenerator.GetRandomUInt().ToString();
        }

        /**
        * 
        * 测速上报
        * @param string interface_url 接口URL
        * @param int timeCost 接口耗时
        * @param WxPayData inputObj参数数组
        */
        private static void ReportCostTime(string interface_url, int timeCost, WxPayData inputObj)
        {
            //如果不需要进行上报
            if (WxPayConfig.GetConfig().GetReportLevel() == 0)
            {
                return;
            }

            //如果仅失败上报
            if (WxPayConfig.GetConfig().GetReportLevel() == 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.GetConfig().GetAppID());//公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID());//商户号
            inputObj.SetValue("user_ip", WxPayConfig.GetConfig().GetIp());//终端ip
            inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss"));//商户上报时间     
            inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//签名类型
            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;
        }

        /**
       * 
       * 申请退款
       * @param WxPayData inputObj 提交给申请退款API的参数
       * @param int timeOut 超时时间
       * @throws WxPayException
       * @return 成功时返回接口调用结果,其他抛异常
       */
        public static WxPayData Refund(WxPayData inputObj, int payType, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //检测必填参数
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!");
            }
            else if (!inputObj.IsSet("out_refund_no"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数total_fee!");
            }
            else if (!inputObj.IsSet("refund_fee"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!");
            }
            else if (!inputObj.IsSet("op_user_id"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!");
            }
            if (payType == 2)// 微信PC扫码支付退款
            {
                inputObj.SetValue("appid", WxPayConfig.GetConfig().GetAppID());// 微信公众平台AppId
            }
            else  // 微信小程序支付退款
            {
                inputObj.SetValue("appid", WxAppId);// 微信小程序appID
            }
         
            inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID());// 资金流向商户号

            inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串
            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256);//签名类型
            inputObj.SetValue("sign", inputObj.MakeSign());//签名

            string xml = inputObj.ToXml();
            var start = DateTime.Now;

            string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时

            //将xml格式的结果转换为对象以返回
            WxPayData result = new WxPayData();
            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//测速上报

            return result;
        }
    }

  3、退款基础数据帮助类

   /// <summary>
    /// 微信支付协议接口数据类,所有的API接口通信都依赖这个数据结构,
    /// 在调用接口之前先填充各个字段的值,然后进行接口通信,
    /// 这样设计的好处是可扩展性强,用户可随意对协议进行更改而不用重新设计数据结构,
    /// 还可以随意组合出不同的协议数据包,不用为每个协议设计一个数据包结构
    /// </summary>
    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 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) || pair.Value.GetType() == typeof(float))
                {
                    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不合法!");
            }


            SafeXmlDocument xmlDoc = new SafeXmlDocument();
            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
            {
                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 = JsonMapper.ToJson(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}\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 WxPayException("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 WxPayException("WxPayData签名存在但不合法!");
            }
            //如果设置了签名但是签名为空,则抛异常
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                throw new WxPayException("WxPayData签名存在但不合法!");
            }

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

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

            if (cal_sign == return_sign)
            {
                return true;
            }
            throw new WxPayException("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.UTF8;// 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;
        }
    }  

  4、POST方式向微信服务器提交数据

      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.UserAgent = USER_AGENT;
                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)
                {
                    X509Certificate2 cert = new X509Certificate2(WxPayConfig.GetConfig().GetSSlCertPath(), WxPayConfig.GetConfig().GetSSlCertPassword());
                    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)
            {
                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;
        }  

微信支付--退款(支付金额原路退回)

标签:print   stc   语言   网关   流程   alc   cos   guid   check   

原文地址:https://www.cnblogs.com/openWorld/p/13026106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!