微信支付提交的XML Data数据
Example #1
0
        /// <summary>
        /// 统一支付接口
        /// 统一支付接口,可接受JSAPI/NATIVE/APP 下预支付订单,返回预支付订单号。NATIVE 支付返回二维码code_url。
        /// </summary>
        /// <param name="dataInfo">微信支付需要post的Data数据</param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static UnifiedorderResult Unifiedorder(TenPayV3RequestData dataInfo, int timeOut = Config.TIME_OUT)
        {
            var urlFormat = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var data = dataInfo.PackageRequestHandler.ParseXML();//获取XML

            MemoryStream ms = new MemoryStream();
            var formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置

            var resultXml = RequestUtility.HttpPost(urlFormat, null, ms, timeOut: timeOut);
            return new UnifiedorderResult(resultXml);
        }
Example #2
0
        /// <summary>
        /// 【异步方法】统一支付接口
        /// 统一支付接口,可接受JSAPI/NATIVE/APP 下预支付订单,返回预支付订单号。NATIVE 支付返回二维码code_url。
        /// </summary>
        /// <param name="dataInfo">微信支付需要post的xml数据</param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static async Task <UnifiedorderResult> UnifiedorderAsync(TenPayV3RequestData dataInfo, int timeOut = Config.TIME_OUT)
        {
            var          urlFormat     = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var          data          = dataInfo.PackageRequestHandler.ParseXML();//获取XML
            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();
            await ms.WriteAsync(formDataBytes, 0, formDataBytes.Length);

            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            var resultXml = await RequestUtility.HttpPostAsync(urlFormat, null, ms, timeOut : timeOut);

            return(new UnifiedorderResult(resultXml));
        }
        public ActionResult JsApi(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return Content("您拒绝了授权!");
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return Content("验证失败!请从正规途径进入!1001");
            }
            try
            {


                //获取产品信息
                var stateData = state.Split('|');
                int productId = 0;
                ProductModel product = null;
                if (int.TryParse(stateData[0], out productId))
                {
                    int hc = 0;
                    if (int.TryParse(stateData[1], out hc))
                    {
                        var products = ProductModel.GetFakeProductList();
                        product = products.FirstOrDefault(z => z.Id == productId);
                        if (product == null || product.GetHashCode() != hc)
                        {
                            return Content("商品信息不存在,或非法进入!1002");
                        }
                        ViewData["product"] = product;
                    }
                }

                //通过,用code换取access_token
                var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);
                if (openIdResult.errcode != ReturnCode.请求成功)
                {
                    return Content("错误:" + openIdResult.errmsg);
                }

                string sp_billno = Request["order_no"];
                if (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId, DateTime.Now.ToString("yyyyMMdd"),
                        TenPayV3Util.BuildRandomStr(10));
                }
                else
                {
                    sp_billno = Request["order_no"];
                }

                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr = TenPayV3Util.GetNoncestr();

                var body = product == null ? "test" : product.Name;
                var price = product == null ? 100 : product.Price * 100;
                var xmlDataInfo = new TenPayV3RequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openIdResult.openid, TenPayV3Info.Key, nonceStr);

                var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口

                //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                ViewData["appId"] = TenPayV3Info.AppId;
                ViewData["timeStamp"] = timeStamp;
                ViewData["nonceStr"] = nonceStr;
                ViewData["package"] = package;
                ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

                return View();
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                msg += "<br>" + ex.StackTrace;
                msg += "<br>==Source==<br>" + ex.Source;

                if (ex.InnerException != null)
                {
                    msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                }
                return Content(msg);
            }
        }
        /// <summary>
        /// 原生支付 模式二
        /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。
        /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付
        /// </summary>
        /// <returns></returns>
        public ActionResult NativeByCodeUrl()
        {
            //创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr = TenPayV3Util.GetNoncestr();

            //商品Id,用户自行定义
            string productId = DateTime.Now.ToString("yyyyMMddHHmmss");

            //创建请求统一订单接口参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            //packageReqHandler.SetParameter("nonce_str", nonceStr);
            //packageReqHandler.SetParameter("body", "test");
            //packageReqHandler.SetParameter("out_trade_no", sp_billno);
            //packageReqHandler.SetParameter("total_fee", "1");
            //packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);
            //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);
            //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            //packageReqHandler.SetParameter("product_id", productId);

            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);

            //string data = packageReqHandler.ParseXML();
            var xmlDataInfo = new TenPayV3RequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.NATIVE, productId, TenPayV3Info.Key, nonceStr);
            //调用统一订单接口
            var result = TenPayV3.Unifiedorder(xmlDataInfo);
            //var unifiedorderRes = XDocument.Parse(result);
            //string codeUrl = unifiedorderRes.Element("xml").Element("code_url").Value;
            string codeUrl = result.code_url;
            BitMatrix bitMatrix;
            bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 600, 600);
            BarcodeWriter bw = new BarcodeWriter();

            var ms = new MemoryStream();
            var bitmap = bw.Write(bitMatrix);
            bitmap.Save(ms, ImageFormat.Png);
            //return File(ms, "image/png");
            ms.WriteTo(Response.OutputStream);
            Response.ContentType = "image/png";
            return null;
        }
        public ActionResult NativeNotifyUrl()
        {
            ResponseHandler resHandler = new ResponseHandler(null);

            //返回给微信的请求
            RequestHandler res = new RequestHandler(null);

            string openId = resHandler.GetParameter("openid");
            string productId = resHandler.GetParameter("product_id");

            if (openId == null || productId == null)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "回调数据异常");
            }

            //创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr = TenPayV3Util.GetNoncestr();

            //创建请求统一订单接口参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            //packageReqHandler.SetParameter("nonce_str", nonceStr);
            //packageReqHandler.SetParameter("body", "test");
            //packageReqHandler.SetParameter("out_trade_no", sp_billno);
            //packageReqHandler.SetParameter("total_fee", "1");
            //packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);
            //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);
            //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            //packageReqHandler.SetParameter("openid", openId);
            //packageReqHandler.SetParameter("product_id", productId);

            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);

            //string data = packageReqHandler.ParseXML();

            var xmlDataInfo = new TenPayV3RequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, productId, TenPayV3Info.Key, nonceStr);


            try
            {
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                //var unifiedorderRes = XDocument.Parse(result);
                //string prepayId = unifiedorderRes.Element("xml").Element("prepay_id").Value;

                //创建应答信息返回给微信
                res.SetParameter("return_code", result.return_code);
                res.SetParameter("return_msg", result.return_msg ?? "OK");
                res.SetParameter("appid", result.appid);
                res.SetParameter("mch_id", result.mch_id);
                res.SetParameter("nonce_str", result.nonce_str);
                res.SetParameter("prepay_id", result.prepay_id);
                res.SetParameter("result_code", result.result_code);
                res.SetParameter("err_code_des", "OK");

                string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key);
                res.SetParameter("sign", result.sign);
            }
            catch (Exception)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "统一下单失败");
            }

            return Content(res.ParseXML());
        }