微信支付V2 统一下单 .NET CORE

微信支付V2 统一下单 .NET CORE

 

一个小功能总是拖拖拖。。唉。。。今天2024年01月15日终于调成功了,以下是代码,能取到预支付订单号就行了。。

 

 /// <summary>
        /// 微信支付-微信小程序
        /// </summary>
        /// <returns></returns>
        [HttpGet("Wxpay_app")]
        public async Task<ApiResult> Wxpay_app()
        {
            try
            {
                //微信支付V2-统一下单文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1
                //1.准备提交数据
                Hashtable ht = new Hashtable();
                ht.Add("appid", "wxd64fd8b6111111");
                ht.Add("mch_id", "149111111");
                ht.Add("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));
                ht.Add("sign_type", "MD5");
                ht.Add("body", "腾讯充值中心-QQ会员充值");
                ht.Add("out_trade_no", DateTime.Now.ToString("yyyyMMddHHmmss") + Guid.NewGuid().ToString().Substring(0, 4));
                ht.Add("total_fee", 1);
                ht.Add("spbill_create_ip", HttpContext.UserHostAddress().ToString());
                ht.Add("notify_url", "https://xx.xxx.net/wx/notify");
                ht.Add("trade_type", "JSAPI");
                ht.Add("openid", "oOGeG6xoflRianAWRn8UpyCgyZiM");
                //2.签名: 排序、拼接、MD5, 把生成的签名加入到提交数据的sign中
                string pinjie = "";
                SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
                foreach (DictionaryEntry entry in ht)
                {
                    sortedDictionary.Add(entry.Key.ToString(), entry.Value.ToString());
                }
                foreach (KeyValuePair<string, string> pair in sortedDictionary)
                {
                    if (string.IsNullOrEmpty(pair.Value)) { continue; }
                    pinjie += $"{pair.Key}={pair.Value}&";
                }
                pinjie += "key=32021fdds325346433243254322";
                _logger.LogInformation("拼接好的串:\r\n"+pinjie+"\r\n");
                string sign = Tool.MD5Hash(pinjie).ToUpper();
                ht.Add("sign", sign);
                //3.把提交的数据转为XML
                XmlDocument xmlDoc = new XmlDocument();
                XmlElement rootElement = xmlDoc.CreateElement("xml");
                xmlDoc.AppendChild(rootElement);
                foreach (DictionaryEntry entry in ht)
                {
                    XmlElement element = xmlDoc.CreateElement(entry.Key.ToString());
                    element.InnerText = entry.Value.ToString();
                    rootElement.AppendChild(element);
                }
                string postdata = xmlDoc.OuterXml;
                _logger.LogInformation("提交的XML:\r\n"+postdata+"\r\n");
                //4.把XML数据POST提交到微信支付V2的接口地址,得到返回的预支付订单号,小程序端再通过预支付订单号调起微信支付
                string aaa = "";
                using (var client = new HttpClient())
                {
                    var content = new StringContent(postdata, Encoding.UTF8, "application/xml");
                    var response =await  client.PostAsync("https://api.mch.weixin.qq.com/pay/unifiedorder", content);

                    if (response.IsSuccessStatusCode)
                    {
                        aaa = await response.Content.ReadAsStringAsync();
                        _logger.LogInformation("远程返回:\r\n"+aaa+"\r\n");
                    }
                    else
                    {
                       throw new Exception($"StatusCode: {response.StatusCode}");
                    }
                }
                return new ApiResult() { code = 0, msg = aaa };
            }
            catch (Exception ex)
            {
                return new ApiResult() { code = 1, msg = "出错:" + ex.Message };
            }
        }

 

注意MD5加密那里得用utf8,原来是ascii的总是签名错误

 

   /// <summary>
        /// netcore下的实现MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MD5Hash(string input)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(input)); //用Encoding.ASCII的话在微信支付V2那里的签名不匹配
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "");
            }

        }

 

posted @ 2024-01-15 16:21  牛腩  阅读(154)  评论(0编辑  收藏  举报