public void DistributeStockAsyncTest()
        {
            var key = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);

            var TenPayV3Info = TenPayV3InfoCollection.Data[key];

            // 如果还未创建代金券批次 则创建新的代金券批次 并且激活
            if (createStockResult is null)
            {
                StartStockAsyncTest();
            }

            var out_request_no = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));

            var requestData = new DistributeStockRequsetData(createStockResult.stock_id, out_request_no, TenPayV3Info.AppId, TenPayV3Info.MchId);

            var marketingApis = new MarketingApis();

            distributeStockResult = marketingApis.DistributeStockAsync(openId, requestData).GetAwaiter().GetResult();

            Console.WriteLine("微信支付 V3 发放代金券批次接口结果:" + distributeStockResult.ToJson(true));

            Assert.IsNotNull(distributeStockResult);
            Assert.IsTrue(distributeStockResult.ResultCode.Success);
            Assert.IsTrue(distributeStockResult.VerifySignSuccess == true);//通过验证
        }
        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(26);//最多32位
            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 TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.JSAPI, openId, 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()));
        }
        /// <summary>
        /// 退款通知地址
        /// </summary>
        /// <returns></returns>
        public ActionResult RefundNotifyUrl()
        {
            WeixinTrace.SendCustomLog("RefundNotifyUrl被访问", "IP" + HttpContext.Request.UserHostAddress);

            string responseCode = "FAIL";
            string responseMsg  = "FAIL";

            try
            {
                ResponseHandler resHandler = new ResponseHandler(null);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                WeixinTrace.SendCustomLog("跟踪RefundNotifyUrl信息", resHandler.ParseXML());

                if (return_code == "SUCCESS")
                {
                    responseCode = "SUCCESS";
                    responseMsg  = "OK";

                    string appId     = resHandler.GetParameter("appid");
                    string mch_id    = resHandler.GetParameter("mch_id");
                    string nonce_str = resHandler.GetParameter("nonce_str");
                    string req_info  = resHandler.GetParameter("req_info");

                    var decodeReqInfo = TenPayV3Util.DecodeRefundReqInfo(req_info, TenPayV3Info.Key);
                    var decodeDoc     = XDocument.Parse(decodeReqInfo);

                    //获取接口中需要用到的信息
                    string transaction_id       = decodeDoc.Root.Element("transaction_id").Value;
                    string out_trade_no         = decodeDoc.Root.Element("out_trade_no").Value;
                    string refund_id            = decodeDoc.Root.Element("refund_id").Value;
                    string out_refund_no        = decodeDoc.Root.Element("out_refund_no").Value;
                    int    total_fee            = int.Parse(decodeDoc.Root.Element("total_fee").Value);
                    int?   settlement_total_fee = decodeDoc.Root.Element("settlement_total_fee") != null
                            ? int.Parse(decodeDoc.Root.Element("settlement_total_fee").Value)
                            : null as int?;

                    int    refund_fee = int.Parse(decodeDoc.Root.Element("refund_fee").Value);
                    int    tosettlement_refund_feetal_fee = int.Parse(decodeDoc.Root.Element("settlement_refund_fee").Value);
                    string refund_status         = decodeDoc.Root.Element("refund_status").Value;
                    string success_time          = decodeDoc.Root.Element("success_time").Value;
                    string refund_recv_accout    = decodeDoc.Root.Element("refund_recv_accout").Value;
                    string refund_account        = decodeDoc.Root.Element("refund_account").Value;
                    string refund_request_source = decodeDoc.Root.Element("refund_request_source").Value;

                    //进行业务处理
                }
            }
            catch (Exception ex)
            {
                responseMsg = ex.Message;
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
            }

            string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", responseCode, responseMsg);

            return(Content(xml, "text/xml"));
        }
        public ActionResult JsApi(int productId, int hc)
        {
            try
            {
                //获取订单信息
                dynamic job = new OrderService().GetOrderByOrderID(productId);

                if (job == null)
                {
                    return(Content("商品信息不存在,或非法进入!1002"));
                }

                //var openId = User.Identity.Name;
                var openId = (string)Session["OpenId"];

                string sp_billno = job[0].ChannelOrderID;

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

                string body  = job[0].PayInfo;
                int    price = Convert.ToInt32(job[0].PayMoney * 100);
                price = 1;

#if DEBUG
                price = 1;
#else
                Console.WriteLine("Release:222222222222");
#endif

                string productInfo = job[0].ChannelOrderID.ToString();
                string attach      = TenPayV3Info.AppId + "," + openId + "," + productInfo;

                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr, null, null, null, null, attach);

                var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口
                                                                 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                ViewData["product"] = job;

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

                //临时记录订单信息,留给退款申请接口测试使用
                Session["BillNo"]  = sp_billno;
                Session["BillFee"] = price;

                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>
        /// H5支付
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="hc"></param>
        /// <returns></returns>
        public ActionResult H5Pay(int productId, int hc)
        {
            {
                try
                {
                    //获取产品信息
                    var products = ProductModel.GetFakeProductList();
                    var product  = products.FirstOrDefault(z => z.Id == productId);
                    if (product == null || product.GetHashCode() != hc)
                    {
                        return(Content("商品信息不存在,或非法进入!1002"));
                    }

                    string openId = null;//此时在外部浏览器,无法或得到OpenId

                    string sp_billno = Request["order_no"];
                    if (string.IsNullOrEmpty(sp_billno))
                    {
                        //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                        sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                                  TenPayV3Util.BuildRandomStr(6));
                    }
                    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 : (int)product.Price * 100;
                    //var ip = Request.Params["REMOTE_ADDR"];
                    var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId, TenPayV3Info.Key, nonceStr);

                    var result = TenPayV3.Html5Order(xmlDataInfo); //调用统一订单接口
                                                                   //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);

                    /*
                     * result:{"device_info":"","trade_type":"MWEB","prepay_id":"wx20170810143223420ae5b0dd0537136306","code_url":"","mweb_url":"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20170810143223420ae5b0dd0537136306\u0026package=1505175207","appid":"wx669ef95216eef885","mch_id":"1241385402","sub_appid":"","sub_mch_id":"","nonce_str":"juTchIZyhXvZ2Rfy","sign":"5A37D55A897C854F64CCCC4C94CDAFE3","result_code":"SUCCESS","err_code":"","err_code_des":"","return_code":"SUCCESS","return_msg":null}
                     */
                    //return Json(result, JsonRequestBehavior.AllowGet);

                    var package = string.Format("prepay_id={0}", result.prepay_id);

                    ViewData["product"] = product;

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

                    //设置成功页面(也可以不设置,支付成功后默认返回来源地址)
                    var returnUrl =
                        string.Format("https://sdk.weixin.senparc.com/TenpayV3/H5PaySuccess?productId={0}&hc={1}",
                                      productId, hc);

                    var mwebUrl = result.mweb_url;
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        mwebUrl += string.Format("&redirect_url={0}", returnUrl.AsUrlData());
                    }

                    ViewData["MWebUrl"] = mwebUrl;

                    //临时记录订单信息,留给退款申请接口测试使用
                    Session["BillNo"]  = sp_billno;
                    Session["BillFee"] = price;

                    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>
        /// 目前支持向指定微信用户的openid发放指定金额红包
        /// 注意total_amount、min_value、max_value值相同
        /// total_num=1固定
        /// 单个红包金额介于[1.00元,200.00元]之间
        /// </summary>
        /// <returns></returns>
        public ActionResult SendRedPack()
        {
            string mchbillno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);

            string         nonceStr          = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);                //随机字符串
            packageReqHandler.SetParameter("wxappid", TenPayV3Info.AppId);        //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);         //商户号
            packageReqHandler.SetParameter("mch_billno", mchbillno);              //填入商家订单号
            packageReqHandler.SetParameter("send_name", "红包发送者名称");               //红包发送者名称
            packageReqHandler.SetParameter("re_openid", "接受收红包的用户的openId");       //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", "100");                //付款金额,单位分
            packageReqHandler.SetParameter("total_num", "1");                     //红包发放总人数
            packageReqHandler.SetParameter("wishing", "红包祝福语");                   //红包祝福语
            packageReqHandler.SetParameter("client_ip", Request.UserHostAddress); //调用接口的机器Ip地址
            packageReqHandler.SetParameter("act_name", "活动名称");                   //活动名称
            packageReqHandler.SetParameter("remark", "备注信息");                     //备注信息
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            //最新的官方文档中将以下三个字段去除了
            //packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            //packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            //packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分


            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = @"F:\apiclient_cert.p12";
            //私钥(在安装证书时设置)
            string password = "";

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          responseContent = streamReader.ReadToEnd();
            #endregion

            return(Content(responseContent));
        }
Beispiel #7
0
        public ActionResult ajaxorder(string orderno)
        {
            try
            {
                ReturnJson root         = null;
                var        ordersEntity = ordersbll.GetEntityByOrderSn(orderno);
                if (ordersEntity != null)
                {
                    var sp_billno = ordersEntity.OrderSn;
                    var nonceStr  = TenPayV3Util.GetNoncestr();

                    //商品Id,用户自行定义
                    string  productId = ordersEntity.TelphoneID.ToString();
                    decimal?Amount    = ordersEntity.Price;//0.01M 测试
                    if (Amount < 0)
                    {
                        root = new ReturnJson {
                            code = 200, msg = "付款金额小于0"
                        };
                    }
                    else
                    {
                        if (ordersEntity.PayType == "支付宝")
                        {
                            try
                            {
                                DefaultAopClient client = new DefaultAopClient(WeixinConfig.serviceUrl, WeixinConfig.aliAppId, WeixinConfig.privateKey, "json", "1.0",
                                                                               WeixinConfig.signType, WeixinConfig.payKey, WeixinConfig.charset, false);

                                // 组装业务参数model
                                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                                model.Body           = "支付宝购买靓号";                                       // 商品描述
                                model.Subject        = productId;                                       // 订单名称
                                model.TotalAmount    = Amount.ToString();                               // 付款金额"0.01"ordersEntity.Price.ToString()
                                model.OutTradeNo     = sp_billno;                                       // 外部订单号,商户网站订单系统中唯一的订单号
                                model.ProductCode    = "QUICK_WAP_WAY";
                                model.QuitUrl        = "http://www.1650539.com/webapp/agentshop/index"; // 支付中途退出返回商户网站地址
                                model.TimeoutExpress = "90m";
                                AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
                                //设置支付完成同步回调地址
                                request.SetReturnUrl(WeixinConfig.return_url);
                                //设置支付完成异步通知接收地址
                                request.SetNotifyUrl(WeixinConfig.notify_url);
                                // 将业务model载入到request
                                request.SetBizModel(model);

                                AlipayTradeWapPayResponse response = null;
                                try
                                {
                                    response = client.pageExecute(request, null, "post");
                                    //Response.Write(response.Body);
                                    H5PayData h5PayData = new H5PayData();
                                    h5PayData.form = response.Body;
                                    root           = new ReturnJson {
                                        code = 200, msg = "\u652f\u4ed8\u5b9d\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                                    };
                                }
                                catch (Exception exp)
                                {
                                    throw exp;
                                }
                            }
                            catch (Exception ex)
                            {
                                //return Json(new { Result = false, msg = "缺少参数" });
                            }
                        }
                        else
                        {
                            //0 手机(H5支付)  1 电脑(扫码Native支付),2微信浏览器(JSAPI)
                            //pc端返回二维码,否则H5
                            if (ordersEntity.PayType == "微信扫码")
                            {
                                //创建请求统一订单接口参数
                                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID,
                                                                                      tenPayV3Info.MchId,
                                                                                      "扫码支付靓号",
                                                                                      sp_billno,
                                                                                      Convert.ToInt32(Amount * 100),
                                                                                      //1,
                                                                                      Request.UserHostAddress,
                                                                                      tenPayV3Info.TenPayV3Notify,
                                                                                      TenPayV3Type.NATIVE,
                                                                                      null,
                                                                                      tenPayV3Info.Key,
                                                                                      nonceStr,
                                                                                      productId: productId);
                                //调用统一订单接口
                                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                                if (result.return_code == "SUCCESS")
                                {
                                    H5PayData h5PayData = new H5PayData()
                                    {
                                        appid         = WeixinConfig.AppID,
                                        code_url      = result.code_url,//weixin://wxpay/bizpayurl?pr=lixpXgt-----------扫码支付
                                        mch_id        = WeixinConfig.MchId,
                                        nonce_str     = result.nonce_str,
                                        prepay_id     = result.prepay_id,
                                        result_code   = result.result_code,
                                        return_code   = result.return_code,
                                        return_msg    = result.return_msg,
                                        sign          = result.sign,
                                        trade_type    = "NATIVE",
                                        trade_no      = sp_billno,
                                        payid         = ordersEntity.Id.ToString(),
                                        wx_query_href = "http://www.1650539.com/webapp/agentshop/queryWx/" + ordersEntity.Id,
                                        wx_query_over = "http://www.1650539.com/webapp/agentshop/paymentFinish/" + ordersEntity.Id
                                    };

                                    root = new ReturnJson {
                                        code = 200, msg = "\u5fae\u4fe1\u626b\u7801\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                                    };
                                }
                                else
                                {
                                    root = new ReturnJson {
                                        code = 400, msg = result.return_msg
                                    };
                                }
                            }
                            else
                            {
                                var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, "H5购买靓号", sp_billno,
                                                                                        // 1,
                                                                                        Convert.ToInt32(Amount * 100),
                                                                                        Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, null, tenPayV3Info.Key, nonceStr);

                                var resultH5 = TenPayV3.Html5Order(xmlDataInfoH5); //调用统一订单接口
                                LogHelper.AddLog(resultH5.ResultXml);              //记录日志
                                if (resultH5.return_code == "SUCCESS")
                                {
                                    H5PayData h5PayData = new H5PayData()
                                    {
                                        appid         = WeixinConfig.AppID,
                                        mweb_url      = resultH5.mweb_url,//H5访问链接
                                        mch_id        = WeixinConfig.MchId,
                                        nonce_str     = resultH5.nonce_str,
                                        prepay_id     = resultH5.prepay_id,
                                        result_code   = resultH5.result_code,
                                        return_code   = resultH5.return_code,
                                        return_msg    = resultH5.return_msg,
                                        sign          = resultH5.sign,
                                        trade_type    = "H5",
                                        trade_no      = sp_billno,
                                        payid         = ordersEntity.Id.ToString(),
                                        wx_query_href = "http://www.1650539.com/webapp/agentshop/queryWx/" + ordersEntity.Id,
                                        wx_query_over = "http://www.1650539.com/webapp/agentshop/paymentFinish/" + ordersEntity.Id
                                    };

                                    root = new ReturnJson {
                                        code = 200, msg = "\u5fae\u4fe1\u0048\u0035\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                                    };
                                }
                                else
                                {
                                    root = new ReturnJson {
                                        code = 400, msg = resultH5.return_msg
                                    };
                                }
                            }
                        }
                    }
                }
                else
                {
                    root = new ReturnJson {
                        code = 400, msg = "订单号不存在!"
                    };
                }

                LogHelper.AddLog(JsonConvert.SerializeObject(root));//记录日志
                return(Json(root));
            }
            catch (Exception ex)
            {
                LogHelper.AddLog(ex.Message);//记录日志
                throw;
            }
        }
Beispiel #8
0
        public ActionResult ajaxorder(int?id)
        {
            //return Content("{\"code\":true,\"status\":true,\"msg\":\"提交成功!\",\"data\":{\"appid\":\"wx288f944166a4bdc6\",\"code_url\":\"weixin://wxpay/bizpayurl?pr=K9tQFgw\",\"mch_id\":\"1582948931\",\"nonce_str\":\"gelx5Eej34TWkYjL\",\"prepay_id\":\"wx18152655644502b82539bf421260374600\",\"result_code\":\"SUCCESS\",\"return_code\":\"SUCCESS\",\"return_msg\":null,\"sign\":\"4D19F96F050056C904DBD7371D974905\",\"trade_type\":\"NATIVE\",\"trade_no\":\"LX-20200418151928103008\",\"payid\":\"11\",\"wx_query_href\":\"http://localhost:4066/WeChatManage/user_order/queryWx/11\",\"wx_query_over\":\"http://localhost:4066/WeChatManage/user_order/paymentFinish/11\"}}");
            try
            {
                OrdersEntity ordersEntity = ordersbll.GetEntity(id);

                var sp_billno = ordersEntity.OrderSn;
                var nonceStr  = TenPayV3Util.GetNoncestr();

                //商品Id,用户自行定义
                string productId = ordersEntity.TelphoneID.ToString();

                //创建请求统一订单接口参数
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2,
                                                                      tenPayV3Info.MchId,
                                                                      "支付靓号",
                                                                      sp_billno,
                                                                      Convert.ToInt32(ordersEntity.Price * 100),
                                                                      Request.UserHostAddress,
                                                                      tenPayV3Info.TenPayV3Notify,
                                                                      TenPayV3Type.NATIVE,
                                                                      null,
                                                                      tenPayV3Info.Key,
                                                                      nonceStr,
                                                                      productId: productId);
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(xmlDataInfo);

                LogHelper.AddLog(result.ResultXml);//记录日志

                H5Response root = null;
                if (result.return_code == "SUCCESS")
                {
                    H5PayData h5PayData = new H5PayData()
                    {
                        appid         = WeixinConfig.AppID2,
                        code_url      = result.code_url,//weixin://wxpay/bizpayurl?pr=lixpXgt
                        mch_id        = WeixinConfig.MchId,
                        nonce_str     = result.nonce_str,
                        prepay_id     = result.prepay_id,
                        result_code   = result.result_code,
                        return_code   = result.return_code,
                        return_msg    = result.return_msg,
                        sign          = result.sign,
                        trade_type    = "NATIVE",
                        trade_no      = sp_billno,
                        payid         = id.ToString(),
                        wx_query_href = Config.GetValue("Domain2") + "/WeChatManage/user_order/queryWx/" + id,
                        wx_query_over = Config.GetValue("Domain2") + "/WeChatManage/user_order/paymentFinish/" + id
                    };

                    root = new H5Response {
                        code = true, status = true, msg = "\u63d0\u4ea4\u6210\u529f\uff01", data = h5PayData
                    };
                }
                else
                {
                    root = new H5Response {
                        code = false, status = false, msg = result.return_msg
                    };
                }
                LogHelper.AddLog(JsonConvert.SerializeObject(root));//记录日志

                return(Content(JsonConvert.SerializeObject(root)));
            }
            catch (Exception ex)
            {
                LogHelper.AddLog(ex.Message);//记录日志
                throw;
            }
        }
Beispiel #9
0
        public void CreateUniqueThresholdActivityAsyncTest()
        {
            var key          = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);
            var TenPayV3Info = TenPayV3InfoCollection.Data[key];

            // 如果还未创建支付有礼活动 则建立支付有礼活动
            if (createUniqueThresholdActivityResult is null)
            {
                CreateUniqueThresholdActivityAsyncTest();
            }

            // TODO:流水号?这样是否有效?
            var out_request_no = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));

            //TODO: 此接口测试依赖商户券接口和图片上传接口
            var activity_base_info = new CreateUniqueThresholdActivityRequestData.Activity_Base_Info("Senparc支付有礼单元测试活动", "活动副标题", "TODO:仅支持通过《图片上传API》接口获取的图片URL地址", null, new TenpayDateTime(DateTime.Now), new TenpayDateTime(DateTime.Now.AddHours(2)), null, out_request_no, "OFF_LINE_PAY", null, null);
            var award_send_rule    = new CreateUniqueThresholdActivityRequestData.Award_Send_Rule(100, "SINGLE_COUPON", "BUSIFAVOR", new CreateUniqueThresholdActivityRequestData.Award_Send_Rule.Award_List[] { new(createBusifavorStockResult.stock_id, "TODO:原始图", "TODO:缩略图") }, "IN_SEVICE_COUPON_MERCHANT", null);
Beispiel #10
0
        protected override void DoWork()
        {
            //将已经过期的团购订单设置为失败,并退款
            //_orderRepository.GetAll().Where(t=>t.Type==OrderType.Groupon && t.GrouponStatus==GrouponStatus.Grouponing)

            var groupOrdrs = _groupOrderRepository.GetAll()
                             .Where(t => t.GrouponStatus == GrouponStatus.GrouponFail)
                             .ToList();

            Logger.Info("GrouponCancelWorker 需要退款数量:" + groupOrdrs.Count);

            foreach (var grouponOrder in groupOrdrs)
            {
                //设置对应订单的状态
                var orderInfo = _orderRepository.FirstOrDefault(t => t.JoinGrouponId == grouponOrder.Id);
                if (orderInfo != null && orderInfo.Type == OrderType.Groupon &&
                    orderInfo.GrouponStatus == GrouponStatus.GrouponFail)
                {
                    var payinfo = _orderPayRepository.FirstOrDefault(t => t.OrderId == orderInfo.Id);
                    if (payinfo == null)
                    {
                        continue;
                    }

                    switch (payinfo.Channel)
                    {
                    case "微信支付":
                        string nonceStr    = TenPayV3Util.GetNoncestr();
                        string outTradeNo  = orderInfo.OrderNo;
                        string outRefundNo = "OutRefunNo-" + DateTime.Now.Ticks;
                        int    totalFee    = (int)(payinfo.Money * 100);
                        int    refundFee   = totalFee;
                        var    paykey      = SettingManager.GetSettingValue(AppSettings.Weixin.PayKey);
                        var    AppId       = SettingManager.GetSettingValue(AppSettings.Weixin.AppId);
                        var    MchId       = SettingManager.GetSettingValue(AppSettings.Weixin.MchId);

                        string opUserId = MchId;
                        var    dataInfo = new TenPayV3RefundRequestData(AppId, MchId, paykey,
                                                                        null, nonceStr, null, outTradeNo, outRefundNo, totalFee, refundFee, opUserId, null);
                        var cert     = Path.Combine(_appFolders.Root, "apiclient_cert.p12"); //  @"D:\cert\apiclient_cert_SenparcRobot.p12";//根据自己的证书位置修改
                        var password = MchId;                                                //默认为商户号,建议修改
                        var result   = TenPayV3.Refund(dataInfo, cert, password);
                        Logger.Warn("refundFee:" + refundFee);
                        Logger.Warn(result.ToJsonString());
                        if (result.IsResultCodeSuccess() && result.IsReturnCodeSuccess())
                        {
                            payinfo.RefundsTradeNo  = result.out_refund_no;
                            payinfo.RefundsPayTime  = DateTime.Now;
                            orderInfo.GrouponStatus = GrouponStatus.GrouponFailAndRefunds;
                            _orderRepository.Update(orderInfo);

                            grouponOrder.GrouponStatus = GrouponStatus.GrouponFailAndRefunds;
                            _groupOrderRepository.Update(grouponOrder);
                        }


                        break;

                    case "支付宝":

                        string APPID             = "2016081501749843";
                        string PID               = "2088421556051016";
                        string APP_PRIVATE_KEY   = @"MIIEowIBAAKCAQEArtd47la2jHyV5wbTkn/GtVPvTzTr0w6PxWYRY/dnscHVHyPd56Yc/NMJoavcMvJaH4lUzmTBcj3Nz8cv4gsVqYUqyojtukh9JBqW4njdC3IuggBH1Lmo/6cgaZjOzSEHcwyWNU0TcgfFj+y8Kd47YVdh9+xW9/M3nQn9MAaQgfHZbmLMzV5mg/IsB9JzCG963JSuMGq1CiEtYggllC+bhLtJTi+Mmlf0EcTI7CWd80ibMVgtaCyuEl9mdPo9qf0uUHQvZjPo24H24yhinspNlWYkRz9KeqU+agaIz5VKL7Nqwf5YZMauCzsDvM6wurfAHBClRh/UfAvxHN7+Oeqz8QIDAQABAoIBAF/Vd1Gccf7bIwc4tKsuImqtkRRnO4O6DY/zfEDBETNbvUeOT0lzwZvKyRK2ssGyGTgD/FoM3AOUYMUsttA9pyf9+BB/sV5T8VPixyVnfjGR6nATW0v8X+eRYbC/s0q4ee7TzVl139y26dETv6drSjz2upo8DwdlZuxK116Fmpu+XiMc3u0QCbrnbFamhMXQoaYrYcU+pYYLc7Zzoc9ZN4szULZDDF6wkrktZbAuKyiERYF8vLNS2Gm6A6hMpVPpviSA48hhk4k4Gjn2oihEsvuqDf5Y8yI+5xASBLyqylvpZTNjp6B4V49MjyrY5DEecdpTf1kzFR6clAxaOmoCgCkCgYEA4t/5Ikbvyn3WdZK8Oyqlw9MxQKrZHz//s1OE+QV5Aqf5R3U30HaOGdImvocQb+Shgz7nV9fKN1hVdKNK6ASgQ0clhQGb6FrdxdyvPGrDmjDBvKULNM7rFbzeUSC5wHEHbZ8xkMY+sdai0R/sEk8FvUa+hzU3yyv5SmxJ2ESLjUMCgYEAxUl6Qaa5BO8qsrj33Px3Ag8umzLP7Dco+cPjR+b2D1Eg2RYvvr/+68gXB27nde5GEo+i8mIi9C2vfAsfbHJqLFBWX95gePMnRFoeWylNPqSz1+cGZJTsBWvptj7nHle5MYn8fe4JBLBIOGAUwPwA5SN5pMRkhU1+xT3mcUjRLLsCgYBw7ifm5gSKeOT9lVLY6LumpEOJ+wEkywiOzO4NvqmjptUwuqpTvA+zzqW2hSiradTzraYeVa20quWur3Gj2Fml445LjKd8m251BQq9Oi+vWsG1EzpmyPC/20mWfIG5xwl5iZp0hBnFEB/vlMI/wtIKi2Jfjx/8pCDs6MZBPq1wXQKBgG0lHmbtttRdAJFJtY7jeW+BOLaR4Of9CEVNsxLXWu/UYUjYdmegTobg9qSdHZ5nyQqBvpM76byO/dOxT5wunECR3YdCPrsLQoEVHlAuxFZQxlI+tJG2tfC15+F0YWau/3zBqxd8Ni8K25mcxj6R7GjYPHcEU9xPqD+05CVuNJL7AoGBAM1Xi7gWKaV7bYQdmW2HFfmAaW1z5DUPPZoVQ/wsZwSbBPf3Hn7qE6DM+dRMK6RBL1GIuRdxfCPOT4ktei9dvghM42gU2me8U5B6T5s1Sf99m/iw6svyoU5OAcIPSZ38R4l00VA1w+jYSMdQukhBlgYZQgRxeXKOFiM9IpkVvH9U";
                        string ALIPAY_PUBLIC_KEY = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlhGDVAL2+yN9HYkxgLBTI4MswpHi9QLrN/8zkJDFWQOGJEuUic2wPEJ/Mi45wuNMpeE57gzGMEk9AODTb+dzN5uA9gd0GVBcDI+5pBxJASWCouDUQR4Lvuo52vPTJGc2oageP5Of2L7eUazIYKU6jxoJWFbjzRN36p0l3SCvyvkOFaiTyIUFqDe5pprEPRWdxJmbwDnPsF4b3W1NdivoxP9y/ztCGN7ImX/mPLRrwveZe4xqvDOJ0sZ9LgfzJL7POE8lkj7m5LWM/5cNDKB3rtElp6eDWI7blBCvBsqMuzaCjzuYswYttu/j5gVLUd1oQ8v0wdw8lmPskcYEtobF6wIDAQAB";
                        string CHARSET           = "UTF-8";


                        APPID             = SettingManager.GetSettingValue(AppSettings.Alipay.APPID);
                        PID               = SettingManager.GetSettingValue(AppSettings.Alipay.PID);
                        APP_PRIVATE_KEY   = SettingManager.GetSettingValue(AppSettings.Alipay.APP_PRIVATE_KEY);
                        ALIPAY_PUBLIC_KEY = SettingManager.GetSettingValue(AppSettings.Alipay.ALIPAY_PUBLIC_KEY);

                        var client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", APPID, APP_PRIVATE_KEY, "json", "1.0", "RSA2", ALIPAY_PUBLIC_KEY, CHARSET, false);
                        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                        request.BizContent = "{" +
                                             "    \"out_trade_no\":\"" + orderInfo.OrderNo + "\"," +
                                             "    \"trade_no\":\"" + payinfo.TradeNo + "\"," +
                                             "    \"refund_amount\":" + payinfo.Money.ToString("F2") + "," +
                                             "    \"refund_reason\":\"拼团失败退款\"" +
                                             "  }";
                        AlipayTradeRefundResponse response = client.Execute(request);
                        Logger.Warn(response.Body);
                        if (!response.IsError)
                        {
                            payinfo.RefundsTradeNo  = response.TradeNo;
                            payinfo.RefundsPayTime  = DateTime.Now;
                            orderInfo.GrouponStatus = GrouponStatus.GrouponFailAndRefunds;
                            _orderRepository.Update(orderInfo);

                            grouponOrder.GrouponStatus = GrouponStatus.GrouponFailAndRefunds;
                            _groupOrderRepository.Update(grouponOrder);
                        }
                        break;
                    }
                }



                //if (orderInfo != null && orderInfo.Type==OrderType.Groupon && orderInfo.GrouponStatus==GrouponStatus.GrouponFail)
                //{
                //    orderInfo.Status = OrderStatus.Cancel;
                //    orderInfo.GrouponStatus = GrouponStatus.GrouponFail;
                //    _orderRepository.Update(orderInfo);
                //}

                ////修改团购状态
                //grouponOrder.GrouponStatus = GrouponStatus.GrouponFail;
                //_groupOrderRepository.Update(grouponOrder);
            }
        }
Beispiel #11
0
        public override async Task <(bool success, RefundData refundDetail)> RefundResultNotify(
            IEnumerable <KeyValuePair <string, string> > query,
            IDictionary <string, string> header,
            IDictionary <string, string> form,
            Stream body)
        {
            await Task.CompletedTask;
            var xml = body.ReadToString();

            if (xml.IsNullOrWhiteSpace())
            {
                Logger.LogWarning("微信退款回调,xml数据为空");
                return(false, null);
            }

            ResponseHandler resHandler;

            try
            {
                // 获取微信回调数据
                resHandler = new ResponseHandler(HttpContextAccessor.HttpContext);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");
                if (return_code != "SUCCESS")
                {
                    return(false, null);
                }

                string appId     = resHandler.GetParameter("appid");
                string mch_id    = resHandler.GetParameter("mch_id");
                string nonce_str = resHandler.GetParameter("nonce_str");
                string req_info  = resHandler.GetParameter("req_info");

                var secret = MchOptions.Value.Get(mch_id)?.MchKey;
                if (secret.IsNullOrWhiteSpace())
                {
                    Logger.LogError($"微信支付回调,未找到商户密钥,mchId:{mch_id},result:{xml}");
                    return(false, null);
                }

                var decodeReqInfo = TenPayV3Util.DecodeRefundReqInfo(req_info, secret);
                var decodeDoc     = XDocument.Parse(decodeReqInfo);

                //获取接口中需要用到的信息
                string transaction_id       = decodeDoc.Root.Element("transaction_id").Value;
                string out_trade_no         = decodeDoc.Root.Element("out_trade_no").Value;
                string refund_id            = decodeDoc.Root.Element("refund_id").Value;
                string out_refund_no        = decodeDoc.Root.Element("out_refund_no").Value;
                int    total_fee            = int.Parse(decodeDoc.Root.Element("total_fee").Value);
                int?   settlement_total_fee = decodeDoc.Root.Element("settlement_total_fee") != null
                    ? int.Parse(decodeDoc.Root.Element("settlement_total_fee").Value)
                    : null as int?;

                int    refund_fee = int.Parse(decodeDoc.Root.Element("refund_fee").Value);
                int    tosettlement_refund_feetal_fee = int.Parse(decodeDoc.Root.Element("settlement_refund_fee").Value);
                string refund_status         = decodeDoc.Root.Element("refund_status").Value;
                string success_time          = decodeDoc.Root.Element("success_time").Value;
                string refund_recv_accout    = decodeDoc.Root.Element("refund_recv_accout").Value;
                string refund_account        = decodeDoc.Root.Element("refund_account").Value;
                string refund_request_source = decodeDoc.Root.Element("refund_request_source").Value;

                var refundDetail = new RefundData
                {
                    FailReason       = "",
                    LocalRefundNo    = out_refund_no,
                    RefundNo         = refund_id,
                    RealRefundAmount = tosettlement_refund_feetal_fee,
                    Status           = ToStatus(refund_status),
                    SuccessTime      = success_time.IsNullOrWhiteSpace()
                        ? null
                        : (long?)success_time.ConvertTo <DateTime>().GetLongDate(),
                    OriginData = decodeReqInfo
                };
                return(true, refundDetail);
            }
            catch (XmlException)
            {
                Logger.LogWarning("微信退款回调,xml数据解析错误");
                return(false, null);
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, "微信退款回调数据处理异常");
                return(false, null);
            }
        }
        /// <summary>
        /// 退款通知地址
        /// </summary>
        /// <returns></returns>
        public ActionResult RefundNotifyUrl()
        {
            WeixinTrace.SendCustomLog("RefundNotifyUrl被访问", "IP" + HttpContext.UserHostAddress()?.ToString());

            string responseCode = "FAIL";
            string responseMsg  = "FAIL";

            try
            {
                ResponseHandler resHandler = new ResponseHandler(null);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                WeixinTrace.SendCustomLog("跟踪RefundNotifyUrl信息", resHandler.ParseXML());

                if (return_code == "SUCCESS")
                {
                    responseCode = "SUCCESS";
                    responseMsg  = "OK";

                    string appId     = resHandler.GetParameter("appid");
                    string mch_id    = resHandler.GetParameter("mch_id");
                    string nonce_str = resHandler.GetParameter("nonce_str");
                    string req_info  = resHandler.GetParameter("req_info");

                    if (!appId.Equals(Senparc.Weixin.Config.SenparcWeixinSetting.TenPayV3_AppId))
                    {
                        /*
                         * 注意:
                         * 这里添加过滤只是因为盛派Demo经常有其他公众号错误地设置了我们的地址,
                         * 导致无法正常解密,平常使用不需要过滤!
                         */
                        SenparcTrace.SendCustomLog("RefundNotifyUrl 的 AppId 不正确",
                                                   $"appId:{appId}\r\nmch_id:{mch_id}\r\nreq_info:{req_info}");
                        return(Content("faild"));
                    }

                    var decodeReqInfo = TenPayV3Util.DecodeRefundReqInfo(req_info, TenPayV3Info.Key);
                    var decodeDoc     = XDocument.Parse(decodeReqInfo);

                    //获取接口中需要用到的信息
                    string transaction_id       = decodeDoc.Root.Element("transaction_id").Value;
                    string out_trade_no         = decodeDoc.Root.Element("out_trade_no").Value;
                    string refund_id            = decodeDoc.Root.Element("refund_id").Value;
                    string out_refund_no        = decodeDoc.Root.Element("out_refund_no").Value;
                    int    total_fee            = int.Parse(decodeDoc.Root.Element("total_fee").Value);
                    int?   settlement_total_fee = decodeDoc.Root.Element("settlement_total_fee") != null
                            ? int.Parse(decodeDoc.Root.Element("settlement_total_fee").Value)
                            : null as int?;

                    int    refund_fee = int.Parse(decodeDoc.Root.Element("refund_fee").Value);
                    int    tosettlement_refund_feetal_fee = int.Parse(decodeDoc.Root.Element("settlement_refund_fee").Value);
                    string refund_status         = decodeDoc.Root.Element("refund_status").Value;
                    string success_time          = decodeDoc.Root.Element("success_time").Value;
                    string refund_recv_accout    = decodeDoc.Root.Element("refund_recv_accout").Value;
                    string refund_account        = decodeDoc.Root.Element("refund_account").Value;
                    string refund_request_source = decodeDoc.Root.Element("refund_request_source").Value;


                    WeixinTrace.SendCustomLog("RefundNotifyUrl被访问", "验证通过");

                    //进行后续业务处理
                }
            }
            catch (Exception ex)
            {
                responseMsg = ex.Message;
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
            }

            string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", responseCode, responseMsg);

            return(Content(xml, "text/xml"));
        }
Beispiel #13
0
        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));
            }
        }
        public void CreateStockAsyncTest()
        {
            var key = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);

            var TenPayV3Info = TenPayV3InfoCollection.Data[key];

            // 代金券批次发放使用规则 发放10张优惠券 预算1000分 每个用户限领10张 开启防刷
            var stock_use_rule = new CreateStockRequsetData.Stock_Use_Rule(2, 4, null, 2, false, true);

            // 代金券使用规则 指明可使用本批次代金券的商户号
            var coupon_use_rule = new CreateStockRequsetData.Coupon_Use_Rule(null, null, null, null, null, null, null, new string[] { TenPayV3Info.MchId /*"1610625015"*/ });

            // TODO:流水号?这样是否有效?
            var out_request_no = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));

            var requestData = new CreateStockRequsetData("单元测试代金券批次", "用于单元测试", TenPayV3Info.MchId, new TenpayDateTime(DateTime.Now.AddMinutes(1)), new TenpayDateTime(DateTime.Now.AddMinutes(30)), stock_use_rule, null, coupon_use_rule, true, "NORMAL", out_request_no);


            /* 提示:
             * 使用此功能必须在后台【产品中心】开通【预充值代金券】功能!
             */

            var marketingApis = new MarketingApis();

            try
            {
                // stock_type = "NORMAL" 的情况
                createStockResult = marketingApis.CreateStockAsync(requestData).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(TenpayApiRequestException));
                Console.WriteLine(ex.Message);
                Assert.IsTrue(ex.Message.Contains("必填"));
            }

            try
            {
                //修改参数
                requestData.coupon_use_rule.fixed_normal_coupon = new CreateStockRequsetData.Coupon_Use_Rule.Fixed_Normal_Coupon(6, 1);
                createStockResult = marketingApis.CreateStockAsync(requestData).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(TenpayApiRequestException));
                Console.WriteLine(ex.Message);
                Assert.IsTrue(ex.Message.Contains("必须等于"));
            }

            try
            {
                //修改参数
                requestData.coupon_use_rule.fixed_normal_coupon.coupon_amount = 2;// coupon_amount = max_coupons * max_coupons_per_user
                createStockResult = marketingApis.CreateStockAsync(requestData).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(TenpayApiRequestException));
                Console.WriteLine(ex.Message);
                Assert.IsTrue(ex.Message.Contains("必须小于等于"));
            }

            //修改参数
            requestData.coupon_use_rule.fixed_normal_coupon.transaction_minimum = 2;// coupon_amount = max_coupons * max_coupons_per_user
            createStockResult = marketingApis.CreateStockAsync(requestData).GetAwaiter().GetResult();


            Assert.IsTrue(createStockResult.ResultCode.Additional.Contains("可用商户不符合规则,请检查"));

            //修改参数
            requestData.no_cash = false;//只有当参数为 false 时,可以使用本商户,否则只能使用其他商户
            createStockResult   = marketingApis.CreateStockAsync(requestData).GetAwaiter().GetResult();


            Console.WriteLine("微信支付 V3 创建代金券接口批次结果:" + createStockResult.ToJson(true));

            Assert.IsNotNull(createStockResult);
            Assert.IsTrue(createStockResult.ResultCode.Success);
            Assert.IsTrue(createStockResult.VerifySignSuccess == true);//通过验证
        }
Beispiel #15
0
        public HttpResponseMessage Notify()
        {
            var respData = new Dictionary <string, string>();

            try
            {
                // 读取微信支付返回结果
                var resp = ReadFromInputStream();
                var dict = ReadXml(resp);

                LogHelper.Info("\n\nnotify 接收内容:\n" + JsonHelper.Serialize(dict));

                // 微信订单号
                string transactionId, tradeNo;
                dict.TryGetValue("transaction_id", out transactionId);
                dict.TryGetValue("out_trade_no", out tradeNo);

                #region 1. 检查支付结果中transaction_id是否存在

                if (string.IsNullOrEmpty(transactionId))
                {
                    //若transaction_id不存在,则立即返回结果给微信支付后台
                    respData.Add("return_code", "FAIL");
                    respData.Add("return_msg", "支付结果中微信订单号不存在");

                    var xml = DictToXml(respData);
                    LogHelper.Info("\n\nnotify 响应内容:\n" + xml);

                    return(RetMessage(xml));
                }

                #endregion

                #region 2. 同步查询订单,判断订单真实性

                var appId = ConfigurationManager.AppSettings["appId"];
                var mchId = ConfigurationManager.AppSettings["mchId"];
                var key   = ConfigurationManager.AppSettings["appKey"];

                var reqData   = new TenPayV3OrderQueryRequestData(appId, mchId, transactionId, TenPayV3Util.GetNoncestr(), "", key);
                var queryData = TenPayV3.OrderQuery(reqData);

                if (queryData.result_code == "SUCCESS" && queryData.result_code == "SUCCESS")
                {//查询订单成功
                    // 业务逻辑:更新订单状态
                    if (_orderService.UpdateOrderStatus(tradeNo, (int)Enums.OrderStatus.未发货))
                    {
                        respData.Add("return_code", "SUCCESS");
                        respData.Add("return_msg", "OK");

                        var xml = DictToXml(respData);
                        LogHelper.Info("\n\nnotify 响应内容:\n" + xml);

                        return(RetMessage(xml));
                    }
                    else
                    {
                        respData.Add("return_code", "FAIL");
                        respData.Add("return_msg", "订单状态修改失败");

                        var xml = DictToXml(respData);
                        LogHelper.Info("\n\nnotify 响应内容:\n" + xml);

                        return(RetMessage(xml));
                    }
                }
                else
                {//若订单查询失败,则立即返回结果给微信支付后台
                    respData.Add("return_code", "FAIL");
                    respData.Add("return_msg", "订单查询失败");

                    var xml = DictToXml(respData);
                    LogHelper.Info("\n\nnotify 响应内容:\n" + xml);

                    return(RetMessage(xml));
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Info("\n\nnotify 异常:\n", ex);
                respData.Add("return_code", "FAIL");
                respData.Add("return_msg", "系统异常:" + ex.Message);

                var xml = DictToXml(respData);
                return(RetMessage(xml));
            }
        }
Beispiel #16
0
        /// <summary>
        /// 患者微信支付下订单
        /// </summary>
        /// <returns></returns>
        public async Task <TencentJSPayRequestModel> UnifiedorderAsync(bool sharing, string spbillCreateIp, YaeherConsultation consul, YaeherUser user, ServiceMoneyList product, SystemConfigs tencentparam)
        {
            TencentJSPayRequestModel jspay = new TencentJSPayRequestModel();

            try
            {
                TenPayV3Info tenPayV3Info = new TenPayV3Info(tencentparam.AppID, tencentparam.AppSecret, tencentparam.TenPayMchId, tencentparam.TenPayKey, tencentparam.TenPayNotify, tencentparam.TenPayWxOpenNotify);

                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                //  var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                // var sjs =;//随机数
                var sjs       = consul.ConsultNumber.Substring(3, consul.ConsultNumber.Length - 3) + TenPayV3Util.BuildRandomStr(6);
                var sp_billno = sjs;
                //   var sp_billno = string.Format("{0}{1}", sjs, user.Id);
                var shortbillno = sp_billno;

                TenPayInfo tenPayInfo = new TenPayInfo();
                //   var body = product == null ? "怡芽问诊" : product.DoctorName+"医生" + product.ServiceType;
                var body      = "怡禾健康咨询";
                var price     = product == null ? 100 : (int)(product.ServiceExpense * 100);//单位:分
                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr  = TenPayV3Util.GetNoncestr();

                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, body, sp_billno, price, spbillCreateIp, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, user.WecharOpenID, tenPayV3Info.Key, nonceStr);
                //CreateWrite("C:\\回调.txt", "订单参数:" + JsonHelper.ToJson(xmlDataInfo));
                var result = await UnifiedorderAsync(xmlDataInfo, sharing? "Y" : "N"); //调用统一订单接口

                //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);

                if (result.IsResultCodeSuccess())
                {
                    var package = string.Format("prepay_id={0}", result.prepay_id);
                    var paysign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key);

                    jspay.product   = product;
                    jspay.timeStamp = timeStamp;
                    jspay.nonceStr  = nonceStr;
                    jspay.package   = package;
                    jspay.paySign   = paysign;
                    jspay.appid     = tenPayV3Info.AppId;
                    jspay.sp_billno = shortbillno;
                    jspay.code      = result.result_code;
                    jspay.msg       = result.return_msg;
                }
                else
                {
                    jspay.code = result.result_code;
                    jspay.msg  = result.return_msg;
                }
            }
            catch (Exception ex)
            {
                jspay.code = "FAIL";
                jspay.msg  = ex.Message.ToString();
            }
            return(jspay);
        }
Beispiel #17
0
        public async Task <ActionResult> Index(FormCollection collection)
        {
            ModelForOrder order        = null;
            int           totalfee     = 0;
            object        objResult    = "";
            string        strTotal_fee = Request.Form["totalfee"];

            if (int.TryParse(strTotal_fee, out totalfee))
            {
                totalfee = totalfee * 100;
                OAuthAccessTokenResult tokenResult = Session["AccessToken"] as OAuthAccessTokenResult;
                string body           = "瑞雪管理系统充值";
                string timeStamp      = TenPayV3Util.GetTimestamp();
                string nonceStr       = TenPayV3Util.GetNoncestr();
                string openid         = tokenResult.openid;
                string tenPayV3Notify = "http://w.roccode.cn/pay/ResultNotify";
                string key            = "8f75e82b6f1b7d82f7952121a6801b4a";
                string billNo         = string.Format("{0}{1}{2}", WeixinData.MchId, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));
                var    xmlDataInfo    = new TenPayV3UnifiedorderRequestData(WeixinData.AppId, WeixinData.MchId, body, billNo, totalfee, Request.UserHostAddress,
                                                                            tenPayV3Notify, Senparc.Weixin.MP.TenPayV3Type.JSAPI, openid, key, nonceStr);

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

                if (result.result_code == "SUCCESS")
                {
                    order              = new ModelForOrder();
                    order.appId        = result.appid;
                    order.nonceStr     = result.nonce_str;
                    order.packageValue = "prepay_id=" + result.prepay_id;
                    order.paySign      = TenPayV3.GetJsPaySign(result.appid, timeStamp, result.nonce_str, order.packageValue, key);
                    order.timeStamp    = timeStamp;
                    order.msg          = "预支付订单生成成功";

                    // 保存预支付订单信息
                    string id = Session["readerId"] as string;
                    //OAuthUserInfo userInfo = Session["UserInfo"] as OAuthUserInfo;
                    if (!string.IsNullOrEmpty(id))
                    {
                        string groundCode = id.Substring(0, 6);
                        string gameCode   = id.Substring(6, 2);
                        string readerCode = id.Substring(8, 3);
                        //string sn = id.Substring(11, 5);
                        db.Orders.Add(new Order()
                        {
                            GroundCode = groundCode,
                            GameCode   = gameCode,
                            ReaderCode = readerCode,
                            Amt        = totalfee / 100,
                            BillNo     = billNo,
                            //WeiXinCode = userInfo.nickname,
                            //Openid = userInfo.openid,
                            //Unionid = userInfo.unionid
                        });
                        db.SaveChanges();
                    }
                }
            }
            else
            {
                order     = new ModelForOrder();
                order.msg = "输入充值数量异常";
            }
            if (order == null)
            {
                order     = new ModelForOrder();
                order.msg = "预支付订单生成失败,请重试!";
            }
            objResult = order;
            return(Json(objResult));
        }
Beispiel #18
0
        public ActionResult JsApi(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

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

            //获取产品信息
            var stateData = state.Split('|');
            //商品
            string           Id      = stateData[0];
            Spl_ProductModel product = m_BLL.GetById(Id);

            if (product == null)
            {
                return(Content("商品信息不存在,或非法进入!1002"));
            }
            //todo 这里需要为用户保存订单
            //todo 如果用户的订单已经存在,那么不需要再次添加,激活此订单



            ViewData["product"] = product;



            //通过,用code换取access_token
            //-------------------开起来支付
            var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);

            if (openIdResult.errcode != ReturnCode.请求成功)
            {
                return(Content("错误:" + openIdResult.errmsg));
            }

            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";
            //把系统ID当成订单号
            string sp_billno = product.Id;



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

            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);               //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);              //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                     //随机字符串
            packageReqHandler.SetParameter("body", product.Name + " " + product.Code); //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                 //商家订单号
            decimal price = product.Price;

            packageReqHandler.SetParameter("total_fee", price.ToString());               //////////////////////商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);   //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);               //用户的openId



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

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(null);

            paySignReqHandler.SetParameter("appId", TenPayV3Info.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            ViewData["appId"]     = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"]  = nonceStr;
            ViewData["package"]   = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"]   = paySign;

            return(View());
        }
Beispiel #19
0
        public ActionResult JsApi(string code, string state)
        {
            var sessionCount = GetSessionCount();

            sessionCount++;
            SetSessionCount(sessionCount);
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

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



            //获取产品信息
            var stateData = state.Split('|');
            int productId = 0;

            //return Content(string.Format("已經到這裡 {0}:{1}", stateData[0], stateData[1]));
            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;
                }
            }
            var identityNo = state[2];  //身份证号码

            string openId;
            OAuthAccessTokenResult openIdResult = null;

            #region 解決 Auth 出現 40028(Invalid code)錯誤
            try
            {
                //通过,用code换取access_token

                var isSecondRequest = false;
                lock (OAuthCodeCollectionLock)
                {
                    isSecondRequest = OAuthCodeCollection.ContainsKey(code);
                }

                if (!isSecondRequest)
                {
                    //第一次请求
                    //LogUtility.Weixin.DebugFormat("第一次微信OAuth到达,code:{0}", code);
                    lock (OAuthCodeCollectionLock)
                    {
                        OAuthCodeCollection[code] = null;
                    }
                }
                else
                {
                    //第二次请求
                    //LogUtility.Weixin.DebugFormat("第二次微信OAuth到达,code:{0}", code);

                    lock (OAuthCodeCollectionLock)
                    {
                        openIdResult = OAuthCodeCollection[code];
                    }
                }

                try
                {
                    try
                    {
                        openIdResult = openIdResult ?? OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);
                    }
                    catch (Exception ex)
                    {
                        return(Content("OAuth AccessToken错误:" + ex.Message));
                    }

                    if (openIdResult != null)
                    {
                        lock (OAuthCodeCollectionLock)
                        {
                            OAuthCodeCollection[code] = openIdResult;
                        }
                    }
                }
                catch (ErrorJsonResultException ex)
                {
                    if (ex.JsonResult.errcode == ReturnCode.合法的oauth_code)
                    {
                        //code已经被使用过
                        lock (OAuthCodeCollectionLock)
                        {
                            openIdResult = OAuthCodeCollection[code];
                        }
                    }
                }

                openId = openIdResult != null ? openIdResult.openid : null;
            }
            catch (Exception ex)
            {
                return(Content("授权过程发生错误:" + ex.Message));
            }
            #endregion


            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

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

            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);                                             //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);                                            //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                                                   //随机字符串
            packageReqHandler.SetParameter("body", product == null ? "test" : product.Name);                         //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                                               //商家订单号
            packageReqHandler.SetParameter("total_fee", product == null ? "100" : (product.Price * 100).ToString()); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                             //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);                               //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                             //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);                                           //用户的openId

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

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(null);
            paySignReqHandler.SetParameter("appId", TenPayV3Info.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            ViewData["appId"]     = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"]  = nonceStr;
            ViewData["package"]   = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"]   = paySign;

            return(View());
        }
Beispiel #20
0
        public async Task <IActionResult> RefundGet([FromQuery] RefundModel refund)
        {
            try
            {
                //  WeixinTrace.SendCustomLog("进入退款流程", "1");
                if (string.IsNullOrWhiteSpace(refund.NonceStr))
                {
                    refund.NonceStr = TenPayV3Util.GetNoncestr();
                }
                if (string.IsNullOrWhiteSpace(refund.OpUserId))
                {
                    refund.OpUserId = TenPyConfigRead.MchId;
                }

                if (string.IsNullOrWhiteSpace(refund.OutTradeNo) && string.IsNullOrWhiteSpace(refund.TransactionId))
                {
                    return(BadRequest("需要OutTradeNo,TransactionId之一"));
                }

                //      string outTradeNo = HttpContext.Session.GetString("BillNo");

                // WeixinTrace.SendCustomLog("进入退款流程", "2 outTradeNo:" + refund.OutTradeNo);

                refund.SignType = "MD5";

                var dataInfo = new TenPayV3RefundRequestData(
                    appId: TenPyConfigRead.AppId,
                    mchId: TenPyConfigRead.MchId,
                    key: TenPyConfigRead.Key,
                    deviceInfo: refund.DeviceInfo,
                    nonceStr: refund.NonceStr,
                    transactionId: refund.TransactionId,
                    outTradeNo: refund.OutTradeNo,
                    outRefundNo: refund.OutRefundNo,
                    totalFee: refund.TotalFee,
                    refundFee: refund.RefundFee,
                    opUserId: refund.OpUserId,
                    refundAccount: refund.RefundAccount,
                    notifyUrl: refund.NotifyUrl);


                //#region 旧方法
                //var cert = @"D:\cert\apiclient_cert_SenparcRobot.p12";//根据自己的证书位置修改
                //var password = TenPayV3Info.MchId;//默认为商户号,建议修改
                //var result = TenPayV3.Refund(dataInfo, TenPyConfigRead.CertPath, Int32.Parse(TenPyConfigRead.CertSecret));
                //#endregion

                #region 新方法(Senparc.Weixin v6.4.4+)
                var result = await TenPayV3.RefundAsync(_serviceProvider, dataInfo);//证书地址、密码,在配置文件中设置,并在注册微信支付信息时自动记录

                #endregion
                var log = _logger.CreateLogger("申请退款");
                if (result.return_code == "FAIL")
                {
                    log.LogError($"退款单号(out_refund_no):{refund.OutRefundNo}   通讯标记(return_code):{result.return_code}  {result.return_msg}");
                }
                if (result.result_code == "FAIL")
                {
                    log.LogError($"退款单号(out_refund_no):{refund.OutRefundNo}   业务结果(result_code):{result.result_code}\n{result.err_code}:{result.err_code_des}");
                }
                else if (result.result_code == "SUCCESS")
                {
                    log.LogInformation($"退款单号(out_refund_no):{refund.OutRefundNo}  业务结果(result_code):{result.result_code}");
                }
                // WeixinTrace.SendCustomLog("进入退款流程", "3 Result:" + result.ToJson());
                //   ViewData["Message"] = $"退款结果:{result.result_code} {result.err_code_des}。您可以刷新当前页面查看最新结果。";
                return(Ok(new
                {
                    respond = result,
                    request = refund
                }));
                //return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));

                throw;
            }

            #region 原始方法

            //RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		 //公众账号ID
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);	     //商户号
            //packageReqHandler.SetParameter("out_trade_no", "124138540220170502163706139412"); //填入商家订单号
            ////packageReqHandler.SetParameter("out_refund_no", "");                //填入退款订单号
            //packageReqHandler.SetParameter("total_fee", "");                    //填入总金额
            //packageReqHandler.SetParameter("refund_fee", "100");                //填入退款金额
            //packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id,默认就是商户号
            //packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);	                    //签名
            ////退款需要post的数据
            //string data = packageReqHandler.ParseXML();

            ////退款接口地址
            //string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            ////本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            //string cert = @"D:\cert\apiclient_cert_SenparcRobot.p12";
            ////私钥(在安装证书时设置)
            //string password = TenPayV3Info.MchId;
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ////调用证书
            //X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            //#region 发起post请求
            //HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //webrequest.ClientCertificates.Add(cer);
            //webrequest.Method = "post";

            //byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            //webrequest.ContentLength = postdatabyte.Length;
            //Stream stream;
            //stream = webrequest.GetRequestStream();
            //stream.Write(postdatabyte, 0, postdatabyte.Length);
            //stream.Close();

            //HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            //StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            //string responseContent = streamReader.ReadToEnd();
            //#endregion

            //// var res = XDocument.Parse(responseContent);
            ////string openid = res.Element("xml").Element("out_refund_no").Value;
            //return Content("申请成功:<br>" + HttpUtility.RequestUtility.HtmlEncode(responseContent));

            #endregion
        }
Beispiel #21
0
        public void SendCardAsyncTest()
        {
            var key          = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);
            var TenPayV3Info = TenPayV3InfoCollection.Data[key];

            // 如果还未创建建立合作关系 则建立合作关系
            if (buildPartnershipsResult is null)
            {
                BuildPartnershipsAsyncTest();
            }
            var card_id = "pIJMr5MMiIkO_93VtPyIiEk2DZ4w";//TODO: 消费卡ID,即card_id。card_id获取方法请参见《接入前准备》配置应用中的创建消费卡。https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter5_6_2.shtml#part-6

            // TODO:流水号?这样是否有效?
            var out_request_no = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));

            var requestData = new SendCardRequestData(card_id, TenPayV3Info.AppId, openId, out_request_no, new TenpayDateTime(DateTime.Now));

            var marketingApis = new MarketingApis();
            var result        = marketingApis.SendCardAsync(requestData).GetAwaiter().GetResult();

            Console.WriteLine("微信支付 V3 发放消费卡接口测试结果:" + result.ToJson(true));

            Assert.IsNotNull(result);
            Assert.IsTrue(result.ResultCode.Success);
            Assert.IsTrue(result.VerifySignSuccess == true);//通过验证
        }
Beispiel #22
0
        public async Task <IActionResult> Unifiedorder(UnifiedorderModel unifiedorder)
        {
            string         appid      = TenPyConfigRead.AppId;
            string         scret      = TenPyConfigRead.AppSecret;
            DateTimeOffset?timestart  = null;
            DateTime?      timeexpire = null;
            string         feetype    = "CNY";

            //      var result = await WxLogin.SendCodeForOpenId(appid, scret, code);
            //     WxLoginModel loginModel= JsonSerializer.Deserialize<WxLoginModel>(result);
            if (string.IsNullOrWhiteSpace(unifiedorder.NotifyUrl))
            {
                unifiedorder.NotifyUrl = TenPyConfigRead.TenPayV3_WxOpenNotify;
            }
            if (string.IsNullOrWhiteSpace(unifiedorder.NonceStr))
            {
                unifiedorder.NonceStr = TenPayV3Util.GetNoncestr();
            }
            if (!string.IsNullOrWhiteSpace(unifiedorder.TimeStart))
            {
                timestart = DateTimeOffset.Parse(unifiedorder.TimeStart);
            }
            if (!string.IsNullOrWhiteSpace(unifiedorder.TimeExpire))
            {
                timeexpire = DateTime.Parse(unifiedorder.TimeExpire);
            }
            if (!string.IsNullOrWhiteSpace(unifiedorder.FeeType))
            {
                feetype = unifiedorder.FeeType;
            }


            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(appId: TenPyConfigRead.AppId,
                                                                  mchId: TenPyConfigRead.MchId,
                                                                  body: unifiedorder.Body,
                                                                  outTradeNo: unifiedorder.OutTradeNo,
                                                                  totalFee: unifiedorder.TotalFee,
                                                                  spbillCreateIp: unifiedorder.SpbillCreateIP,
                                                                  notifyUrl: unifiedorder.NotifyUrl,
                                                                  tradeType: TenPayV3Type.JSAPI,
                                                                  openid: unifiedorder.OpenId,
                                                                  key: TenPyConfigRead.Key,
                                                                  nonceStr: unifiedorder.NonceStr,
                                                                  deviceInfo: unifiedorder.DeviceInfo,
                                                                  timeStart: timestart,
                                                                  timeExpire: timeexpire,
                                                                  detail: unifiedorder.Detail,
                                                                  attach: unifiedorder.Attach,
                                                                  feeType: feetype,
                                                                  goodsTag: unifiedorder.GoodsTag,
                                                                  productId: unifiedorder.ProductId,
                                                                  limitPay: unifiedorder.LimitPay);

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

            var log = _logger.CreateLogger("统一下单");

            if (result.return_code == "FAIL")
            {
                log.LogError($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo}   通讯标记(return_code):{result.return_code}  {result.return_msg}");
            }
            if (result.result_code == "FAIL")
            {
                log.LogError($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo}   业务结果(result_code):{result.result_code}\n{result.err_code}:{result.err_code_des}");
            }
            else if (result.result_code == "SUCCESS")
            {
                log.LogInformation($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo}   业务结果(result_code):{result.result_code}");
            }
            var timeStamp = TenPayV3Util.GetTimestamp();

            var package = string.Format("prepay_id={0}", result.prepay_id);
            var paysign = TenPayV3.GetJsPaySign(TenPyConfigRead.AppId, timeStamp, unifiedorder.NonceStr, package, TenPyConfigRead.Key);

            // return Ok(new { timeStamp, nonceStr, package, paysign });
            return(Ok(new
            {
                client = new
                {
                    timeStamp,
                    unifiedorder.NonceStr,
                    package,
                    paysign,
                    sign = "MD5"
                },
                respond = result,
                request = unifiedorder
            }));
        }
Beispiel #23
0
        private string SendHB(string opid, string stid, string hb, string uname, string picurl, string cursjd)
        {
            #region 设置参数信息
            try
            {
                string         mchbillno         = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
                string         nonceStr          = TenPayV3Util.GetNoncestr();
                RequestHandler packageReqHandler = new RequestHandler(null);

                //设置package订单参数
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                 //随机字符串
                packageReqHandler.SetParameter("wxappid", WebConfigurationManager.AppSettings["wxappid6"]);            //公众账号ID
                packageReqHandler.SetParameter("mch_id", WebConfigurationManager.AppSettings["WeixinPay_PartnerId6"]); //商户号
                packageReqHandler.SetParameter("mch_billno", mchbillno);                                               //填入商家订单号
                packageReqHandler.SetParameter("send_name", WebConfigurationManager.AppSettings["sendname6"]);         //红包发送者名称
                packageReqHandler.SetParameter("re_openid", opid);                                                     //接受收红包的用户的openId
                packageReqHandler.SetParameter("total_amount", hb);                                                    //付款金额,单位分
                packageReqHandler.SetParameter("total_num", "1");                                                      //红包发放总人数
                packageReqHandler.SetParameter("wishing", WebConfigurationManager.AppSettings["hbzf6"]);               //红包祝福语
                packageReqHandler.SetParameter("client_ip", _context.Request.UserHostAddress);                         //调用接口的机器Ip地址
                packageReqHandler.SetParameter("act_name", WebConfigurationManager.AppSettings["hbname6"]);            //活动名称
                packageReqHandler.SetParameter("remark", WebConfigurationManager.AppSettings["hbDesc6"]);              //备注信息
                string sign = packageReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key6"]);
                packageReqHandler.SetParameter("sign", sign);                                                          //签名
                //发红包需要post的数据
                string data = packageReqHandler.ParseXML();
                //发红包接口地址
                string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
                //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
                string cert = WebConfigurationManager.AppSettings["zswz6"];
                //私钥(在安装证书时设置)
                string password = WebConfigurationManager.AppSettings["WeixinPay_PartnerId6"];
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //调用证书
                X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
                #endregion
                #region 发起post请求

                HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webrequest.ClientCertificates.Add(cer);
                webrequest.Method = "post";
                byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
                webrequest.ContentLength = postdatabyte.Length;
                Stream stream;
                stream = webrequest.GetRequestStream();
                stream.Write(postdatabyte, 0, postdatabyte.Length);
                stream.Close();
                HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
                StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
                string          responseContent = streamReader.ReadToEnd();

                WxZFData tdata = new WxZFData();
                tdata.FromXml(responseContent);
                string return_code = tdata.GetValue("return_code").ToString(); //状态码
                string return_msg  = tdata.GetValue("return_msg").ToString();  //状态码

                var str = string.Empty;
                if ("SUCCESS".Equals(return_code))
                {
                    string result_code = tdata.GetValue("result_code").ToString();
                    if ("SUCCESS".Equals(result_code))
                    {
                        //红包发送成功!
                        using (WXDBEntities db = new WXDBEntities())
                        {
                            var model = new Oders()
                            {
                                Title        = WebConfigurationManager.AppSettings["hbDesc6"],
                                OrderId      = "1233445",
                                Number       = 1,
                                Mobile       = "",
                                Soucre       = opid,
                                Remark       = HttpUtility.UrlDecode(uname).Replace("?", ""),
                                AddTime      = DateTime.Now,
                                UpdateTime   = DateTime.Now,
                                UpdateUser   = "******",
                                OrderStatus  = 0,
                                Status       = 0,
                                Orders       = 0,
                                Extent1      = stid,
                                Extent2      = picurl,
                                AddUser      = cursjd,
                                CheckTime    = DateTime.Now,
                                CheckoutTime = DateTime.Now,
                                Totals       = Convert.ToInt32(hb)
                            };
                            db.Oders.AddObject(model);
                            db.SaveChanges();
                        }
                        //加入数据库操作
                        str = "1|发送红包成功|" + hb;
                    }
                    else
                    {
                        string err_code     = tdata.GetValue("err_code").ToString();
                        string err_code_des = tdata.GetValue("err_code_des").ToString();
                        using (WXDBEntities db = new WXDBEntities())
                        {
                            OperateLoginfo mt = new OperateLoginfo()
                            {
                                Title      = "永达红包",
                                Descs      = err_code,
                                AddTime    = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                Status     = 0,
                                Orders     = 0,
                                Extent1    = "",
                                Extent2    = err_code_des,
                                LogType    = 1
                            };
                            db.OperateLoginfo.AddObject(mt);
                            db.SaveChanges();
                        }
                        //红包发送失败
                        str = "2|发送红包失败!";
                    }
                }
                else
                {
                    using (WXDBEntities db = new WXDBEntities())
                    {
                        OperateLoginfo mt = new OperateLoginfo()
                        {
                            Title      = "永达红包",
                            Descs      = return_msg,
                            AddTime    = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Status     = 0,
                            Orders     = 0,
                            Extent1    = "",
                            Extent2    = "",
                            LogType    = 1
                        };
                        db.OperateLoginfo.AddObject(mt);
                        db.SaveChanges();
                    }
                    str = "3|发送红包失败";
                }
                return(str);
            }
            catch (Exception ex)
            {
                using (WXDBEntities db = new WXDBEntities())
                {
                    OperateLoginfo mt = new OperateLoginfo()
                    {
                        Title      = "永达红包",
                        Descs      = ex.Message,
                        AddTime    = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        Status     = 0,
                        Orders     = 0,
                        Extent1    = hb,
                        Extent2    = "",
                        LogType    = 6
                    };
                    db.OperateLoginfo.AddObject(mt);
                    db.SaveChanges();
                }
                return("4|获取失败!");
            }
            #endregion
        }
Beispiel #24
0
        public HttpResult JsApi(int productId)
        {
            string errorMessage = string.Empty;

            try
            {
                //获取产品信息
                var products = ProductModel.GetFakeProductList();
                var product  = products.FirstOrDefault(z => z.Id == productId);
                if (product == null)
                {
                    return(HttpResult.WeChatError("商品信息不存在!", null));
                }

                var openId = Commons.Current.WxOpenId;

                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                string sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmssfff"),
                                                 TenPayV3Util.BuildRandomStr(6));
                //注意:以上订单号仅作为演示使用,如果访问量比较大,建议增加订单流水号的去重检查。

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

                var body        = product.Name;
                var price       = (int)(product.Price * 100);//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr);
                xmlDataInfo.NotifyUrl = "https://yufaquan.cn/wx/PayV3/PayNotifyUrl";

                var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口
                                                                 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                //TO DO
                //记录订单信息,留给退款申请接口测试使用
                //HttpContext.Session.SetString("BillNo", sp_billno);
                //HttpContext.Session.SetString("BillFee", price.ToString());


                var res = new
                {
                    product,
                    appId = TenPayV3Info.AppId,
                    timeStamp,
                    nonceStr,
                    package,
                    paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key)
                };
                return(HttpResult.Success(res));
            }
            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(HttpResult.WeChatError(ex.Message, null));
            }
        }
        public ActionResult JsApi(int productId, int hc)
        {
            try
            {
                //获取产品信息
                var products = ProductModel.GetFakeProductList();
                var product  = products.FirstOrDefault(z => z.Id == productId);
                if (product == null || product.GetHashCode() != hc)
                {
                    return(Content("商品信息不存在,或非法进入!1002"));
                }

                //var openId = User.Identity.Name;
                var openId = (string)Session["OpenId"];

                string sp_billno = Request["order_no"];
                if (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                              TenPayV3Util.BuildRandomStr(6));
                }
                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 : (int)(product.Price * 100);//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.JSAPI, 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["product"] = product;

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

                //临时记录订单信息,留给退款申请接口测试使用
                Session["BillNo"]  = sp_billno;
                Session["BillFee"] = price;

                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));
            }
        }
Beispiel #26
0
        /// <summary>
        /// 原生支付 模式二
        /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。
        /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付
        /// </summary>
        /// <returns></returns>
        public ActionResult NativeByCodeUrl()
        {
            //创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);

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

            //商品Id,用户自行定义
            string productId = SystemTime.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", HttpContext.UserHostAddress()?.ToString());
            //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 TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId,
                                                                  TenPayV3Info.MchId,
                                                                  "test",
                                                                  sp_billno,
                                                                  1,
                                                                  HttpContext.UserHostAddress()?.ToString(),
                                                                  TenPayV3Info.TenPayV3Notify,
                                                                  TenPay.TenPayV3Type.NATIVE,
                                                                  null,
                                                                  TenPayV3Info.Key,
                                                                  nonceStr,
                                                                  productId: productId);
            //调用统一订单接口
            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);
            var bw = new ZXing.BarcodeWriterPixelData();

            var pixelData = bw.Write(bitMatrix);

            using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
            {
                using (var ms = new MemoryStream())
                {
                    var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                    try
                    {
                        // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
                        System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
                    }
                    finally
                    {
                        bitmap.UnlockBits(bitmapData);
                    }
                    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                    return(File(ms, "image/png"));
                }
            }
        }
        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Refund()
        {
            string nonceStr = TenPayV3Util.GetNoncestr();

            string outTradeNo  = (string)(Session["BillNo"]);
            string outRefundNo = "OutRefunNo-" + DateTime.Now.Ticks;
            int    totalFee    = (int)(Session["BillFee"]);
            int    refundFee   = totalFee;
            string opUserId    = TenPayV3Info.MchId;
            var    notifyUrl   = "http://sdk.weixin.senparc.com/TenPayV3/RefundNotifyUrl";
            var    dataInfo    = new TenPayV3RefundRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, TenPayV3Info.Key,
                                                               null, nonceStr, null, outTradeNo, outRefundNo, totalFee, refundFee, opUserId, null, notifyUrl: notifyUrl);
            var cert     = @"D:\cert\apiclient_cert_SenparcRobot.p12"; //根据自己的证书位置修改
            var password = TenPayV3Info.MchId;                         //默认为商户号,建议修改
            var result   = TenPayV3.Refund(dataInfo, cert, password);

            return(Content(string.Format("退款结果:{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des)));

            //return Json(result, JsonRequestBehavior.AllowGet);

            #region 原始方法

            //RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		 //公众账号ID
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);	     //商户号
            //packageReqHandler.SetParameter("out_trade_no", "124138540220170502163706139412"); //填入商家订单号
            ////packageReqHandler.SetParameter("out_refund_no", "");                //填入退款订单号
            //packageReqHandler.SetParameter("total_fee", "");                    //填入总金额
            //packageReqHandler.SetParameter("refund_fee", "100");                //填入退款金额
            //packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id,默认就是商户号
            //packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);	                    //签名
            ////退款需要post的数据
            //string data = packageReqHandler.ParseXML();

            ////退款接口地址
            //string url = "http://api.mch.weixin.qq.com/secapi/pay/refund";
            ////本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            //string cert = @"D:\cert\apiclient_cert_SenparcRobot.p12";
            ////私钥(在安装证书时设置)
            //string password = TenPayV3Info.MchId;
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ////调用证书
            //X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            //#region 发起post请求
            //HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //webrequest.ClientCertificates.Add(cer);
            //webrequest.Method = "post";

            //byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            //webrequest.ContentLength = postdatabyte.Length;
            //Stream stream;
            //stream = webrequest.GetRequestStream();
            //stream.Write(postdatabyte, 0, postdatabyte.Length);
            //stream.Close();

            //HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            //StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            //string responseContent = streamReader.ReadToEnd();
            //#endregion

            //// var res = XDocument.Parse(responseContent);
            ////string openid = res.Element("xml").Element("out_refund_no").Value;
            //return Content("申请成功:<br>" + HttpUtility.RequestUtility.HtmlEncode(responseContent));

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

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

            //通过,用code换取access_token
            var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);

            if (openIdResult.errcode != ReturnCode.请求成功)
            {
                return(Content("错误:" + openIdResult.errmsg));
            }

            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

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

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

            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);                 //公众账号ID
            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", "100");                          //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);   //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);               //用户的openId

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

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(null);

            paySignReqHandler.SetParameter("appId", TenPayV3Info.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            ViewData["appId"]     = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"]  = nonceStr;
            ViewData["package"]   = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"]   = paySign;

            return(View());
        }
Beispiel #29
0
        private string SendHB(HttpContext context, string opid, string name, string phone, string hb)
        {
            #region 设置参数信息

            string mchbillno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);

            string         nonceStr          = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);                                                //随机字符串
            packageReqHandler.SetParameter("wxappid", WebConfigurationManager.AppSettings["wxappid"]);            //公众账号ID
            packageReqHandler.SetParameter("mch_id", WebConfigurationManager.AppSettings["WeixinPay_PartnerId"]); //商户号
            packageReqHandler.SetParameter("mch_billno", mchbillno);                                              //填入商家订单号
            packageReqHandler.SetParameter("send_name", "D3舍首饰设计创意生活");                                           //红包发送者名称
            packageReqHandler.SetParameter("re_openid", opid);                                                    //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", hb);                                                   //付款金额,单位分
            packageReqHandler.SetParameter("total_num", "1");                                                     //红包发放总人数
            packageReqHandler.SetParameter("wishing", WebConfigurationManager.AppSettings["hbzf"]);               //红包祝福语
            packageReqHandler.SetParameter("client_ip", context.Request.UserHostAddress);                         //调用接口的机器Ip地址
            packageReqHandler.SetParameter("act_name", WebConfigurationManager.AppSettings["hbname"]);            //活动名称
            packageReqHandler.SetParameter("remark", WebConfigurationManager.AppSettings["hbDesc"]);              //备注信息
            string sign = packageReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key"]);
            packageReqHandler.SetParameter("sign", sign);                                                         //签名

            //最新的官方文档中将以下三个字段去除了
            //packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            //packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            //packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分


            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = WebConfigurationManager.AppSettings["zswz"];
            //私钥(在安装证书时设置)
            string password = WebConfigurationManager.AppSettings["WeixinPay_PartnerId"];
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            #endregion
            #region 发起post请求
            try
            {
                HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webrequest.ClientCertificates.Add(cer);
                webrequest.Method = "post";

                byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
                webrequest.ContentLength = postdatabyte.Length;
                Stream stream;
                stream = webrequest.GetRequestStream();
                stream.Write(postdatabyte, 0, postdatabyte.Length);
                stream.Close();

                HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
                StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
                string          responseContent = streamReader.ReadToEnd();
                //using (WXDBEntities db = new WXDBEntities())
                //{
                //    OperateLoginfo mt = new OperateLoginfo()
                //    {
                //        Title = name,
                //        Descs = "返回成功",
                //        AddTime = DateTime.Now,
                //        UpdateTime = DateTime.Now,
                //        Status = 0,
                //        Orders = 0,
                //        Extent1 = "",
                //        Extent2 = "",
                //        LogType = 1
                //    };
                //    db.OperateLoginfo.AddObject(mt);
                //    db.SaveChanges();
                //}
                WxZFData tdata = new WxZFData();
                tdata.FromXml(responseContent);
                string return_code = tdata.GetValue("return_code").ToString(); //状态码
                string return_msg  = tdata.GetValue("return_msg").ToString();  //状态码
                //using (WXDBEntities db = new WXDBEntities())
                //{
                //    OperateLoginfo mt = new OperateLoginfo()
                //    {
                //        Title = name,
                //        Descs = "返回值:" + return_code,
                //        AddTime = DateTime.Now,
                //        UpdateTime = DateTime.Now,
                //        Status = 0,
                //        Orders = 0,
                //        Extent1 = "",
                //        Extent2 = "",
                //        LogType = 1
                //    };
                //    db.OperateLoginfo.AddObject(mt);
                //    db.SaveChanges();
                //}
                var str = string.Empty;
                if ("SUCCESS".Equals(return_code))
                {
                    //string zfsign = tdata.GetValue("sign").ToString();
                    string result_code = tdata.GetValue("result_code").ToString();

                    //using (WXDBEntities db = new WXDBEntities())
                    //{
                    //    //+ "|" + err_code + "|" + err_code_des
                    //    OperateLoginfo mt = new OperateLoginfo()
                    //    {
                    //        Title = name,
                    //        Descs = "返回值:" + result_code,
                    //        AddTime = DateTime.Now,
                    //        UpdateTime = DateTime.Now,
                    //        Status = 0,
                    //        Orders = 0,
                    //        Extent1 = "",
                    //        Extent2 = "",
                    //        LogType = 1
                    //    };
                    //    db.OperateLoginfo.AddObject(mt);
                    //    db.SaveChanges();
                    //}
                    if ("SUCCESS".Equals(result_code))
                    {
                        //红包发送成功!
                        using (WXDBEntities db = new WXDBEntities())
                        {
                            var model = new Forms()
                            {
                                Title      = "万圣节红包",
                                FormType   = 0,
                                Name       = name,
                                Number     = 1,
                                Mobile     = phone,
                                Age        = 0,
                                Source     = opid,
                                Income     = "",
                                Remark     = "",
                                AddTime    = DateTime.Now,
                                Status     = 0,
                                Orders     = 0,
                                UpdateTime = DateTime.Now,
                                Extend     = context.Request.UserHostAddress,
                                Extend2    = "",
                                Type       = 8,
                                JFCount    = Convert.ToDouble(hb)
                            };
                            db.Forms.AddObject(model);
                            db.SaveChanges();
                        }
                        //加入数据库操作
                        str = "1|发送红包成功";
                    }
                    else
                    {
                        string err_code     = tdata.GetValue("err_code").ToString();
                        string err_code_des = tdata.GetValue("err_code_des").ToString();
                        using (WXDBEntities db = new WXDBEntities())
                        {
                            OperateLoginfo mt = new OperateLoginfo()
                            {
                                Title      = name,
                                Descs      = err_code,
                                AddTime    = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                Status     = 0,
                                Orders     = 0,
                                Extent1    = "",
                                Extent2    = err_code_des,
                                LogType    = 1
                            };
                            db.OperateLoginfo.AddObject(mt);
                            db.SaveChanges();
                        }
                        //红包发送失败
                        str = "2|发送红包失败!";
                    }
                }
                else
                {
                    using (WXDBEntities db = new WXDBEntities())
                    {
                        OperateLoginfo mt = new OperateLoginfo()
                        {
                            Title      = name,
                            Descs      = return_msg,
                            AddTime    = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Status     = 0,
                            Orders     = 0,
                            Extent1    = "",
                            Extent2    = "",
                            LogType    = 1
                        };
                        db.OperateLoginfo.AddObject(mt);
                        db.SaveChanges();
                    }
                    str = "3|发送红包失败";
                }
                return(str);
            }
            catch (Exception ex)
            {
                using (WXDBEntities db = new WXDBEntities())
                {
                    OperateLoginfo mt = new OperateLoginfo()
                    {
                        Title      = name,
                        Descs      = ex.Message,
                        AddTime    = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        Status     = 0,
                        Orders     = 0,
                        Extent1    = "",
                        Extent2    = "",
                        LogType    = 5
                    };
                    db.OperateLoginfo.AddObject(mt);
                    db.SaveChanges();
                }
                return("4|获取失败!");
            }
            #endregion
        }
        public object GetWeixinPayOption()
        {
            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(28);


            RequestHandler packageReqHandler = new RequestHandler(null);

            packageReqHandler.Init();

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


            var dict_package = new Dictionary <string, string> {
                { "appid", TenPayV3Info.AppId },
                { "mch_id", TenPayV3Info.MchId },
                { "nonce_str", nonceStr },
                { "body", "充值" },
                { "out_trade_no", sp_billno },
                { "total_fee", (0.01 * 100).ToString() },
                { "spbill_create_ip", System.Web.HttpContext.Current.Request.UserHostAddress },
                { "notify_url", TenPayV3Info.TenPayV3Notify },
                { "trade_type", "JSAPI" },
                { "openid", CurrentUser.openId }
            };

            dict_package.Keys.ToList().ForEach(key => packageReqHandler.SetParameter(key, dict_package[key]));

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

            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = string.Empty;

            try
            {
                prepayId = res.Element("xml").Element("prepay_id").Value;
            }
            catch (Exception ex)
            {
                return(new ReturnMessage {
                    success = false, message = ex.Message, data = new { xml = res.ToString() }
                });
            }

            var cbll = new CoinBLL();

            cbll.SaveJsapiPackageRequest(prepayId, CurrentUser.userId, dict_package);

            RequestHandler paySignReqHandler = new RequestHandler(null);

            paySignReqHandler.SetParameter("appId", TenPayV3Info.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            var ViewData = new Dictionary <string, object> {
            };

            ViewData["appId"]     = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"]  = nonceStr;
            ViewData["package"]   = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"]   = paySign;
            ViewData["signType"]  = "MD5";
            return(ViewData);
        }