Exemple #1
0
        protected WxpayInfo wxjsApiPay()
        {
            string            wxkey     = "s_wx_key_ticket";
            string            timeStamp = TenPayV3Util.GetTimestamp();
            string            nonceStr  = TenPayV3Util.GetNoncestr();
            JsApiTicketResult wxTicket  = CacheManager.Instance.Get <JsApiTicketResult>(wxkey);

            if (wxTicket == null)
            {
                wxTicket = CommonApi.GetTicket(Appid, Appkey);
                CacheManager.Instance.Set(wxkey, wxTicket, 0, wxTicket.expires_in - 120);
            }
            string url = Request.Url.AbsoluteUri;

            Senparc.Weixin.MP.TenPayLib.RequestHandler nativeHandler = new Senparc.Weixin.MP.TenPayLib.RequestHandler(null);
            nativeHandler.SetParameter("jsapi_ticket", wxTicket.ticket);
            nativeHandler.SetParameter("noncestr", nonceStr);
            nativeHandler.SetParameter("timestamp", timeStamp);
            nativeHandler.SetParameter("url", url);
            string sign = nativeHandler.CreateSHA1Sign();

            return(new WxpayInfo()
            {
                AppId = Appid,
                Noncestr = nonceStr,
                Timestamp = timeStamp,
                Signature = sign
            });
        }
        public Unified WxPay(string body, int price, string openId)
        {
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr  = TenPayV3Util.GetNoncestr();

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

            return(new Unified {
                timeStamp = timeStamp,
                nonceStr = nonceStr,
                package = package,
                paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key)
            });
        }
Exemple #3
0
        /// <summary>
        /// 获取预支付交易ID签名
        /// </summary>
        /// <param name="appId">微信APPID</param>
        /// <param name="key">微信支付——商家支付密匙</param>
        /// <param name="prepayId">预支付ID</param>
        /// <returns></returns>
        public WxPaySign GetPaySign(string appId, string key, string prepayId)
        {
            RequestHandler paysignReqHandler = new RequestHandler(null);

            //设置支付参数
            string timestamp = TenPayV3Util.GetTimestamp();
            string nonceStr  = TenPayV3Util.GetNoncestr();

            var wxPaySign = new WxPaySign()
            {
                NonceStr  = nonceStr,
                TimeStamp = timestamp,
                Package   = string.Format("prepay_id={0}", prepayId),
                SignType  = "MD5",
                AppId     = appId
            };

            paysignReqHandler.SetParameter("appId", appId);
            paysignReqHandler.SetParameter("timeStamp", wxPaySign.TimeStamp);
            paysignReqHandler.SetParameter("nonceStr", wxPaySign.NonceStr);
            paysignReqHandler.SetParameter("package", wxPaySign.Package);
            paysignReqHandler.SetParameter("signType", wxPaySign.SignType);

            string paySign = paysignReqHandler.CreateMd5Sign("key", key);

            wxPaySign.PaySign = paySign;

            return(wxPaySign);
        }
Exemple #4
0
        public ActionResult productJsApi(int?id, string host)
        {
            TelphoneLiangH5Entity entity = tlbll.GetEntity(id);
            var sp_billno = string.Format("{0}{1}", "LX-", DateTime.Now.ToString("yyyyMMddHHmmss"));
            var openId    = (string)Session["OpenId"];
            var nonceStr  = TenPayV3Util.GetNoncestr();
            var timeStamp = TenPayV3Util.GetTimestamp();

            //商品Id,用户自行定义
            var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "JSAPI购买靓号", sp_billno,
                                                                    Convert.ToInt32(Convert.ToDecimal(entity.Price) * 100),
                                                                    Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, tenPayV3Info.Key, nonceStr);
            var result = TenPayV3.Unifiedorder(xmlDataInfoH5); //调用统一订单接口

            LogHelper.AddLog(result.ResultXml);                //记录日志
            var package = string.Format("prepay_id={0}", result.prepay_id);

            if (result.return_code == "SUCCESS")
            {
                WFTWxModel jsApiPayData = new WFTWxModel()
                {
                    appId        = WeixinConfig.AppID2,
                    timeStamp    = timeStamp,
                    nonceStr     = nonceStr,
                    package      = package,
                    paySign      = TenPayV3.GetJsPaySign(WeixinConfig.AppID2, timeStamp, nonceStr, package, WeixinConfig.Key),
                    callback_url = "https://shop.jnlxsm.net/webapp/jinan2/paymentFinish/" + id
                };
                ViewBag.WxModel = jsApiPayData;
                LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志
            }
            ViewBag.OrderSn = sp_billno;
            ViewBag.Host    = host;
            return(View(entity));
        }
Exemple #5
0
//         #region 订单及退款

//         /// <summary>
//         /// 订单查询
//         /// </summary>
//         /// <returns></returns>
//         public ActionResult OrderQuery()
//         {
//             string nonceStr = TenPayV3Util.GetNoncestr();
//             RequestHandler packageReqHandler = new RequestHandler(null);

//             //设置package订单参数
//             packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
//             packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
//             packageReqHandler.SetParameter("transaction_id", "");       //填入微信订单号
//             packageReqHandler.SetParameter("out_trade_no", "");         //填入商家订单号
//             packageReqHandler.SetParameter("nonce_str", nonceStr);             //随机字符串
//             string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
//             packageReqHandler.SetParameter("sign", sign);	                    //签名

//             string data = packageReqHandler.ParseXML();

//             var result = TenPayV3.OrderQuery(data);
//             var res = XDocument.Parse(result);
//             string openid = res.Element("xml").Element("sign").Value;

//             return Content(openid);
//         }

//         /// <summary>
//         /// 关闭订单接口
//         /// </summary>
//         /// <returns></returns>
//         public ActionResult CloseOrder()
//         {
//             string nonceStr = TenPayV3Util.GetNoncestr();
//             RequestHandler packageReqHandler = new RequestHandler(null);

//             //设置package订单参数
//             packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
//             packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
//             packageReqHandler.SetParameter("out_trade_no", "");                 //填入商家订单号
//             packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
//             string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
//             packageReqHandler.SetParameter("sign", sign);	                    //签名

//             string data = packageReqHandler.ParseXML();

//             var result = TenPayV3.CloseOrder(data);
//             var res = XDocument.Parse(result);
//             string openid = res.Element("xml").Element("openid").Value;

//             return Content(openid);
//         }

//         /// <summary>
//         /// 退款申请接口
//         /// </summary>
//         /// <returns></returns>
//         public ActionResult Refund()
//         {
//             try
//             {
//                 WeixinTrace.SendCustomLog("进入退款流程", "1");

//                 string nonceStr = TenPayV3Util.GetNoncestr();

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

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


//                 string outRefundNo = "OutRefunNo-" + SystemTime.Now.Ticks;
//                 int totalFee = int.Parse(HttpContext.Session.GetString("BillFee"));
//                 int refundFee = totalFee;
//                 string opUserId = TenPayV3Info.MchId;
//                 var notifyUrl = $"{_siteUrl}/TenPayV3/RefundNotifyUrl";
//                 var dataInfo = new TenPayV3RefundRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, TenPayV3Info.Key,
//                     null, nonceStr, null, outTradeNo, outRefundNo, totalFee, refundFee, opUserId, null, notifyUrl: notifyUrl);

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

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

//                 WeixinTrace.SendCustomLog("进入退款流程", "3 Result:" + result.ToJson());


//                 return Content(string.Format("退款结果:{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des));
//                 //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 = "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

//         }

//         /// <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");

//                     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");
//         }

//         #endregion

        public IActionResult Card()
        {
            try
            {
                JsSdkUiPackage jssdkUiPackage = JSSDKHelper.GetJsSdkUiPackage(TenPayV3Info.AppId, TenPayV3Info.AppSecret, Request.AbsoluteUri());

                var api_ticket = WxCardApiTicketContainer.TryGetWxCardApiTicket(TenPayV3Info.AppId, TenPayV3Info.AppSecret);
                // var openId = HttpContext.Session.GetString("OpenId");
                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr  = TenPayV3Util.GetNoncestr();
                var sign      = JSSDKHelper.GetcardExtSign(api_ticket, timeStamp, "pukHe541WmaHEBgW3gACiBCD4EbY", nonceStr);
                var cardExt   = new { timestamp = timeStamp, signature = sign, nonce_str = nonceStr };
                ViewData["cardExt"] = JsonConvert.SerializeObject(cardExt);
                return(View(jssdkUiPackage));
            }
            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));
            }
        }
Exemple #6
0
        /// <summary>
        /// 微信支付下单
        /// APP下单部分
        /// </summary>
        /// <param name="reqmodel"></param>
        /// <returns></returns>
        public UnifiedOrderModelForApp WxPayUnifiedOrderByApp(RequestUnifiedOrder reqmodel)
        {
            try
            {
                var wxPayAcc  = JsonHelper.Deserialize <WxPayAccVM>(AccStr);
                var nonceStr  = TenPayV3Util.GetNoncestr();
                var timeStamp = TenPayV3Util.GetTimestamp();
                //此处填入此支付附加信息
                var attach      = string.Empty;
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(wxPayAcc.AppId, wxPayAcc.MchId, reqmodel.Body,
                                                                      reqmodel.OutTradeNo, reqmodel.TotalFee,
                                                                      reqmodel.SpbillCreateIp, wxPayAcc.NotifyUrl, Senparc.Weixin.TenPay.TenPayV3Type.APP,
                                                                      null, wxPayAcc.MchIdKey, nonceStr, null, null, null, null, attach);

                var response = TenPayV3.Unifiedorder(xmlDataInfo);                //调用统一订单接口
                if (response.result_code != Success || response.return_code != Success)
                {
                    throw new Exception("微信App统一下单失败,请检查参数是否配置正确");
                }
                //重新获取混淆信息以及时间戳
                nonceStr  = TenPayV3Util.GetNoncestr();
                timeStamp = TenPayV3Util.GetTimestamp();
                var signData = new UnifiedOrderModelForApp
                {
                    AppId     = wxPayAcc.AppId,
                    PartnerId = wxPayAcc.MchId,
                    PrepayId  = response.prepay_id,
                    Package   = "Sign=WXPay",
                    NonceStr  = nonceStr,
                    TimeStamp = timeStamp
                };
                //构建签名词典
                var sParams = new SortedDictionary <string, string> {
                    { "appid", wxPayAcc.AppId },
                    { "partnerid", wxPayAcc.MchId },
                    { "prepayid", response.prepay_id },
                    { "package", "Sign=WXPay" },
                    { "noncestr", nonceStr },
                    { "timestamp", timeStamp }
                };
                var li = new List <string>();
                //拼接部分
                foreach (KeyValuePair <string, string> temp in sParams)
                {
                    li.Add(temp.Key + "=" + temp.Value);
                }
                //在最后追加支付密钥
                li.Add("key=" + wxPayAcc.MchIdKey.Trim());
                //MD5处理部分
                MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
                var inputBye  = Encoding.UTF8.GetBytes(string.Join("&", li));
                var outputBye = m5.ComputeHash(inputBye);
                signData.Sign = BitConverter.ToString(outputBye).Replace("-", "").ToUpper();
                return(signData);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #7
0
        /// <summary>
        /// 原生支付 模式一
        /// </summary>
        /// <returns></returns>
        public ActionResult Native()
        {
            RequestHandler nativeHandler = new RequestHandler(null);
            string         timeStamp     = TenPayV3Util.GetTimestamp();
            string         nonceStr      = TenPayV3Util.GetNoncestr();

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

            nativeHandler.SetParameter("appid", TenPayV3Info.AppId);
            nativeHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            nativeHandler.SetParameter("time_stamp", timeStamp);
            nativeHandler.SetParameter("nonce_str", nonceStr);
            nativeHandler.SetParameter("product_id", productId);
            string sign = nativeHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            var url = TenPayV3.NativePay(TenPayV3Info.AppId, timeStamp, TenPayV3Info.MchId, nonceStr, productId, sign);

            BitMatrix bitMatrix;

            bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 600, 600);
            BarcodeWriter bw = new BarcodeWriter();

            var ms     = new MemoryStream();
            var bitmap = bw.Write(bitMatrix);

            bitmap.Save(ms, ImageFormat.Png);
            //return File(ms, "image/png");
            ms.WriteTo(Response.OutputStream);
            Response.ContentType = "image/png";
            return(null);
        }
Exemple #8
0
        public ActionResult Order(string name)
        {
            var body      = name ?? "SenparcProduct";
            var price     = 100;//单位:分
            var sp_billno = string.Format("{0}{1}{2}", "1234567890", DateTime.Now.ToString("yyyyMMddHHmmss"),
                                          TenPayV3Util.BuildRandomStr(6));
            var openId    = User.Identity.Name;
            var nonceStr  = TenPayV3Util.GetNoncestr();
            var timeStamp = TenPayV3Util.GetTimestamp();


            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(
                Service.Config.AppId, Service.Config.MchId, body, sp_billno, price, Request.UserHostAddress,
                Service.Config.TenPayV3Notify, TenPayV3Type.JSAPI, openId, Service.Config.TenPayV3_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);

            var paySign = TenPayV3.GetJsPaySign(Service.Config.AppId, timeStamp, nonceStr, package, Service.Config.TenPayV3_Key);

            var vd = new TenPayV3_Odrer()
            {
                Product = name,
                Package = package,
                PaySign = paySign
            };

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

            return(View(vd));
        }
Exemple #9
0
 /// <summary>
 /// 微信支付下单
 /// JsAPI下单部分
 /// </summary>
 /// <param name="reqmodel"></param>
 /// <returns></returns>
 public UnifiedOrderModelForJSAPI WxPayUnifiedOrderForJSAPI(RequestUnifiedOrder reqmodel)
 {
     try
     {
         var wxPayAcc  = JsonHelper.Deserialize <WxPayAccVM>(AccStr);
         var nonceStr  = TenPayV3Util.GetNoncestr();
         var timeStamp = TenPayV3Util.GetTimestamp();
         //此处填入此支付附加信息
         var attach      = string.Empty;
         var xmlDataInfo = new TenPayV3UnifiedorderRequestData(wxPayAcc.AppId, wxPayAcc.MchId, reqmodel.Body,
                                                               reqmodel.OutTradeNo, reqmodel.TotalFee, reqmodel.SpbillCreateIp, wxPayAcc.NotifyUrl, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI,
                                                               reqmodel.OpenId, wxPayAcc.MchIdKey, nonceStr, null, null, null, null, attach);
         var result  = TenPayV3.Html5Order(xmlDataInfo);               //调用统一订单接口
         var package = string.Format("prepay_id={0}", result.prepay_id);
         var paySign = TenPayV3.GetJsPaySign(wxPayAcc.AppId, timeStamp, nonceStr, package, wxPayAcc.MchIdKey);
         var model   = new UnifiedOrderModelForJSAPI
         {
             AppId     = result.appid,
             NonceStr  = nonceStr,
             TimeStamp = timeStamp,
             Package   = package,
             SignType  = "MD5",
             PaySign   = paySign
         };
         return(model);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #10
0
        public async Task <JsonResult> GetPaySign(PayInput input)
        {
            using (CurrentUnitOfWork.DisableFilter(DataFilters.MustHaveTenant, DataFilters.MayHaveTenant))
            {
                Order        order        = _orderRepository.Get(input.Id);
                TenPayV3Info tenPayV3Info = await GetTenPayV3Info(InfrastructureSession.TenantId.Value);

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

                if (order.PrepayIdCreatedTime.HasValue && order.PrepayIdCreatedTime < DateTime.Now.AddHours(-2))
                {
                    throw new UserFriendlyException(L("TheOrderHasOverTime"));
                }

                if (string.IsNullOrEmpty(order.PrepayId))
                {
                    string body             = order.Title;                 //商品或支付单简要描述
                    string out_trade_no     = order.Number;                //商户系统内部的订单号,32个字符内,可包含字母,其他说明见商户订单号
                    int    totalFee         = (int)(order.PayMoney * 100); //订单总金额,只能是整数。
                    string spbill_create_ip = Request.UserHostAddress;     //APP和网页支付提交用户端IP,Native支付填调用微信支付API的机器IP

                    string openid = WechatUserManager.GetOpenid(order.User.ToUserIdentifier());
                    TenPayV3UnifiedorderRequestData xmlDataInfo = new TenPayV3UnifiedorderRequestData(
                        tenPayV3Info.AppId,
                        tenPayV3Info.MchId,
                        body,
                        out_trade_no,
                        totalFee,
                        Request.UserHostAddress,
                        tenPayV3Info.TenPayV3Notify,
                        //trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。必传,这里需要将去获取openid赋值上去
                        TenPayV3Type.JSAPI,
                        openid,
                        tenPayV3Info.Key,
                        nonceStr);

                    UnifiedorderResult unifiedorderResult = TenPayV3.Unifiedorder(xmlDataInfo, 10000);
                    string             prepay_id          = unifiedorderResult.prepay_id;
                    order.PrepayId            = prepay_id;
                    order.PrepayIdCreatedTime = DateTime.Now;
                    _orderRepository.Update(order);
                }
                nonceStr = TenPayV3Util.GetNoncestr();

                RequestHandler paysignReqHandler = new RequestHandler(null);
                paysignReqHandler.Init();

                //设置支付参数
                paysignReqHandler.SetParameter("appId", tenPayV3Info.AppId);
                paysignReqHandler.SetParameter("timeStamp", timeStamp);
                paysignReqHandler.SetParameter("nonceStr", nonceStr);
                string package = string.Format("prepay_id={0}", order.PrepayId);
                paysignReqHandler.SetParameter("package", package);

                string paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key);
                paysignReqHandler.SetParameter("paySign", paySign);
                return(Json(paysignReqHandler.GetAllParameters()));
            }
        }
Exemple #11
0
        /// <summary>
        /// 取得微信JsSdk相关参数值
        /// </summary>
        /// <param name="appId">微信应用ID</param>
        /// <param name="ticket">JsTicket</param>
        /// <param name="url">需要授权Url地址</param>
        /// <returns></returns>
        public JsSdkResp GetJsSdk(string appId, string ticket, string url)
        {
            var    decodeUrl = HttpUtility.UrlDecode(url);
            string timeStamp = TenPayV3Util.GetTimestamp();
            string nonceStr  = TenPayV3Util.GetNoncestr();

            string signature = "";

            Senparc.Weixin.MP.TenPayLib.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLib.RequestHandler(null);

            paySignReqHandler.SetParameter("jsapi_ticket", ticket);
            paySignReqHandler.SetParameter("noncestr", nonceStr);
            paySignReqHandler.SetParameter("timestamp", timeStamp);
            paySignReqHandler.SetParameter("url", decodeUrl);

            signature = paySignReqHandler.CreateSHA1Sign();

            return(new JsSdkResp
            {
                AppId = appId,
                Timestamp = timeStamp,
                NonceStr = nonceStr,
                Signature = signature
            });
        }
Exemple #12
0
        /// <summary>
        /// H5支付
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="hc"></param>
        /// <returns></returns>
        public async Task <IActionResult> 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 notifyUrl = TenPayV3Info.TenPayV3Notify.Replace("/TenpayV3/", "/TenpayRealV3/");

                TransactionsRequestData.Scene_Info sence_info = new(HttpContext.UserHostAddress()?.ToString(), null, null, new("Wap", null, null, null, null));

                TransactionsRequestData requestData = new(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, new TenpayDateTime(DateTime.Now.AddHours(1), false), null, notifyUrl, null, new() { currency = "CNY", total = price }, new(openId), null, null, sence_info);

                WeixinTrace.SendCustomLog("H5Pay接口请求", requestData.ToJson());

                var result = await _basePayApis.H5Async(requestData);

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

                if (!result.VerifySignSuccess == true)
                {
                    return(Content("未通过验证,请检查数据有效性!"));
                }

                //直接跳转
                return(Redirect(result.h5_url));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
Exemple #13
0
        public async Task <IActionResult> WxPayIndex()
        {
            // 获取openId
            var openId = HttpContext.Session.GetString("OpenId");

            if (string.IsNullOrEmpty(openId))
            {
                return(Json(Url.Action("Index", "Home")));
            }
            var accessToken = HttpContext.Session.GetString("accessToken");

            HttpContext.Session.SetString("SiteUrl", _siteUrl);

            // 根据openId 查询用户
            var user = _authSrv.GetUserByExternalId(openId, 1);

            // 获取微信用户信息
            OAuthUserInfo userInfo = OAuthApi.GetUserInfo(accessToken, openId);

            // 用户存在则获取信息,不存在则创建用户
            if (user == null)
            {
                var newUser = new BaseUser {
                    UserName = openId, ExternalId = openId, ExternalType = 1, ExternalName = userInfo.nickname
                };
                var result = await _authSrv.CreateUser(newUser, openId);

                if (result.Succeeded)
                {
                    var role = await _authSrv.AddRolesAsync(openId, new string[] { "SysUser" });
                }
                user = newUser;
            }
            var paidOrders = _orderSrv.GetPaidOrders().Where(q => (q.OrderType == OrderType.BuyInStore || q.OrderType == OrderType.BuyOnline) && q.BuyerIdentity == openId);

            // Card
            var jssdkUiPackage = JSSDKHelper.GetJsSdkUiPackage(TenPayV3Info.AppId, TenPayV3Info.AppSecret, Request.AbsoluteUri());
            var api_ticket     = WxCardApiTicketContainer.TryGetWxCardApiTicket(TenPayV3Info.AppId, TenPayV3Info.AppSecret);

            // var openId = HttpContext.Session.GetString("OpenId");
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr  = TenPayV3Util.GetNoncestr();
            var sign      = JSSDKHelper.GetcardExtSign(api_ticket, timeStamp, "pukHe541WmaHEBgW3gACiBCD4EbY", nonceStr);
            var cardExt   = new { timestamp = timeStamp, signature = sign, nonce_str = nonceStr };

            // 登陆Identity用户
            await _authSrv.Login(user);

            ViewData["credit"]         = user.Credit;
            ViewData["biz"]            = _biz;
            ViewData["userInfo"]       = userInfo;
            ViewData["paidOrders"]     = paidOrders;
            ViewData["jssdkUiPackage"] = jssdkUiPackage;
            ViewData["cardExt"]        = JsonConvert.SerializeObject(cardExt);

            return(View());
            // 前端菜单:直接支付,跳转js支付,余额支付跳转/Home/CreditPay,套餐支付:
        }
        public IActionResult Index([FromQuery] string prepay_id)
        {
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr  = TenPayV3Util.GetNoncestr();
            var package   = string.Format("prepay_id={0}", prepay_id);
            var paysign   = TenPayV3.GetJsPaySign("wx40a04481d2e12c20", timeStamp, nonceStr, package, tenPyConfigRead.Key);

            return(Ok(new { timeStamp, nonceStr, package, paysign }));
        }
Exemple #15
0
 public TenPayV3JSAPIParameters(string prepay_id)
 {
     this.AppId     = WeChatInfo.AppID;
     this.TimeStamp = TenPayV3Util.GetTimestamp();
     this.NonceStr  = TenPayV3Util.GetNoncestr();
     this.Package   = string.Format("prepay_id={0}", prepay_id);
     this.SignType  = "MD5";
     this.PaySign   = TenPayV3.GetJsPaySign(this.AppId, this.TimeStamp, this.NonceStr, this.Package, WeChatInfo.Key);
 }
Exemple #16
0
        public object Do_Payment(object param)
        {
            PaymentParam paymentParam = JsonConvert.DeserializeObject <PaymentParam>(param.ToString());

            if (paymentParam == null)
            {
                throw new ApiException(CodeMessage.InvalidParam, "InvalidParam");
            }

            try
            {
                SessionBag sessionBag = SessionContainer.GetSession(paymentParam.token);
                var        openId     = sessionBag.OpenId;
                var        billId     = this.createBill(openId, paymentParam);
                var        totalPrice = this.getBillPrice(paymentParam);
                if (totalPrice == 0)
                {
                    throw new ApiException(CodeMessage.PaymentTotalPriceZero, "PaymentTotalPriceZero");
                }
                var timeStamp   = TenPayV3Util.GetTimestamp();
                var nonceStr    = TenPayV3Util.GetNoncestr();
                var product     = paymentParam.product;
                var xmlDataInfo =
                    new TenPayV3UnifiedorderRequestData(
                        tenPayV3Info.AppId,
                        tenPayV3Info.MchId,
                        product,
                        billId,
                        totalPrice,
                        "127.0.0.1",
                        tenPayV3Info.TenPayV3Notify,
                        TenPayV3Type.JSAPI,
                        openId,
                        tenPayV3Info.Key,
                        nonceStr);

                var result = TenPayV3.Html5Order(xmlDataInfo);
                pDao.writePrePayId(billId, result.prepay_id);
                var package = string.Format("prepay_id={0}", result.prepay_id);
                var paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key);

                PaymentResults paymentResults = new PaymentResults();
                paymentResults.appId     = tenPayV3Info.AppId;
                paymentResults.nonceStr  = nonceStr;
                paymentResults.package   = package;
                paymentResults.paySign   = paySign;
                paymentResults.timeStamp = timeStamp;
                paymentResults.product   = product;
                paymentResults.billId    = billId;

                return(paymentResults);
            }
            catch (Exception ex)
            {
                throw new ApiException(CodeMessage.PaymentError, "PaymentError");
            }
        }
Exemple #17
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);
        }
Exemple #18
0
        /// <summary>
        /// 获取给 JsApi UI 使用的打包签名信息
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="prepayId"></param>
        /// <returns></returns>
        public static JsApiUiPackage GetJsApiUiPackage(string appId, string prepayId)
        {
            var timeStamp       = TenPayV3Util.GetTimestamp();
            var nonceStr        = TenPayV3Util.GetNoncestr();
            var prepayIdPackage = prepayId.Contains("prepay_id=") ? prepayId : string.Format("prepay_id={0}", prepayId);
            var sign            = TenPaySignHelper.CreatePaySign(timeStamp, nonceStr, prepayIdPackage);

            JsApiUiPackage jsApiUiPackage = new(appId, timeStamp, nonceStr, prepayIdPackage, sign);

            return(jsApiUiPackage);
        }
        public ActionResult GetPrepayid(string sessionId)
        {
            try
            {
                var sessionBag = SessionContainer.GetSession(sessionId);
                var openId = sessionBag.OpenId;


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

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

                var body = "小程序微信支付Demo";
                var price = 1;//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, Config.SenparcWeixinSetting.TenPayV3_MchId, body, sp_billno,
                    price, Request.UserHostAddress, Config.SenparcWeixinSetting.TenPayV3_WxOpenTenpayNotify, TenPay.TenPayV3Type.JSAPI, openId, Config.SenparcWeixinSetting.TenPayV3_Key, nonceStr);

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

                WeixinTrace.SendCustomLog("统一订单接口调用结束", "请求:" + xmlDataInfo.ToJson() + "\r\n\r\n返回结果:" + result.ToJson());

                var packageStr = "prepay_id=" + result.prepay_id;

                //记录到缓存

                var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance();
                cacheStrategy.Set($"WxOpenUnifiedorderRequestData-{openId}", xmlDataInfo, TimeSpan.FromDays(4));//3天内可以发送模板消息
                cacheStrategy.Set($"WxOpenUnifiedorderResultData-{openId}", result, TimeSpan.FromDays(4));//3天内可以发送模板消息

                return Json(new
                {
                    success = true,
                    prepay_id = result.prepay_id,
                    appId = Config.SenparcWeixinSetting.WxOpenAppId,
                    timeStamp,
                    nonceStr,
                    package = packageStr,
                    //signType = "MD5",
                    paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, Config.SenparcWeixinSetting.TenPayV3_Key)
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }

        }
Exemple #20
0
        /// <summary>
        /// 原生支付 模式一
        /// </summary>
        /// <returns></returns>
        public ActionResult Native()
        {
            try
            {
                RequestHandler nativeHandler = new RequestHandler(null);
                string         timeStamp     = TenPayV3Util.GetTimestamp();
                string         nonceStr      = TenPayV3Util.GetNoncestr();

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

                nativeHandler.SetParameter("appid", TenPayV3Info.AppId);
                nativeHandler.SetParameter("mch_id", TenPayV3Info.MchId);
                nativeHandler.SetParameter("time_stamp", timeStamp);
                nativeHandler.SetParameter("nonce_str", nonceStr);
                nativeHandler.SetParameter("product_id", productId);
                string sign = nativeHandler.CreateMd5Sign("key", TenPayV3Info.Key);

                var url = TenPayOldV3.NativePay(TenPayV3Info.AppId, timeStamp, TenPayV3Info.MchId, nonceStr, productId, sign);

                BitMatrix bitMatrix;
                bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 600, 600);
                var bw = new ZXing.BarcodeWriterPixelData();

                var pixelData = bw.Write(bitMatrix);
                var bitmap    = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

                var fileStream = 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(_fileStream, System.Drawing.Imaging.ImageFormat.Png);
                _fileStream.Seek(0, SeekOrigin.Begin);

                return(File(_fileStream, "image/png"));
            }
            catch (Exception ex)
            {
                SenparcTrace.SendCustomLog("TenPayV3.Native 执行出错", ex.Message);
                SenparcTrace.BaseExceptionLog(ex);

                throw;
            }
        }
Exemple #21
0
        public ActionResult WxPayOrder(Guid orderid, Guid payid)
        {
            try
            {
                var openId = HttpContext.Session.GetString("OpenId");

                var order = _orderSrv.GetProductOrderById(orderid);
                var pay   = _paySrv.GetPaymentOrderById(payid);
                if (order == null)
                {
                    return(NotFound());
                }
                string sp_billno = GuidEncoder.Encode(pay.Id);
                var    timeStamp = TenPayV3Util.GetTimestamp();
                var    nonceStr  = TenPayV3Util.GetNoncestr();

                var body        = payid.ToString();
                var price       = (int)(order.Amount * 100);
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.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["appId"]      = TenPayV3Info.AppId;
                ViewData["timeStamp"]  = timeStamp;
                ViewData["nonceStr"]   = nonceStr;
                ViewData["package"]    = package;
                ViewData["paySign"]    = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);
                ViewData["successUrl"] = Url.Action("WxPayOrder", "WxPay", new { orderid = orderid, payid = payid });
                // //临时记录订单信息,留给退款申请接口测试使用
                // HttpContext.Session.SetString("BillNo", sp_billno);
                // HttpContext.Session.SetString("BillFee", price.ToString());
                ViewData["order"] = order;
                ViewData["pay"]   = pay;
                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));
            }
        }
Exemple #22
0
        public ActionResult GetPrepayid(string sessionId)
        {
            try
            {
                var sessionBag = SessionContainer.GetSession(sessionId);
                var openId     = sessionBag.OpenId;


                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                var sp_billno = string.Format("{0}{1}{2}", Service.Config.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                              Guid.NewGuid().ToString("n").Substring(0, 6));
                //生成订单信息并保存到数据库

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

                var body        = "小程序微信支付Demo";
                var price       = 1;//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(Service.Config.WxOpenAppId, Service.Config.MchId,
                                                                      body, sp_billno, price, Request.UserHostAddress, Service.Config.TenPayV3Notify,
                                                                      TenPayV3Type.JSAPI, openId, Service.Config.TenPayV3_Key, nonceStr);

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

                var packageStr = "prepay_id=" + result.prepay_id;

                return(Json(new
                {
                    success = true,
                    prepay_id = result.prepay_id,
                    appId = Service.Config.WxOpenAppId,
                    timeStamp,
                    nonceStr,
                    package = packageStr,
                    //signType = "MD5",
                    paySign = TenPayV3.GetJsPaySign(Service.Config.WxOpenAppId, timeStamp, nonceStr, packageStr, Service.Config.TenPayV3_Key)
                }));
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    success = false,
                    msg = ex.Message
                }));
            }
        }
Exemple #23
0
        public ActionResult JsApi(int?id, string Tel, string Price, string host)
        {
            OrdersEntity ordersEntity = new OrdersEntity()
            {
                TelphoneID = id,
                Tel        = Tel,
                Price      = Convert.ToDecimal(Price),
                Host       = host,
                PayType    = "JsApi"
            };

            //创建订单表
            ordersEntity = ordersbll.SaveForm(ordersEntity);

            var openId    = (string)Session["OpenId"];
            var sp_billno = ordersEntity.OrderSn;
            var nonceStr  = TenPayV3Util.GetNoncestr();
            var timeStamp = TenPayV3Util.GetTimestamp();

            //商品Id,用户自行定义
            var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID2, tenPayV3Info.MchId, "JSAPI购买靓号", sp_billno,
                                                                    Convert.ToInt32(ordersEntity.Price * 100),
                                                                    Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, tenPayV3Info.Key, nonceStr);
            var result = TenPayV3.Unifiedorder(xmlDataInfoH5); //调用统一订单接口

            LogHelper.AddLog(result.ResultXml);                //记录日志
            var package = string.Format("prepay_id={0}", result.prepay_id);

            if (result.return_code == "SUCCESS")
            {
                WFTWxModel jsApiPayData = new WFTWxModel()
                {
                    appId        = WeixinConfig.AppID2,
                    timeStamp    = timeStamp,
                    nonceStr     = nonceStr,
                    package      = package,
                    paySign      = TenPayV3.GetJsPaySign(WeixinConfig.AppID2, timeStamp, nonceStr, package, WeixinConfig.Key),
                    callback_url = "https://shop.jnlxsm.net/webapp/jinan2/paymentFinish/" + ordersEntity.Id
                };
                ViewBag.WxModel = jsApiPayData;
                LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志
            }
            return(View(ordersEntity));
        }
        /// <summary>
        /// 按订单号进行支付
        /// </summary>
        /// <param name="orderid">订单号</param>
        /// <returns></returns>
        public ActionResult Pay(long orderid = 81150718819501)
        {
            //TODO:将该页加入登录页,就可以启用下边的注释
            //var userid = UserInfo.UserId;
            //var openId = UserInfo.WxOpenId;
            var userid = 161;
            var openId = "oOGootzpwe38CkQSTj00wyHhKSMk";
            var order  = OrderService.GetOrderViewModel(userid, orderid);

            if (string.IsNullOrEmpty(order.ProductName) || order.OrderId == 0 || order.TotalMoney == 0M)
            {
                return(Content("ERROR"));
            }
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr  = TenPayV3Util.GetNoncestr();

            var pre_id = WeixinPay.WeixinPayApi.Unifiedorder(order.ProductName, order.OrderId, order.TotalMoney, Request.UserHostAddress, openId);

            if (pre_id == "ERROR" || pre_id == "FAIL")
            {
                return(Content("ERROR"));
            }
            var package = "prepay_id=" + pre_id;

            var req = new RequestHandler(null);

            req.SetParameter("appId", AppId);
            req.SetParameter("timeStamp", timeStamp);
            req.SetParameter("nonceStr", nonceStr);
            req.SetParameter("package", package);
            req.SetParameter("signType", "MD5");
            var paySign = req.CreateMd5Sign("key", PayKey);

            //绑定页面数据
            ViewBag.TimeStamp = timeStamp;
            ViewBag.NonceStr  = nonceStr;
            ViewBag.PaySign   = paySign;
            ViewBag.Package   = package;
            ViewBag.AppId     = AppId;
            ViewBag.OrderId   = order.OrderId;
            return(View());
        }
Exemple #25
0
        private static void ChooseWXPay(HttpContext context)
        {
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr  = TenPayV3Util.GetNoncestr();

            var prepayId          = GetPrepayOrder(context.Request);
            var paySignReqHandler = new Dictionary <string, string>()
            {
                { "appId", ConfigHelper.AppConfig["appId"] },
                { "timeStamp", timeStamp },
                { "nonceStr", nonceStr },
                { "package", "prepay_id=" + prepayId },
                { "signType", "MD5" }
            };
            var paySign = paySignReqHandler.CreateMd5Sign("key", ConfigHelper.AppConfig["appKey"], context.Request.ContentEncoding.BodyName);

            paySignReqHandler.Remove("appId");
            paySignReqHandler.Add("paySign", paySign);

            context.Response.Write(JsonConvert.SerializeObject(paySignReqHandler));
        }
Exemple #26
0
        public static PayRequestData GetPayData(Vip model, string hostAddress)
        {
            //var _payInfo = TenPayV3InfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]];
            var _payInfo = GetTenPayInfo();

            _payInfo.TenPayV3Notify = AppConfig.Instance.PayNotify;
            var orderCode   = string.Format("{0}{1}{2}", _payInfo.MchId, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));
            var productInfo = "中捷足球-教练培训费";

            //var mpconfig = GetMpConfigModel();
            var price     = 5000 * 100; //(int)((mpconfig == null  || mpconfig.VipFee == 0 ? 50 : mpconfig.VipFee) * 100);
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonestr   = TenPayV3Util.GetNoncestr();

            var data = new TenPayV3UnifiedorderRequestData(_payInfo.AppId, _payInfo.MchId, productInfo, orderCode, price, hostAddress, _payInfo.TenPayV3Notify,
                                                           Senparc.Weixin.MP.TenPayV3Type.JSAPI, model.WeChatId, _payInfo.Key, nonestr);

            Senparc.Weixin.WeixinTrace.SendCustomLog("支付请求日志1", Newtonsoft.Json.JsonConvert.SerializeObject(data));

            var result = TenPayV3.Unifiedorder(data);

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

            var reqData = new PayRequestData
            {
                OrderCode = orderCode,
                Fee       = price,
                AppId     = _payInfo.AppId,
                TimeStamp = timeStamp,
                NonceStr  = nonestr,
                Package   = package,
                PaySign   = TenPayV3.GetJsPaySign(_payInfo.AppId, timeStamp, nonestr, package, _payInfo.Key),
                VipName   = model.VipName
            };

            Senparc.Weixin.WeixinTrace.SendCustomLog("支付请求日志1", Newtonsoft.Json.JsonConvert.SerializeObject(reqData));


            return(reqData);
        }
Exemple #27
0
        public ActionResult pay(string orderno)
        {
            var ordersEntity = ordersbll.GetEntityByOrderSn(orderno);

            if (ordersEntity != null)
            {
                var nonceStr  = TenPayV3Util.GetNoncestr();
                var timeStamp = TenPayV3Util.GetTimestamp();

                //商品Id,用户自行定义
                var xmlDataInfoH5 = new TenPayV3UnifiedorderRequestData(WeixinConfig.AppID, tenPayV3Info.MchId, ordersEntity.Tel, ordersEntity.OrderSn,
                                                                        Convert.ToInt32(Convert.ToDecimal(ordersEntity.Price) * 100), //1
                                                                        Request.UserHostAddress, WeixinConfig.TenPayV3Notify, TenPayV3Type.JSAPI, CurrentWxUser.OpenId, tenPayV3Info.Key, nonceStr);
                var result = TenPayV3.Unifiedorder(xmlDataInfoH5);                                                                    //调用统一订单接口
                LogHelper.AddLog(result.ResultXml);                                                                                   //记录日志
                var package = string.Format("prepay_id={0}", result.prepay_id);
                if (result.return_code == "SUCCESS")
                {
                    WFTWxModel jsApiPayData = new WFTWxModel()
                    {
                        appId     = WeixinConfig.AppID,
                        timeStamp = timeStamp,
                        nonceStr  = nonceStr,
                        package   = package,
                        paySign   = TenPayV3.GetJsPaySign(WeixinConfig.AppID, timeStamp, nonceStr, package, WeixinConfig.Key)
                    };
                    ViewBag.id      = ordersEntity.Id;
                    ViewBag.WxModel = jsApiPayData;
                    LogHelper.AddLog(JsonConvert.SerializeObject(jsApiPayData));//记录日志
                }
                return(View());
            }
            else
            {
                ReturnJson root = new ReturnJson {
                    code = 400, msg = "订单号不存在!"
                };
                return(Json(root));
            }
        }
Exemple #28
0
        /// <summary>
        /// 若不管用,请在公众号官方后台---功能设置----js接口安全域名 设置
        ///    初始化微信分享
        /// </summary>
        /// <param name="wxModel"></param>
        /// <param name="fxUrl">分享的目标url,如果传过来的值为空字符串或者为null则默认是当前的网址</param>
        public void jssdkInit(Model.wx_userweixin wxModel, string fxUrl)
        {
            fxModel.appId     = wxModel.AppId;
            fxModel.timestamp = TenPayV3Util.GetTimestamp();
            fxModel.nonceStr  = TenPayV3Util.GetNoncestr();
            fxModel.thisUrl   = HttpContext.Current.Request.Url.ToString();
            // fxModel.fxUrl = MyCommFun.getWebSite() + "/weixin/huodong/index.aspx";
            if (fxUrl == null || fxUrl.Trim() == "")
            {
                fxModel.fxUrl = fxModel.thisUrl;
            }
            else
            {
                fxModel.fxUrl = fxUrl;
            }
            JsApiTicketContainer.Register(wxModel.AppId, wxModel.AppSecret);
            var ticketResult = JsApiTicketContainer.GetTicketResult(wxModel.AppId); //获取Ticket完整结果(包括当前过期秒数)

            // 这里参数的顺序要按照 key 值 ASCII 码升序排序
            string rawstring = "jsapi_ticket=" + ticketResult.ticket + "&noncestr=" + fxModel.nonceStr + "&timestamp=" + fxModel.timestamp + "&url=" + fxModel.thisUrl + "";

            fxModel.signature = SHA1_Hash(rawstring);
        }//end:function
#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释
        public WeChatUnifiedorderResult Pay(WeChatUnifiedorderParamter paramter)
#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
        {
            string nonceStr  = GetNonceStr(paramter);
            string timeStamp = TenPayV3Util.GetTimestamp();

            TenPayV3UnifiedorderRequestData tenPayV3UnifiedorderRequestData = new TenPayV3UnifiedorderRequestData(
                Options.WeChatBaseOptions.AppId, Options.WeChatBaseOptions.MchId, paramter.Body, paramter.OutTradeNo, paramter.TotalFee, Options.WeChatBaseOptions.UserHostAddress,
                GetNotifyUrl(Options.WeChatBaseOptions.PayNotifyUrl, WeChatNotifyType.Pay), paramter.TradeType, paramter.OpenId, Options.WeChatBaseOptions.Key,
                nonceStr, paramter.DeviceInfo, paramter.TimeStart, paramter.TimeExpire, GetDetail(paramter), paramter.Attach,
                paramter.FeeType, paramter.GoodsTag, paramter.ProductId, paramter.LimitPay, GetSceneInfo(paramter), paramter.ProfitSharing);

            UnifiedorderResult unfortifiedResult = TenPayV3.Unifiedorder(tenPayV3UnifiedorderRequestData);

            if (unfortifiedResult.return_code != Model.ReturnCode.SUCCESS)
            {
                throw new WeChatServiceException($"微信统一下单失败, return_code: {unfortifiedResult.return_code}, return_msg: {unfortifiedResult.return_msg}.",
                                                 unfortifiedResult, typeof(UnifiedorderResult));
            }

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

            return(new WeChatUnifiedorderResult
            {
                ResultXml = unfortifiedResult.ResultXml,
                DeviceInfo = unfortifiedResult.device_info,
                TradeType = unfortifiedResult.trade_type,
                MWebUrl = unfortifiedResult.mweb_url,
                PrepayId = unfortifiedResult.prepay_id,

                TimeStamp = timeStamp,
                NonceStr = nonceStr,
                Package = package,
                CodeUrl = unfortifiedResult.code_url,
                JsPaySign = TenPayV3.GetJsPaySign(Options.WeChatBaseOptions.AppId, timeStamp, nonceStr, package, Options.WeChatBaseOptions.Key)
            });
        }
Exemple #30
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 = 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);

                //临时记录订单信息,留给退款申请接口测试使用
                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));
            }
        }