示例#1
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["wxappid1"]);            //公众账号ID
            packageReqHandler.SetParameter("mch_id", WebConfigurationManager.AppSettings["WeixinPay_PartnerId1"]); //商户号
            packageReqHandler.SetParameter("mch_billno", mchbillno);                                               //填入商家订单号
            packageReqHandler.SetParameter("send_name", WebConfigurationManager.AppSettings["sendname3"]);         //红包发送者名称
            packageReqHandler.SetParameter("re_openid", opid);                                                     //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", hb);                                                    //付款金额,单位分
            packageReqHandler.SetParameter("total_num", "1");                                                      //红包发放总人数
            packageReqHandler.SetParameter("wishing", WebConfigurationManager.AppSettings["hbzf3"]);               //红包祝福语
            packageReqHandler.SetParameter("client_ip", context.Request.UserHostAddress);                          //调用接口的机器Ip地址
            packageReqHandler.SetParameter("act_name", WebConfigurationManager.AppSettings["hbname3"]);            //活动名称
            packageReqHandler.SetParameter("remark", WebConfigurationManager.AppSettings["hbDesc3"]);              //备注信息
            string sign = packageReqHandler.CreateMd5Sign("key", WebConfigurationManager.AppSettings["WeixinPay_Key1"]);
            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["zswz3"];
            //私钥(在安装证书时设置)
            string password = WebConfigurationManager.AppSettings["WeixinPay_PartnerId1"];
            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      = WebConfigurationManager.AppSettings["hbDesc3"],
                                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       = 10,
                                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
        }
示例#2
0
        public ReJson DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "")
        {
            //获取订单
            Order entity = Order.Find(Order._.OrderNum == ordernum);

            if (entity == null)
            {
                //reJson.code = 40000;
                //reJson.message = "系统找不到本订单!";
                //return reJson;

                return(new ReJson(40000, "系统找不到本订单!"));
            }
            //判断订单状态
            if (entity.OrderStatus == Utils.OrdersState[3])
            {
                //reJson.code = 40000;
                //reJson.message = "已完成订单不允许支付!";
                //return reJson;
                return(new ReJson(40000, "已完成订单不允许支付!"));
            }
            if (entity.PaymentStatus != Utils.PaymentState[0])
            {
                //reJson.code = 40000;
                //reJson.message = "当前订单支付状态不允许支付!";
                //return reJson;
                return(new ReJson(40000, "当前订单支付状态不允许支付!"));
            }
            //获取用户并判断是否是已经注册用户
            Member my = Member.FindById(entity.UId);

            if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId))
            {
                //reJson.code = 40000;
                //reJson.message = "用户状态错误,无法使用本功能!";
                //return reJson;
                return(new ReJson(40000, "用户状态错误,无法使用本功能!"));
            }
            //开始生成支付订单
            OnlinePayOrder model = new OnlinePayOrder();

            model.OrderId       = entity.Id;
            model.OrderNum      = entity.OrderNum;
            model.PayId         = 1;
            model.PaymentNotes  = "微信支付";
            model.PaymentStatus = Utils.PaymentState[0];
            model.PayOrderNum   = Utils.GetOrderNum();//在线支付订单的订单号
            model.PayType       = "微信支付";
            model.TotalPrice    = entity.TotalPay;
            model.TotalQty      = entity.TotalQty;
            model.UId           = entity.UId;
            model.IP            = Utils.GetIP();
            model.IsOK          = 0;
            model.AddTime       = DateTime.Now;
            model.Insert();

            //写入日志
            OrderLog log = new OrderLog();

            log.AddTime  = DateTime.Now;
            log.OrderId  = entity.Id;
            log.OrderNum = entity.OrderNum;
            log.UId      = entity.UId;
            log.Actions  = "用户使用微信支付;支付订单号:" + model.PayOrderNum;
            log.Insert();

            Core.Config cfg        = Core.Config.GetSystemConfig();
            string      appId      = cfg.WXAppId;     // ConfigurationManager.AppSettings["WeixinAppId"];
            string      appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"];
            string      wxmchId    = cfg.MCHId;       // ConfigurationManager.AppSettings["WeixinMCHId"];
            string      wxmchKey   = cfg.MCHKey;      // ConfigurationManager.AppSettings["WeixinMCHKey"];



            TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify", Utils.GetServerUrl() + "/wxpayment/notify");

            TenPayV3Info.TenPayV3Notify = Utils.GetServerUrl() + "/wxpayment/notify";
            XTrace.WriteLine("微信支付异步通知地址:" + TenPayV3Info.TenPayV3Notify);
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            var            sp_billno         = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);//最多32位
            var            nonceStr          = TenPayV3Util.GetNoncestr();
            string         rtimeStamp        = Utils.GetTimeStamp();

            //创建请求统一订单接口参数
            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, entity.Title, model.PayOrderNum, (int)(entity.TotalPay * 100), Utils.GetIP(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, my.WeixinAppOpenId, TenPayV3Info.Key, nonceStr);

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

            try
            {
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                XTrace.WriteLine("微信支付统一下单返回:" + JsonConvert.SerializeObject(result));

                if (result.return_code == "FAIL")
                {
                    //reJson.code = 40005;
                    //reJson.message = result.return_msg;
                    //return reJson;
                    return(new ReJson(40005, result.return_msg));
                }
                string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key);
                //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
                //paySign = MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111)
                string paySign = Utils.MD5($"appId={TenPayV3Info.AppId}&nonceStr={nonceStr}&package=prepay_id={result.prepay_id}&signType=MD5&timeStamp={rtimeStamp}&key={TenPayV3Info.Key}").ToUpper();

                string package = $"prepay_id={result.prepay_id}";

                dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign };

                //reJson.code = 0;
                //reJson.message = "下单成功!";
                //reJson.detail = detail;
                //return reJson;
                return(new ReJson(40000, "下单成功!", detail));
            }
            catch (Exception ex)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "统一下单失败");
                XTrace.WriteLine($"统一下单失败:{ex.Message}");

                //reJson.code = 40005;
                //reJson.message = "统一下单失败,请联系管理员!";
                return(new ReJson(40005, "统一下单失败,请联系管理员!"));
            }
        }
示例#3
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('|');
            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 != Senparc.Weixin.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", 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", Senparc.Weixin.MP.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());
        }
示例#4
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"));
                }
            }
        }
        public IActionResult Unifiedorder(UnidiedorderData udata)
        {
            using (_dbContext)
            {
                var response = ResponseModelFactory.CreateResultInstance;

                var stu = _dbContext.StudentBill.FirstOrDefault(x => x.StudentBillUuid == udata.BillGuid);


                if (stu == null)
                {
                    response.SetFailed("未查找到对应缴费信息");
                    return(Ok(response));
                }
                if (stu.OrderMoney >= stu.AmountPayable)
                {
                    response.SetFailed("已缴费");
                    return(Ok(response));
                }

                //时间戳
                string timeStamp = TenPayV3Util.GetTimestamp();
                //随机字符串
                string nonceStr = TenPayV3Util.GetNoncestr();
                string appid    = "wx0bf342f51437ca67";

                //获取学校绑定商户信息
                var school = _dbContext.School.FirstOrDefault(x => x.SchoolUuid == udata.Guid);
                if (school == null)
                {
                    response.SetFailed("未查找到对应学校");
                    return(Ok(response));
                }
                if (school.Yard == null || school.Secretkey == null)
                {
                    response.SetFailed("未查找到对应学校商户信息");
                    return(Ok(response));
                }


                //商户号
                string mch_id = school.Yard;                                                 //"1600884893";
                //商户支付秘钥
                string partnerKey = AES.AesDecrypt(school.Secretkey, HaiKan3.Utils.AES.Key); //"ew6QCdWiDfcif902EbC07dh0icTuM5le";
                //签名
                string sign      = "";
                string sign_type = "MD5";

                //商品描述
                string body = udata.Body;
                //商户订单号
                string out_trade_no = "";
                //标价金额(单位:分)
                int total_fee = udata.Totalfee;
                //终端IP
                //string spbill_create_ip = "183.158.56.51"; //Request.HttpContext.Connection.RemoteIpAddress.ToString();
                string spbill_create_ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                _logger.LogInformation("ip:" + spbill_create_ip);
                //通知地址
                string notify_url = "http://msz-b.jiulong.yoruan.com/test/PayCallBack";
                //string notify_url = "http://msz-b.jiulong.yoruan.com/api/v1/student/StudentBill/PayCallBack";
                //交易类型
                string trade_type = "JSAPI";
                //预支付id
                string prepayId = "";
                //微信调用支付的签名
                string paySign = "";
                //用户openid
                string     openid = udata.Openid;
                Store_Info info   = new Store_Info()
                {
                    address   = "xxxxxx",
                    area_code = "330185",
                    id        = "MSZzf" + appid,
                    name      = "码上知支付商城",
                };
                TenPayV3UnifiedorderRequestData_SceneInfo sceneInfo = new TenPayV3UnifiedorderRequestData_SceneInfo(false);
                sceneInfo.store_info = info;

                //生成订单号
                out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(14);
                _logger.LogInformation("订单号:" + out_trade_no);


                TenPayV3UnifiedorderRequestData requestData = new TenPayV3UnifiedorderRequestData(appid, mch_id, body, out_trade_no, total_fee, spbill_create_ip, notify_url, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openid, partnerKey, nonceStr, null, DateTime.Now, DateTime.Now.AddHours(2), null, null, "CNY", null, null, false, sceneInfo, null);

                var urlFormat = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}pay/unifiedorder");
                var data      = requestData.PackageRequestHandler.ParseXML();//获取XML
                _logger.LogInformation("xml:" + data);
                var str = PostXmlMethod.PostXmla(urlFormat, data);
                _logger.LogInformation("postxml:" + str);

                DataSet       ds     = new DataSet();
                StringReader  stream = new StringReader(str);     //读取字符串为数据量
                XmlTextReader reader = new XmlTextReader(stream); //对XML的数据流的只进只读访问
                ds.ReadXml(reader);                               //把数据读入DataSet

                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["return_code"].ToString() == "SUCCESS")
                    {
                        _logger.LogInformation("成功");
                        _logger.LogInformation("timeStamp:" + timeStamp + "; nonceStr:" + nonceStr + "; prepayId:" + ds.Tables[0].Rows[0]["prepay_id"].ToString() + "; paySign:" + ds.Tables[0].Rows[0]["sign"].ToString() + "; partnerKey:" + partnerKey);
                        response.SetData(new { appid = ds.Tables[0].Rows[0]["appid"].ToString(), timeStamp, nonceStr, prepayId = ds.Tables[0].Rows[0]["prepay_id"].ToString(), sign_type, paySign = ds.Tables[0].Rows[0]["sign"].ToString(), sjcode = Electroniccode.getString(32), key = partnerKey, outtradeno = out_trade_no });
                        BillState bill = new BillState()
                        {
                            BillUuid  = Guid.NewGuid(),
                            BillNum   = out_trade_no,
                            Appid     = appid,
                            MchId     = mch_id,
                            Money     = total_fee,
                            Key       = partnerKey,
                            SbillUuid = udata.BillGuid,
                        };
                        _logger.LogInformation("订单记录:" + JsonConvert.SerializeObject(bill));
                        _dbContext.BillState.Add(bill);
                        _dbContext.SaveChanges();
                        return(Ok(response));
                    }
                    else
                    {
                        response.SetFailed(ds.Tables[0].Rows[0]["return_msg"].ToString());
                        _logger.LogInformation("异常");
                        _logger.LogInformation(ds.Tables[0].Rows[0]["return_msg"].ToString());
                        return(Ok(response));
                    }
                }
                else
                {
                    response.SetFailed("订单信息为空");
                    return(Ok(response));
                }
            }
        }
示例#6
0
        /// <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", "wx57d365e74490cf2f");    //公众账号ID
            packageReqHandler.SetParameter("mch_id", "1309832401");             //商户号


            packageReqHandler.SetParameter("sub_appid", "wxfbd774ca1eabd17a");    //商户号
            packageReqHandler.SetParameter("sub_mch_id", "1312583301");           //商户号
            packageReqHandler.SetParameter("sub_openid", "oFo2HjiuEyhtCDbnFLxdhlQ5tRVA");

            packageReqHandler.SetParameter("mch_billno", mchbillno);                     //填入商家订单号
            packageReqHandler.SetParameter("send_name", "浩客");                           //红包发送者名称
            packageReqHandler.SetParameter("re_openid", "oFo2HjiuEyhtCDbnFLxdhlQ5tRVA"); //接受收红包的用户的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", "hk80BEC2BFD727L4W6845133519F3lD6");

            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 = @"E:\cert\apiclient_cert.p12";
            string cert = @"E:\HKfuwushang\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));
        }
示例#7
0
        public IHttpActionResult WechatNotify()
        {
            string reqKey = TenPayV3Util.BuildRandomStr(8);

            LogHelper.Payment(reqKey, $"收到微信支付异步通知,准备解析结果...");
            try
            {
                ResponseHandler resHandler  = new ResponseHandler(null);
                string          return_code = resHandler.GetParameter("return_code");
                string          return_msg  = resHandler.GetParameter("return_msg");
                LogHelper.Payment(reqKey, $"解析返回结果为return_code:{return_code},return_msg:{return_msg}");
                LogHelper.Info($"[{reqKey}]{resHandler.ParseXML()}");

                TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, notifyUrl, notifyUrl);
                resHandler.SetKey(TenPayV3Info.Key);
                //验证请求是否从微信发过来(安全)
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    //return_code是通信标识,非交易标识,交易是否成功需要查看result_code来判断
                    if (resHandler.GetParameter("result_code") == "SUCCESS")
                    {
                        string total_fee      = resHandler.GetParameter("total_fee");      //订单金额
                        string out_trade_no   = resHandler.GetParameter("out_trade_no");   //商户订单号
                        string transaction_id = resHandler.GetParameter("transaction_id"); //微信支付订单号
                        string time_end       = resHandler.GetParameter("time_end");       //支付完成时间
                        string openid         = resHandler.GetParameter("openid");
                        LogHelper.Payment(reqKey, $"微信支付成功,商户订单号:{out_trade_no},支付金额:{total_fee},支付流水号:{transaction_id},openid:{openid}");
                        //1.判断订单是否存在 2.判断订单支付状态 3.插入修改数据等
                        var orderEntity = _repositoryFactory.IOrders.Single(x => x.OrderCode == out_trade_no);
                        if (orderEntity == null)
                        {
                            LogHelper.Payment(reqKey, $"查找订单失败,商户订单号:{out_trade_no}");
                        }
                        else if (orderEntity.OrderStatus != (int)EnumHepler.OrderStatus.Created || orderEntity.PayStatus != (int)EnumHepler.OrderPayStatus.Unpay)
                        {
                            LogHelper.Payment(reqKey, $"订单非待支付状态,当前状态为{orderEntity.OrderStatus},商户订单号:{out_trade_no}");
                        }
                        else
                        {
                            LogHelper.Payment(reqKey, $"更新订单支付状态为已支付待发货,商户订单号:{out_trade_no}");
                            DateTime payTime = DateTime.ParseExact(time_end, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
                            //更新订单状态
                            _repositoryFactory.IOrders.ModifyBy(x => x.OrderCode == out_trade_no,
                                                                new string[] { "OrderStatus", "PayStatus", "PayTime", "PayMode" },
                                                                new object[] { (int)EnumHepler.OrderStatus.WaitSendGoods, (int)EnumHepler.OrderPayStatus.Paied, payTime, (int)EnumHepler.OrderPayMode.WechatPay });
                            _repositoryFactory.SaveChanges();
                        }
                    }
                    else
                    {
                        LogHelper.Payment(reqKey, $"微信支付失败,err_code:{resHandler.GetParameter("err_code")},err_code_des:{resHandler.GetParameter("err_code_des")}");
                    }
                }

                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return(Content(HttpStatusCode.OK, xml, Configuration.Formatters.XmlFormatter, "text/xml"));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
示例#8
0
        /// <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.Query["order_no"];
                if (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"),
                                              TenPayV3Util.BuildRandomStr(6));
                }
                else
                {
                    sp_billno = Request.Query["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, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId, TenPayV3Info.Key, nonceStr);

                SenparcTrace.SendCustomLog("H5Pay接口请求", xmlDataInfo.ToJson());

                var result = TenPayOldV3.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);

                SenparcTrace.SendCustomLog("H5Pay接口返回", result.ToJson());

                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"]   = TenPayOldV3.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(mwebUrl))
                {
                    mwebUrl += string.Format("&redirect_url={0}", returnUrl.AsUrlData());
                }

                ViewData["MWebUrl"] = mwebUrl;

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

                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 async Task <IActionResult> 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"));
                }
                ViewData["product"] = product;

                var openId = HttpContext.Session.GetString("OpenId");

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

                    //注意:以上订单号仅作为演示使用,如果访问量比较大,建议增加订单流水号的去重检查。
                }
                else
                {
                    sp_billno = Request.Query["order_no"];
                }

                //调用下单接口下单
                var name      = product == null ? "test" : product.Name;
                var price     = product == null ? 100 : (int)(product.Price * 100);//单位:分
                var notifyUrl = TenPayV3Info.TenPayV3Notify.Replace("/TenpayV3/", "/TenpayRealV3/").Replace("http://", "https://");

                //请求信息
                TransactionsRequestData jsApiRequestData = new(TenPayV3Info.AppId, TenPayV3Info.MchId, name + " - 微信支付 V3", sp_billno, new TenpayDateTime(DateTime.Now.AddHours(1), false), null, notifyUrl, null, new() { currency = "CNY", total = price }, new(openId), null, null, null);

                //请求接口
                var basePayApis2 = new TenPayV3.TenPayHttpClient.BasePayApis2(_httpClient, _tenpayV3Setting);
                var result       = await basePayApis2.JsApiAsync(jsApiRequestData);

                if (result.VerifySignSuccess != true)
                {
                    throw new WeixinException("获取 prepay_id 结果校验出错!");
                }

                //获取 UI 信息包
                var jsApiUiPackage = TenPaySignHelper.GetJsApiUiPackage(TenPayV3Info.AppId, result.prepay_id);
                ViewData["jsApiUiPackage"] = jsApiUiPackage;

                //临时记录订单信息,留给退款申请接口测试使用(分布式情况下请注意数据同步)
                HttpContext.Session.SetString("BillNo", sp_billno);
                HttpContext.Session.SetString("BillFee", price.ToString());

                return(View());
            }
            catch (Exception ex)
            {
                Senparc.Weixin.WeixinTrace.BaseExceptionLog(ex);
                throw;
            }
        }
示例#10
0
        /// <summary>
        /// 处理发关注红包的逻辑
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="wid"></param>
        /// <param name="actModel"></param>
        public int  proecssSendHB(string openid, int wid, Model.wx_xjhongbao_action actModel)
        {
            BLL.wx_xjhongbao_action actBll    = new BLL.wx_xjhongbao_action();
            BLL.wx_xjhongbao_base   baseBll   = new BLL.wx_xjhongbao_base();
            Model.wx_xjhongbao_base baseModel = baseBll.GetModelByWid(wid);

            BLL.wx_payment_wxpay   weixinPayBLL   = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay weixinPayModel = weixinPayBLL.GetModelByWid(wid);

            if (baseModel == null || weixinPayModel == null || actModel == null)
            {
                return(0);
            }

            #region 取用户昵称--注释掉了
            //string error = "";
            //string accessToken=WeiXinCRMComm.getAccessToken(wid, out error);
            //if (error.Trim().Length > 0)
            //{
            //    WXLogs.AddErrLog(wid, "微信红包", actModel.act_name, "accessToken取值有错误error:"+error);
            //    return;
            //}
            //string nick = UserApi.Info(accessToken, openid).nickname;
            #endregion

            //用户此次获得的红包(单位分)
            int hongbaoFen = 0;
            if (actModel.totalLqMoney >= actModel.totalMoney)
            {
                //1 红包金额已经领取完了,记录到日志
                InsertToLQinfo(wid, actModel.id, openid, 0, DateTime.Parse("1970-1-1"), "", "", "", "", "红包余额不足,需要调整活动的金额");
                return(0);
            }
            //2 判断该用户是否已经领取了
            bool hasLQ = lqBll.ExistsOpenid(actModel.id, openid, actModel.lqType == 0 ? true : false);
            if (hasLQ)
            { //已经领取了
                return(0);
            }
            int leftMoney = actModel.totalMoney.Value - actModel.totalLqMoney.Value;//剩余金额
            //3 计算本次的红包
            if (actModel.moneyType == 0)
            { //定额
                hongbaoFen = actModel.min_value.Value;
            }
            else
            {  //随机
                Random rd = new Random();
                hongbaoFen = rd.Next(actModel.min_value.Value, actModel.max_value.Value);
            }

            if (hongbaoFen >= leftMoney)
            {
                hongbaoFen = leftMoney;
            }

            //4 给用户发红包
            string mchbillno = weixinPayModel.mch_id + DateTime.Now.ToString("yyyymmddHHmmss") + TenPayV3Util.BuildRandomStr(4);


            Model.wx_xjhongbao_lqinfo lqinfoEntity = new Model.wx_xjhongbao_lqinfo();
            lqinfoEntity.wid          = wid;
            lqinfoEntity.actionId     = actModel.id;
            lqinfoEntity.openid       = openid;
            lqinfoEntity.total_amount = hongbaoFen;
            lqinfoEntity.createDate   = DateTime.Now;

            XmlDocument doc = new XmlDocument();
            if (!SendHBBase(weixinPayModel, actModel, wid, openid, hongbaoFen, mchbillno, doc))
            {
                //发红包的方法出现问题
                WXLogs.AddErrLog(wid, "微信红包", actModel.act_name, "发现金红包底层方法报错。");

                lqinfoEntity.Send_time  = DateTime.Now;
                lqinfoEntity.mch_billno = mchbillno;
                lqinfoEntity.mch_id     = weixinPayModel.mch_id;
                lqinfoEntity.hbstatus   = "FAILED";
                lqinfoEntity.send_type  = "API";
                lqinfoEntity.hb_type    = "NORMAL";
                lqinfoEntity.reason     = "result_code:" + doc.InnerXml.ToString();

                lqBll.Add(lqinfoEntity);  //记录领取日志
                WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包领取失败:" + doc.InnerXml.ToString());
                return(0);
            }
            //5修改现金:1活动的领取金额增加;2用户的中奖记录增加
            actModel = actBll.GetModel(actModel.id);
            actModel.totalLqMoney += hongbaoFen;
            actBll.Update(actModel);
            //6修改配置文件的领取金额;
            baseModel.totalLQMoney += hongbaoFen;
            baseBll.Update(baseModel);

            WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包领取成功2:" + doc.InnerXml.ToString());

            lqinfoEntity.Send_time  = MyCommFun.Obj2DateTime(MyCommFun.GetXmlNode("send_time", doc), DateTime.Now);
            lqinfoEntity.mch_billno = mchbillno;
            lqinfoEntity.mch_id     = weixinPayModel.mch_id;
            lqinfoEntity.detail_id  = MyCommFun.GetXmlNode("send_listid", doc);
            lqinfoEntity.hbstatus   = "SUCCESS";
            lqinfoEntity.send_type  = "API";
            lqinfoEntity.hb_type    = "NORMAL";
            lqinfoEntity.reason     = "";
            lqinfoEntity.remark     = doc.InnerXml.ToString();
            lqBll.Add(lqinfoEntity);

            WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包成功领取3:" + doc.InnerXml.ToString());
            return(hongbaoFen);
        }
        /// <summary>
        /// 发送现金红包
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="total_amount"></param>
        /// <param name="TenPayV3_Sender"></param>
        /// <param name="TenPayV3_Wish"></param>
        /// <param name="TenPayV3_Game"></param>
        /// <param name="TenPayV3_Remark"></param>
        /// <returns></returns>
        public string SendCash2(string openid, string total_amount, string TenPayV3_Sender, string TenPayV3_Wish, string TenPayV3_Game, string TenPayV3_Remark)
        {
            try
            {
                var mchbillno         = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
                var nonceStr          = TenPayV3Util.GetNoncestr();
                var packageReqHandler = new RequestHandler(null);

                //设置package订单参数
                string TenPayV3_AppId = ConfigurationManager.AppSettings["TenPayV3_AppId"];
                string TenPayV3_MchId = ConfigurationManager.AppSettings["TenPayV3_MchId"];
                string TenPayV3_Key   = ConfigurationManager.AppSettings["TenPayV3_Key"];
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                               //随机字符串
                //packageReqHandler.SetParameter("wxappid", "wx6953deeefe22a83b"); //公众账号ID
                packageReqHandler.SetParameter("wxappid", TenPayV3_AppId);                                           //公众账号ID
                packageReqHandler.SetParameter("mch_id", TenPayV3_MchId);                                            //商户号
                packageReqHandler.SetParameter("mch_billno", mchbillno);                                             //填入商家订单号
                packageReqHandler.SetParameter("send_name", TenPayV3_Sender);                                        //红包发送者名称
                packageReqHandler.SetParameter("re_openid", openid);                                                 //接受收红包的用户的openId
                packageReqHandler.SetParameter("total_amount", total_amount);                                        //付款金额,单位分
                packageReqHandler.SetParameter("total_num", "1");                                                    //红包发放总人数
                packageReqHandler.SetParameter("wishing", TenPayV3_Wish);                                            //红包祝福语
                packageReqHandler.SetParameter("client_ip", System.Web.HttpContext.Current.Request.UserHostAddress); //调用接口的机器Ip地址
                packageReqHandler.SetParameter("act_name", TenPayV3_Game);                                           //活动名称
                packageReqHandler.SetParameter("remark", TenPayV3_Remark);                                           //备注信息
                var sign = packageReqHandler.CreateMd5Sign("key", TenPayV3_Key);
                packageReqHandler.SetParameter("sign", sign);                                                        //签名

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


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

                //发红包接口地址
                var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

                //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
                var cert = ConfigurationManager.AppSettings["TenPayV3_Cert"];

                //私钥(在安装证书时设置)
                var password = ConfigurationManager.AppSettings["TenPayV3_CertPass"];

                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;

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

                #region 发起post请求

                var webrequest = (HttpWebRequest)WebRequest.Create(url);
                webrequest.ClientCertificates.Add(cer);
                webrequest.Method = "post";

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

                var httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
                var streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
                var responseContent = streamReader.ReadToEnd();
                return(responseContent);

                #endregion
            }
            catch (Exception ex)
            {
                Common.Helper.Logger.Info(string.Format("发送现金红包SendCash2异常,异常信息{0}", ex.ToString()));
                throw;
            }
        }
示例#12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int orderId = MyCommFun.RequestInt("orderid");
            int wid     = MyCommFun.RequestInt("wid");

            getwid     = wid;
            getorderId = orderId;
            string code  = MyCommFun.RequestParam("code");
            string state = MyCommFun.RequestParam("state");

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);
            BLL.wx_userweixin      wx          = new BLL.wx_userweixin();
            Model.wx_userweixin    wxModel     = wx.GetModel(wid);
            BLL.orders             otBll       = new BLL.orders();

            Model.orders orderEntity = otBll.GetModel(orderId, wid);

            litout_trade_no = orderEntity.order_no;
            litMoney        = Decimal.ToInt32(orderEntity.order_amount);
            litDate         = orderEntity.add_time.ToString();



            if (string.IsNullOrEmpty(code))
            {
                Response.Write("您拒绝了授权!");
                return;
            }

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

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

            //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(PayV3Config.Mch_appId, PayV3Config.Mch_Secret, code);

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

            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();
            }

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

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

            //设置package订单参数
            //  packageReqHandler.SetParameter("appid", paymentInfo.appId);		  //公众账号ID
            ///    packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);		  //商户号

            packageReqHandler.SetParameter("appid", PayV3Config.Mch_appId);               //公众账号ID
            packageReqHandler.SetParameter("mch_id", PayV3Config.Mch_mchid);              //商户号
            ////
            packageReqHandler.SetParameter("sub_appid", paymentInfo.appId);               //子商户公众账号ID
            packageReqHandler.SetParameter("sub_mch_id", paymentInfo.partnerId);          //子商户号mch_id
            ///


            packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
            packageReqHandler.SetParameter("body", orderId.ToString());                                                                     //商品信息
            packageReqHandler.SetParameter("out_trade_no", litout_trade_no);                                                                //商家订单号
            packageReqHandler.SetParameter("total_fee", (litMoney * 100).ToString());                                                       //product == null ? "100" : (product.Price * 100).ToString()商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + wid + "|" + orderId); //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);                                                                  //用户的openId

            //   string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.paySignKey);
            string sign = packageReqHandler.CreateMd5Sign("key", PayV3Config.Mch_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;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", PayV3Config.Mch_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", PayV3Config.Mch_Key);



            payaddid        = PayV3Config.Mch_appId;
            paytimeStamp    = timeStamp;
            paynonceStr     = nonceStr;
            paypackageValue = string.Format("prepay_id={0}", prepayId);
            paypaySign      = paySign;
        }
        /// <summary>
        /// H5支付
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="hc"></param>
        /// <returns></returns>
        public ActionResult H5Pay(int orderId = 0)
        {
            {
                try
                {
                    string openId = null;//此时在外部浏览器,无法或得到OpenId

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

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

                    var body  = "SenparcProduct"; //产品名称
                    var price = 100;              //单位:分

                    //var ip = Request.Params["REMOTE_ADDR"];
                    var xmlDataInfo = new TenPayV3UnifiedorderRequestData(Service.Config.AppId, Service.Config.MchId,
                                                                          body, sp_billno, price, Request.UserHostAddress, Service.Config.TenPayV3Notify,
                                                                          TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId,
                                                                          Service.Config.TenPayV3_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"]     = Service.Config.AppId;
                    ViewData["timeStamp"] = timeStamp;
                    ViewData["nonceStr"]  = nonceStr;
                    ViewData["package"]   = package;
                    ViewData["paySign"]   = TenPayV3.GetJsPaySign(Service.Config.AppId, timeStamp, nonceStr, package, Service.Config.TenPayV3_Key);

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

                    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));
                }
            }
        }
示例#14
0
        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, 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()));
        }
示例#15
0
 public static string GenerateOutTradeNo()
 {
     return(string.Format("{0}{1}{2}", WeChatInfo.MchID, DateTime.Now.ToString("yyyyMMddHHmmssff"), TenPayV3Util.BuildRandomStr(6)).PadRight(32, '0').Substring(0, 32));
 }
        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))
            {
                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,
                            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));
        }
        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 /*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, 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);

                //临时记录订单信息,留给退款申请接口测试使用
                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));
            }
        }
示例#18
0
        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 = HttpContext.Session.GetString("OpenId");

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

                    //注意:以上订单号仅作为演示使用,如果访问量比较大,建议增加订单流水号的去重检查。
                }
                else
                {
                    sp_billno = Request.Query["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, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr);

                var result = TenPayOldV3.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"]   = TenPayOldV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

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

                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));
            }
        }
示例#19
0
        /// <summary>
        /// 最新接口调用
        /// 2014-11-24
        /// </summary>
        /// <param name="ttFee">支付金额(单位元)</param>
        /// <param name="busiBody">订单内容</param>
        /// <param name="out_trade_no">订单号</param>
        /// <param name="code"></param>
        protected void WxPayDataV3(decimal ttFee, string busiBody, string out_trade_no, string code)
        {
            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            BLL.wx_userweixin   uwBll    = new BLL.wx_userweixin();
            Model.wx_userweixin uwEntity = uwBll.GetModel(wid);

            // logBll.AddLog(wid,"【微支付】微信预定", "paypage.aspx WxPayDataV3", "211 wid:" + wid, 1);

            //先设置基本信息
            string MchId = paymentInfo.mch_id;      // "1218574001";//

            string partnerKey = paymentInfo.paykey; // 商户支付密钥Key。登录微信商户后台,进入栏目【账户设置】【密码安全】【API 安全】【API 密钥】

            string notify_url = "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx";

            WXLogs.AddLog(wid, "【微支付】微信预定", "paypage.aspx WxPayDataV3", "uwEntity.AppId: " + uwEntity.AppId + "| uwEntity.AppSecret;" + uwEntity.AppSecret + "|code:" + code, 1);


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

            string sp_billno = out_trade_no;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

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


            //创建支付应答对象
            OneGulp.WeChat.MP.TenPayLibV3.RequestHandler packageReqHandler = new OneGulp.WeChat.MP.TenPayLibV3.RequestHandler(null);
            //初始化
            packageReqHandler.Init();
            //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/);

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", uwEntity.AppId);                      //公众账号ID
            packageReqHandler.SetParameter("mch_id", MchId);                              //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                        //随机字符串
            packageReqHandler.SetParameter("body", busiBody);                             //商品描述
            packageReqHandler.SetParameter("attach", wid + "|" + busiBody);
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                    //商家订单号
            packageReqHandler.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);  //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", notify_url);                     //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());  //交易类型
            packageReqHandler.SetParameter("openid", openid);                             //用户的openId

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

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

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3Helper.Unifiedorder(data);

            var res = XDocument.Parse(result);

            prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            OneGulp.WeChat.MP.TenPayLibV3.RequestHandler paySignReqHandler = new OneGulp.WeChat.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", uwEntity.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", partnerKey);

            packageValue  = "";
            packageValue += " \"appId\": \"" + uwEntity.AppId + "\", ";
            packageValue += " \"timeStamp\": \"" + timeStamp + "\", ";
            packageValue += " \"nonceStr\": \"" + nonceStr + "\", ";
            packageValue += " \"package\": \"" + string.Format("prepay_id={0}", prepayId) + "\", ";
            packageValue += " \"signType\": \"MD5\", ";
            packageValue += " \"paySign\": \"" + paySign + "\"";
        }