コード例 #1
0
        /**
         * 生成扫描支付模式一URL
         * @param productId 商品ID
         * @return 模式一URL
         */

        public string GetPrePayUrl(string productId)
        {
            Log.Info(GetType().ToString(), "Native pay mode 1 url is producing...");

            var data = new WxPayData();

            data.SetValue("appid", WxPayConfig.APPID);                 //公众帐号id
            data.SetValue("mch_id", WxPayConfig.MCHID);                //商户号
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp()); //时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());   //随机字符串
            data.SetValue("product_id", productId);                    //商品ID
            data.SetValue("sign", data.MakeSign());                    //签名
            var str = ToUrlParams(data.GetValues());                   //转换为URL串
            var url = "weixin://wxpay/bizpayurl?" + str;

            Log.Info(GetType().ToString(), "Get native pay mode 1 url : " + url);
            return(url);
        }
コード例 #2
0
        /**
         *
         * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数,
         * 微信浏览器调起JSAPI时的输入参数格式如下:
         * {
         *   "appId" : "wx2421b1c4370ec43b",     //公众号名称,由商户传入
         *   "timeStamp":" 1395712654",         //时间戳,自1970年以来的秒数
         *   "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串
         *   "package" : "prepay_id=u802345jgfjsdfgsdg888",
         *   "signType" : "MD5",         //微信签名方式:
         *   "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
         * }
         * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用
         * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
         *
         */
        private string GetJsApiParameters()
        {
            //Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

            WxPayData jsApiParam = new WxPayData();

            jsApiParam.SetValue("appId", _unifiedOrderResult.GetValue("appid"));
            jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + _unifiedOrderResult.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

            string parameters = jsApiParam.ToJson();

            //Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return(parameters);
        }
コード例 #3
0
        /// <summary>
        /// 商家活动
        /// </summary>
        /// <returns></returns>
        public ActionResult ActList()
        {
            var model = new List <Tuple <string, string, string, DateTime, DateTime, bool, TargetCode> >();

            var kanjiaList = IKanJiaService.GetList(x => x.UserID == LoginUser.ID).Select(x =>
            {
                return(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Kanjia));
            }).ToList();

            if (kanjiaList != null && kanjiaList.Count > 0)
            {
                model.AddRange(kanjiaList);
            }
            var pintuanList = IPinTuanService.GetList(x => x.UserID == LoginUser.ID);

            pintuanList.ForEach(x =>
            {
                model.Add(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Pintuan));
            });

            var miaoshaList = IMiaoShaService.GetList(x => x.UserID == LoginUser.ID);

            miaoshaList.ForEach(x =>
            {
                model.Add(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Miaosha));
            });

            var pintuList = IPinTuService.GetList(x => x.UserID == LoginUser.ID);

            pintuList.ForEach(x =>
            {
                model.Add(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Pintu));
            });

            ViewBag.AppId = Params.WeixinAppId;
            string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret);

            ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp();
            ViewBag.NonceStr  = WxPayApi.GenerateNonceStr();
            ViewBag.Signature = WxPayApi.GetSignature(Request.Url.ToString().Split('#')[0], cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr);

            ViewBag.List = model.OrderByDescending(x => x.Item4).ToList();
            return(View());
        }
コード例 #4
0
        /// <summary>
        /// 秒杀页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult MiaoSha(string id)
        {
            var model = IMiaoShaService.Find(id);

            if (model == null)
            {
                return(Forbidden());
            }
            model.ClickCount++;
            IMiaoShaService.Update(model);
            ViewBag.AppId = Params.WeixinAppId;
            string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret);

            ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp();
            ViewBag.NonceStr  = WxPayApi.GenerateNonceStr();
            ViewBag.Signature = WxPayApi.GetSignature(Request.Url.ToString().Split('#')[0], cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr);
            ViewBag.IsReport  = IUserActivityService.IsExits(x => x.TargetID == id && x.JoinUserID == LoginUser.ID);
            return(View(model));
        }
コード例 #5
0
        /// <summary>
        /// 生成扫描支付模式一URL
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <returns>模式一URL</returns>
        public string GetPrePayUrl(string productId)
        {
            LogHelper.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");

            WxPayData data = new WxPayData();

            data.SetValue("appid", WxPayConfig.AppId);                 //公众帐号id
            data.SetValue("mch_id", WxPayConfig.MchId);                //商户号
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp()); //时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());   //随机字符串
            data.SetValue("product_id", productId);                    //商品ID
            data.SetValue("sign", data.MakeSign());                    //签名
            string str = ToUrlParams(data.GetValues());                //转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;

            //weixin://wxpay/bizpayurl?appid=wx426b3015555a46be&mch_id=1900009851&nonce_str=lz2gmz19sbeteufbg2onmbt9sabv0kef&product_id=123456789&time_stamp=1531917401&sign=69C6AEFFF6943AADCF84C4FA372BE60D
            LogHelper.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
            return(url);
        }
コード例 #6
0
        public string H5Pay(string subject, string body, string notifyUrl, string returnUrl, PayLog payLog, Payment payment,
                            Dictionary <string, string> param = null)
        {
            var config = _configService.Get <WeiXinConfig>();

            WxPayData data = new WxPayData();

            data.SetValue("body", body);
            data.SetValue("out_trade_no", payLog.TransactionNo);
            data.SetValue("total_fee", Convert.ToInt32(payLog.OrderAmount * 100));
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", body);
            data.SetValue("trade_type", "WAP");
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("notify_url", notifyUrl);

            WeiXinPayConfig weiXinPayConfig = new WeiXinPayConfig()
            {
                APPID = config.AppId, MCHID = config.MchId, KEY = config.Key
            };
            WxPayData result = WxPayApi.UnifiedOrder(data, 6, weiXinPayConfig);

            if (result.GetValue("return_code").ToString().Equals("fail", StringComparison.OrdinalIgnoreCase))
            {
                return(result.GetValue("return_msg").ToString());
            }

            WxPayData reSignWxPayData = new WxPayData();

            reSignWxPayData.SetValue("appid", result.GetValue("appid"));
            reSignWxPayData.SetValue("partnerid", result.GetValue("mch_id"));
            reSignWxPayData.SetValue("prepayid", result.GetValue("prepay_id"));
            reSignWxPayData.SetValue("noncestr", result.GetValue("nonce_str"));
            reSignWxPayData.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
            reSignWxPayData.SetValue("package", "WAP");
            reSignWxPayData.SetValue("sign", reSignWxPayData.MakeSign(weiXinPayConfig.KEY));

            var deepLink = $"weixin://wap/pay?{HttpUtility.UrlEncode(reSignWxPayData.ToUrl())}";

            return($"<script>location.href='{deepLink}';</script>");
        }
コード例 #7
0
        // GET: User
        public ActionResult BuyTime()
        {
            if (LoginUser == null)
            {
                return(Redirect("/login/index?redirect_uri=" + this.Request.Url.ToString()));
            }
            var user = IUserService.Find(LoginUser.ID);

            if (user.Password.IsNullOrEmpty())
            {
                return(RedirectToAction("PersonData", "user"));
            }
            ViewBag.AppId = Params.WeixinAppId;
            string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret);

            ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp();
            ViewBag.NonceStr  = WxPayApi.GenerateNonceStr();
            ViewBag.Signature = WxPayApi.GetSignature(Params.SiteUrl, cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr);
            return(View(IRechargePlanService.GetList()));
        }
コード例 #8
0
        private static void SDK_Config(HttpContext context)
        {
            JS_SDKModel model = new JS_SDKModel();

            try
            {
                var windowurl = context.Request["windowurl"];
                var action    = context.Request["action"];
                LogTextHelper.Log("action:" + action + " windowurl_1:" + windowurl);
                WxPayData jsApiParam = new WxPayData();
                model.appId     = WeChatConfig.AppId;
                model.timeStamp = WxPayApi.GenerateTimeStamp();
                model.nonceStr  = WxPayApi.GenerateNonceStr();
                model.ticket    = string.Empty;
                //获取jsapi_ticket
                if (HttpRuntime.Cache["JsApiTicket"] == null)
                {
                    model.ticket = WxPayApi.initJSAPITicket();
                }
                model.ticket = HttpRuntime.Cache["JsApiTicket"] as string;
                if (string.IsNullOrEmpty(model.ticket))
                {
                    model.ticket = WxPayApi.initJSAPITicket();
                }
                //构造需要用SHA1算法加密的数据
                WxPayData signData = new WxPayData();
                signData.SetValue("noncestr", model.nonceStr);
                signData.SetValue("jsapi_ticket", model.ticket);
                signData.SetValue("timestamp", model.timeStamp);
                signData.SetValue("url", windowurl);
                string param = signData.ToUrl();
                model.signature = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
            }
            catch (Exception ex)
            {
                model.status = 0;
                model.msg    = ex.Message;
                LogTextHelper.Log(ex.ToString());
            }
            context.Response.Write(JsonConvert.SerializeObject(model));
        }
コード例 #9
0
ファイル: SetWebConfing.cs プロジェクト: a864610877/MEINUO
        public void Set()
        {
            // Load();
            //if(Account!=null)
            //{
            //    ImageUrl = Account.qrCodeUrl;
            //}
            //appId = WxPayConfig.APPID;
            // var access_token = AccessTokenContainer.GetToken(WxPayConfig.APPID);
            var jsapi_ticket = Senparc.Weixin.MP.CommonAPIs.CommonApi.GetTicket(WxPayConfig.APPID, WxPayConfig.APPSECRET).ticket;

            timestamp = WxPayApi.GenerateTimeStamp();
            nonceStr  = WxPayApi.GenerateNonceStr();
            WxPayData jsApiParam = new WxPayData();

            jsApiParam.SetValue("noncestr", nonceStr);
            jsApiParam.SetValue("jsapi_ticket", jsapi_ticket);
            jsApiParam.SetValue("timestamp", timestamp);
            jsApiParam.SetValue("url", url);
            signature = jsApiParam.SHA1_Hash();
        }
コード例 #10
0
ファイル: JsApiPay.cs プロジェクト: radtek/XuHos
        /**
         *
         * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数,
         * 微信浏览器调起JSAPI时的输入参数格式如下:
         * {
         *   "appId" : "wx2421b1c4370ec43b",     //公众号名称,由商户传入
         *   "timeStamp":" 1395712654",         //时间戳,自1970年以来的秒数
         *   "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串
         *   "package" : "prepay_id=u802345jgfjsdfgsdg888",
         *   "signType" : "MD5",         //微信签名方式:
         *   "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
         * }
         * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用
         * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
         *
         */
        public string GetJsApiParameters(string appId)
        {
            var WxPayConfig = Configuration.GetAppPayConfig <Config.Sections.Pay.WXPay>(appId);


            Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

            WxPayData jsApiParam = new WxPayData();

            jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
            jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign(WxPayConfig.KEY));

            string parameters = jsApiParam.ToJson();

            Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return(parameters);
        }
コード例 #11
0
        public JsonResult GetPaySign(string openid)
        {
            string nonceStr       = WxPayApi.GenerateNonceStr();                       //随机字符串,不长于32位
            string outTradeNo     = WxPayApi.GenerateOutTradeNo();                     //订单号:32个字符内、不得重复
            string spbillCreateIp = WxPayConfig.GetIP(System.Web.HttpContext.Current); //用户端IP
            int    total_fee      = 1;                                                 //订单金额(单位:分),整数
            string trade_type     = "JSAPI";                                           //JSAPI,NATIVE,APP,WAP

            #region 调用统一支付接口获得prepay_id(预支付交易会话标识)
            WxPayData wxPayData = new WxPayData();
            wxPayData.SetValue("appid", WxPayConfig.APPID);            //appid
            wxPayData.SetValue("body", WxPayConfig.BODY);              //支付描述
            wxPayData.SetValue("mch_id", WxPayConfig.MCHID);           //商户id
            wxPayData.SetValue("nonce_str", nonceStr);                 //随机字符串
            wxPayData.SetValue("notify_url", WxPayConfig.NOTIFY_URL);  //回调地址
            wxPayData.SetValue("openid", openid);                      //openid
            wxPayData.SetValue("out_trade_no", outTradeNo);            //订单号
            wxPayData.SetValue("spbill_create_ip", spbillCreateIp);    //客户端ip地址
            wxPayData.SetValue("total_fee", total_fee.ToString());     //订单金额(单位:分),整数
            wxPayData.SetValue("trade_type", trade_type);              //交易类型
            wxPayData.SetValue("sign", wxPayData.MakeSign());          //签名
            string data     = wxPayData.ToXml();
            string prepayId = WeChatTools.UnifiedOrder(data);
            #endregion

            #region 支付参数
            string timeStamp = WxPayApi.GenerateTimeStamp();
            nonceStr = WxPayApi.GenerateNonceStr();
            WxPayData wxPaySign = new WxPayData();
            wxPaySign.SetValue("appId", WxPayConfig.APPID);
            wxPaySign.SetValue("timeStamp", timeStamp);
            wxPaySign.SetValue("nonceStr", nonceStr);
            wxPaySign.SetValue("package", string.Format("prepay_id={0}", prepayId));
            wxPaySign.SetValue("signType", "MD5");
            string paysign = wxPaySign.MakeSign();
            wxPaySign.SetValue("paySign", paysign);
            #endregion

            return(Json(new { data = wxPaySign.GetValues(), openid = openid }, JsonRequestBehavior.AllowGet));
        }
コード例 #12
0
ファイル: WechatController.cs プロジェクト: FH-VMS/FycnApi
        private string MakeJsSign(string appId, string ticket)
        {
            string    timeStamp  = WxPayApi.GenerateTimeStamp();
            string    onceStr    = WxPayApi.GenerateNonceStr();
            string    signature  = string.Empty;
            WxPayData jsApiParam = new WxPayData();

            jsApiParam.SetValue("appId", appId);
            jsApiParam.SetValue("timestamp", timeStamp);
            jsApiParam.SetValue("nonceStr", onceStr);
            //jsApiParam.SetValue("signature", signature);
            //string keys = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket,onceStr,timeStamp, PathConfig.DomainConfig+"/wechat.html");
            Dictionary <string, string> dicParam = new Dictionary <string, string>();

            dicParam["jsapi_ticket"] = ticket;
            dicParam["noncestr"]     = onceStr;
            dicParam["timestamp"]    = timeStamp;
            dicParam["url"]          = PathConfig.DomainConfig + "/wechat.html";

            signature = Sha1(dicParam, Encoding.UTF8).ToLower();
            jsApiParam.SetValue("signature", signature);
            return(jsApiParam.ToJson());
        }
コード例 #13
0
ファイル: getOrderId.ashx.cs プロジェクト: yclcy/waitter
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            Stream      stream  = request.InputStream;

            if (stream.Length != 0)
            {
                int       total_fee    = Convert.ToInt32(request["total_fee"]);
                string    out_trade_no = request["out_trade_no"];
                WxPayData data         = new WxPayData();
                data.SetValue("body", "微特众包-商家充值");//商品描述
                //data.SetValue("attach", "test");//附加数据
                //data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//订单号
                data.SetValue("out_trade_no", out_trade_no);                                          //订单号
                data.SetValue("total_fee", total_fee);                                                //总金额
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                 //交易起始时间
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
                data.SetValue("trade_type", "APP");                                                   //交易类型
                WxPayData result = WxPayApi.UnifiedOrder(data);                                       //调用统一下单接口
                if (result.IsSet("prepay_id"))
                {
                    WxPayData order = new WxPayData();
                    order.SetValue("appid", WxPayConfig.APPID);
                    order.SetValue("partnerid", WxPayConfig.MCHID);
                    order.SetValue("noncestr", WxPayApi.GenerateNonceStr());
                    order.SetValue("prepayid", result.GetValue("prepay_id"));
                    order.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
                    order.SetValue("package", "Sign=WXPay");
                    order.SetValue("sign", order.MakeSign());
                    context.Response.Write(order.ToJson());
                }
            }
            else
            {
                context.Response.Write("");
            }
        }
コード例 #14
0
        public static Dictionary <string, string> APPWxPayUnifiedorder(string trade_no, string body, string total_fee, bool IsOrder = true, bool IsChongZhi = false)
        {
            string url        = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            string wx_appid   = PaymentConfig.WeiXinConfig.MobileAppID;
            string wx_mch_id  = PaymentConfig.WeiXinConfig.MobileMCHID;
            string notify_url = string.Empty;

            if (IsChongZhi)
            {
                notify_url = WeixinConfig.app_chongzhi_notify_url;
            }
            else if (IsOrder)
            {
                notify_url = WeixinConfig.app_notify_url;
            }
            //统一下单
            WxPayData data = new WxPayData();

            data.SetValue("body", body);
            data.SetValue("attach", "test");
            data.SetValue("out_trade_no", trade_no);
            data.SetValue("total_fee", total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", "yongyouapp");
            data.SetValue("trade_type", "APP");
            data.SetValue("notify_url", notify_url);                 //异步通知url
            data.SetValue("appid", wx_appid);                        //公众账号ID
            data.SetValue("mch_id", wx_mch_id);                      //商户号
            data.SetValue("spbill_create_ip", WxPayConfig.IP);       //终端ip
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串
            data.SetValue("sign", data.MakeAPPSign());

            string    xml      = data.ToXml();
            string    response = HttpService.Post(xml, url, false, 6);
            WxPayData result   = new WxPayData();

            result.FromXml(response);

            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                throw new Exception("UnifiedOrder response error!");
            }
            WxPayData appApiParam = new WxPayData();

            appApiParam.SetValue("appid", wx_appid);
            appApiParam.SetValue("partnerid", wx_mch_id);
            appApiParam.SetValue("prepayid", result.GetValue("prepay_id"));
            appApiParam.SetValue("package", "Sign=WXPay");
            appApiParam.SetValue("noncestr", WxPayApi.GenerateNonceStr());
            appApiParam.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
            //appApiParam.SetValue("signType", "MD5");
            appApiParam.SetValue("sign", appApiParam.MakeAPPSign());
            //通信成功
            var res = new Dictionary <string, string>
            {
                { "appid", appApiParam.GetValue("appid").ToString() },
                { "partnerid", appApiParam.GetValue("partnerid").ToString() },
                { "prepayid", appApiParam.GetValue("prepayid").ToString() },
                { "package", appApiParam.GetValue("package").ToString() },
                { "noncestr", appApiParam.GetValue("noncestr").ToString() },
                { "timestamp", appApiParam.GetValue("timestamp").ToString() },
                { "sign", appApiParam.GetValue("sign").ToString() }
            };

            //在服务器上签名
            return(res);
        }
コード例 #15
0
ファイル: MemberDal.cs プロジェクト: skipye/HTJK
        //添加和修改用户信息
        public void AddUser(MemberModel Models, out Guid UserId, out string MemberNumber)
        {
            string Mn  = "";
            Guid   UId = Guid.Empty;

            using (var db = new HTJKEntities())
            {
                int Stoct = 0;

                if (Models.Id != null && Models.Id != Guid.Empty)
                {
                    var Tabels = db.MemberInfo.Where(k => k.Id == Models.Id).FirstOrDefault();
                    Tabels.userName = Models.Name;
                    Tabels.RealName = Models.RealName;
                    Tabels.Telphone = Models.Telphone;
                    Tabels.Age      = Models.Age;
                    Tabels.Email    = Models.Email;
                    Tabels.Sex      = Models.Sex;
                    Tabels.Stock    = Tabels.Stock > 0 ? Tabels.Stock + Stoct : Stoct;
                    Tabels.ZStock   = Tabels.ZStock > 0 ? Tabels.ZStock + Stoct : Stoct;
                }
                else
                {
                    var Tabels = new MemberInfo();
                    Tabels.Id            = Guid.NewGuid();
                    Tabels.userName      = Models.Name;
                    Tabels.RealName      = Models.RealName;
                    Tabels.Password      = Models.Password;
                    Tabels.Telphone      = Models.Telphone;
                    Tabels.Email         = Models.Email;
                    Tabels.CreateTime    = DateTime.Now;
                    Tabels.LoginTimes    = 1;
                    Tabels.LastLoginTime = DateTime.Now;
                    Tabels.Sex           = Models.Sex;
                    Tabels.Stock         = !string.IsNullOrEmpty(Models.RequestNumber) ? 100 : 20;
                    Tabels.ZStock        = !string.IsNullOrEmpty(Models.RequestNumber) ? 100 : 20;
                    Tabels.AddStock      = 0;
                    Tabels.Gold          = 0;
                    Tabels.State         = Models.RealName != null && Models.RealName == "微信注册用户" ? false : true;
                    Tabels.MemberNumber  = "HT" + WxPayApi.GenerateTimeStamp();
                    Mn            = Tabels.MemberNumber;
                    UId           = Tabels.Id;
                    Tabels.OpenId = Models.OpenId;
                    if (!string.IsNullOrEmpty(Models.RequestNumber))
                    {
                        Tabels.RequestNumber_1 = Models.RequestNumber;

                        var Membertabel = db.MemberInfo.Where(k => k.MemberNumber == Models.RequestNumber).FirstOrDefault();
                        if (Membertabel != null)
                        {
                            if (Membertabel.RequestNumber_1 != null)
                            {
                                Tabels.RequestNumber_2 = Membertabel.RequestNumber_1;
                            }
                        }
                    }
                    db.MemberInfo.Add(Tabels);
                }
                UserId = UId;

                MemberNumber = Mn;
                db.SaveChanges();
            }
        }
コード例 #16
0
ファイル: WxController.cs プロジェクト: mm1860/paylive
        /**
         *
         * 网页授权获取用户基本信息的全部过程
         * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
         * 第一步:利用url跳转获取code
         * 第二步:利用code去获取openid和access_token
         *
         */
        public async Task <IActionResult> JsApiPay(string code = "")
        {
            if (!string.IsNullOrEmpty(code))
            {
                //获取code码,以获取openid和access_token
                Log.Debug(this.GetType().ToString(), "Get code : " + code);
                await GetOpenidAndAccessTokenFromCodeAsync(code);
            }
            else
            {
                //构造网页授权获取code的URL
                string    host          = Request.Host.Value;
                string    path          = Request.Path;
                string    redirect_uri  = WebUtility.UrlEncode("http://" + host + path);
                WxPayData authorizedata = new WxPayData();
                authorizedata.SetValue("appid", WxPayConfig.APPID);
                authorizedata.SetValue("redirect_uri", redirect_uri);
                authorizedata.SetValue("response_type", "code");
                authorizedata.SetValue("scope", "snsapi_base");
                authorizedata.SetValue("state", "STATE" + "#wechat_redirect");
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + authorizedata.ToUrl();
                Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url);
                try
                {
                    //触发微信返回code码
                    Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
                }
                catch (Exception ex)
                {
                }
            }

            //获取openid失败
            if (string.IsNullOrEmpty(openid))
            {
                Log.Debug(this.GetType().ToString(), "Get openid : " + openid);
                return(View("JsApiPay", string.Empty));
            }


            //jsapipay统一下单
            WxPayData data = new WxPayData();

            data.SetValue("body", "test");
            data.SetValue("attach", "test");
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
            data.SetValue("total_fee", 100);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", "test");
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", openid);

            WxPayData result = await WxPayApi.UnifiedOrder(data);

            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                //统一下单失败
                return(View("JsApiPay", string.Empty));
            }

            WxPayData jsApiParam = new WxPayData();

            jsApiParam.SetValue("appId", result.GetValue("appid"));
            jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

            string parameters = jsApiParam.ToJson();

            Log.Debug(this.GetType().ToString(), "JsApiPay parameters : " + parameters);
            return(View("JsApiPay", parameters));
        }
コード例 #17
0
ファイル: apiController.cs プロジェクト: chedan1992/bellali
        public IActionResult AddOrdered(Order s)
        {
            var r = new RequestModel();

            try
            {
                if (db.Orders.FirstOrDefault(c => c.Card == s.Card && c.ActiveId == s.ActiveId && s.Status == 1) != null)
                {
                    r.code = 0;
                    r.msg  = "您已经报过名了";
                    return(Ok(r));
                }

                var user = db.Users.Find(s.UserId);

                if (user == null)
                {
                    r.code = 0;
                    r.msg  = "用户信息错误";
                    return(Ok(r));
                }
                //新增
                s.CreateTime = DateTime.Now;
                s.PayTime    = DateTime.Now;
                s.Payno      = WxPayAPI.WxPayApi.GenerateOutTradeNo();

                s.Status = 0;
                //Active active = db.Actives.Find(s.ActiveId);
                Catory catory = db.Catorys.Find(s.ClassId);

                s.Grade    = catory.Title;
                s.Money    = catory.Price;
                s.PayMoney = 0.01M;

                if (s.Id > 0)
                {
                    db.Orders.Update(s);
                }
                else
                {
                    db.Orders.Add(s);
                }

                if (db.SaveChanges() > 0)
                {
                    //Log.WriteLog("11111111:SUCCESS");
                    //生成与支付编号
                    unifiedOrderResult = GetUnifiedOrderResult(s.PayMoney, user.LoginName, s.Payno);
                    //Log.WriteLog("11111111:222222222222222222");

                    WxPayData jsApiParam = new WxPayData();
                    jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
                    jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
                    jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
                    jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                    jsApiParam.SetValue("signType", "MD5");
                    jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

                    r.data = jsApiParam.ToJson();
                    r.code = 1;
                    r.msg  = s.Payno;
                }
                return(Ok(r));
            }
            catch (Exception e)
            {
                //打印日志
                r.msg = e.Message;
            }
            return(Ok(r));
        }
コード例 #18
0
        private string OnPay(DataRow row)
        {
            #region 获取基本参数
            string CommunityId = string.Empty;
            if (row.Table.Columns.Contains("CommunityId"))
            {
                CommunityId = row["CommunityId"].ToString();
            }
            string RoomID = string.Empty;
            if (row.Table.Columns.Contains("RoomID"))
            {
                RoomID = row["RoomID"].ToString();
            }
            string CustID = string.Empty;
            if (row.Table.Columns.Contains("CustID"))
            {
                CustID = row["CustID"].ToString();
            }
            string OpenID = string.Empty;
            if (row.Table.Columns.Contains("OpenID"))
            {
                OpenID = row["OpenID"].ToString();
            }
            if (!row.Table.Columns.Contains("PayChannel") || string.IsNullOrEmpty(row["PayChannel"].ToString()))
            {
                return(new ApiResult(false, "参数PayChannel有误").toJson());
            }
            var community = GetCommunity(CommunityId);
            if (community == null)
            {
                return(JSONHelper.FromString(false, "未查询到小区信息"));
            }

            int CommID = AppGlobal.StrToInt(community.CommID);
            PubConstant.hmWyglConnectionString = GetConnectionStr(community);

            var payChannel = row["PayChannel"].ToString();
            var payType    = 0;

            switch (payChannel.ToLower())
            {
            case PayChannelString.Alipay:
                payType = 1;
                break;

            case PayChannelString.WechatPay:
                payType = 2;
                break;

            case PayChannelString.AllInPay_Alipay:
                payType = 1;
                break;

            case PayChannelString.AllInPay_WechatPay:
                payType = 2;
                break;

            default:
                return(new ApiResult(false, "参数payChannel有误").toJson());
            }
            if (payType == 2)
            {
                if (payChannel.ToLower().Equals(PayChannelString.AllInPay_WechatPay) && string.IsNullOrEmpty(OpenID))
                {
                    return(new ApiResult(false, "参数OpenID不能为空").toJson());
                }
            }

            #endregion

            using (IDbConnection erpConn = new SqlConnection(PubConstant.hmWyglConnectionString))
            {
                dynamic tb_Payment_Config = erpConn.QueryFirstOrDefault <dynamic>("SELECT * FROM Tb_Payment_Config WITH(NOLOCK) WHERE CommID = @CommID", new { CommID });
                if (null == tb_Payment_Config)
                {
                    return(new ApiResult(false, "该项目未开通对应支付方式").toJson());
                }
                // 旧方式获取对应支付配置
                AllinConfig allinConfig = null;
                // 新方式获取支付配置
                PaymentConfig paymentConfig = null;
                if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay)
                {
                    try
                    {
                        allinConfig = JsonConvert.DeserializeObject <AllinConfig>(tb_Payment_Config.Config);
                        if (null == allinConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }
                }
                else
                {
                    // 新的方式,Config存储多个配置
                    try
                    {
                        // ERP的配置表,要求存储一个Json数组,用于配置支持不同支付方式
                        // 配置项要求存储一个
                        List <PaymentConfig> configs = JsonConvert.DeserializeObject <List <PaymentConfig> >(tb_Payment_Config.Config);
                        if (null == configs || configs.Count <= 0)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                        if (payChannel == PayChannelString.Alipay)
                        {
                            paymentConfig = configs.Find(item => item.type == "AliPay");
                        }
                        if (payChannel == PayChannelString.WechatPay)
                        {
                            paymentConfig = configs.Find(item => item.type == "WChatPay");
                        }
                        if (null == paymentConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                #region 计算金额
                if (!row.Table.Columns.Contains("PayData") || string.IsNullOrEmpty(row["PayData"].ToString()))
                {
                    return(new ApiResult(false, "缺少参数PayData").toJson());
                }
                string PayData = row["PayData"].ToString();
                if (!CheckPayData(Global_Fun.BurstConnectionString(CommID, Global_Fun.BURST_TYPE_CHARGE), Convert.ToInt64(CustID), Convert.ToInt64(RoomID), PayData, out decimal Amt, out string errMsg, true, false, !"1940".Equals(Global_Var.LoginCorpID)))
                {
                    return(new ApiResult(false, errMsg).toJson());
                }
                if (Amt <= 0.00M)
                {
                    return(new ApiResult(false, "金额必须大于0").toJson());
                }
                #endregion

                JObject PayDataObj = JObject.Parse(PayData);
                int     Type       = (int)PayDataObj["Type"];

                #region 查询项目名称和房屋编号,拼接费用备注
                string FeesMemo = string.Empty;
                string RoomSign = string.Empty;
                if (Type == 1)
                {
                    FeesMemo = "物业综合费用缴纳";
                    string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID });
                    if (string.IsNullOrEmpty(CommName))
                    {
                        CommName = Convert.ToString(CommID);
                    }
                    RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID });
                    if (string.IsNullOrEmpty(RoomSign))
                    {
                        RoomSign = Convert.ToString(RoomID);
                    }

                    FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign);
                }
                else
                {
                    FeesMemo = "物业综合费用预存";
                    string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID });
                    if (string.IsNullOrEmpty(CommName))
                    {
                        CommName = Convert.ToString(CommID);
                    }
                    RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID });
                    if (string.IsNullOrEmpty(RoomSign))
                    {
                        RoomSign = Convert.ToString(RoomID);
                    }

                    FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign);
                }
                #endregion

                string NoticeId = Guid.NewGuid().ToString();

                // 生成订单
                if (erpConn.Execute("INSERT INTO Tb_Notice(Id, CommID, RoomID, CustID, PayData, CreateTime) VALUES(@Id, @CommID, @RoomID, @CustID, @PayData, @CreateTime)", new { Id = NoticeId, CommID, RoomID, CustID, PayData, CreateTime = DateTime.Now.ToString() }) <= 0)
                {
                    return(new ApiResult(false, "创建收款订单失败,请重试").toJson());
                }
                string ChargeMode = "业主APP缴费";
                if (payChannel == PayChannelString.AllInPay_Alipay)
                {
                    ChargeMode = "通联_业主APP(支付宝)";
                }
                else if (payChannel == PayChannelString.AllInPay_WechatPay)
                {
                    ChargeMode = "通联_业主APP(微信)";
                }
                else
                {
                    ChargeMode = "通联_业主APP";
                }
                #region 修改收款方式
                if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM syscolumns WHERE id=object_id('Tb_Notice') AND name = 'ChargeMode'") > 0)
                {
                    erpConn.Execute("UPDATE Tb_Notice SET ChargeMode = @ChargeMode WHERE Id = @Id", new { ChargeMode, Id = NoticeId });
                }
                #endregion
                DateTime dateNow          = DateTime.Now;
                string   OrderSN          = dateNow.ToString("yyyyMMddHHmmssfff") + Utils.BuildRandomStr(3);
                string   PaymentNotifyUrl = string.Empty;

                Dictionary <string, string> param = null;
                if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay)
                {
                    #region 请求通联支付
                    #region 获取对应类型的下账地址
                    if (Type == 1)
                    {
                        PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Notify_Url") + "?CommID=" + CommID;
                    }
                    else
                    {
                        PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Prec_Notify_Url") + "?CommID=" + CommID;
                    }
                    #endregion
                    try
                    {
                        param = SybWxPayService.Pay(Convert.ToInt64(Amt * 100), OrderSN, payChannel == PayChannelString.AllInPay_Alipay ? "A01" : "W06", FeesMemo, RoomSign, OpenID, "", PaymentNotifyUrl, "", "", "", "", allinConfig.orgid, allinConfig.appid, allinConfig.custid, allinConfig.appkey, allinConfig.subbranch);

                        if (param == null || !param.ContainsKey("payinfo"))
                        {
                            GetLog().Error("OnPay:" + JsonConvert.SerializeObject(param));
                            return(new ApiResult(false, "生成支付订单失败,请重试").toJson());
                        }
                    }
                    catch (Exception ex)
                    {
                        GetLog().Error("OnPay", ex);
                        return(new ApiResult(false, "生成支付订单失败,请重试").toJson());
                    }
                    if (erpConn.Execute(@"INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) 
                                            VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)",
                                        new { PayType = payType, OrderSN = OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                    {
                        return(new ApiResult(false, "生成支付订单失败,请重试(1003)").toJson());
                    }
                    return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = param["payinfo"].ToString() }).toJson());

                    #endregion
                }
                if (payChannel == PayChannelString.Alipay)
                {
                    AliConfig aliConfig = null;
                    try
                    {
                        aliConfig = Config.GetConfig <AliConfig>(paymentConfig.config);
                        if (null == aliConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }
                    #region 请求支付宝官方支付
                    #region 获取对应类型的下账地址
                    PaymentNotifyUrl = AppGlobal.GetAppSetting("AliPay_Notify_Url");
                    #endregion
                    AlipayTradeAppPayResponse response = null;
                    try
                    {
                        JObject BizContent = new JObject();
                        //要求15分钟内支付
                        BizContent.Add("timeout_express", "15m");
                        BizContent.Add("total_amount", Amt);
                        BizContent.Add("body", FeesMemo);
                        BizContent.Add("subject", FeesMemo);
                        BizContent.Add("out_trade_no", OrderSN);
                        IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", aliConfig.appid, aliConfig.app_private_key, "json", "1.0", "RSA2", aliConfig.alipay_public_key, "UTF-8", false);
                        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest
                        {
                            BizContent = JsonConvert.SerializeObject(BizContent),
                        };
                        request.SetNotifyUrl(PaymentNotifyUrl);
                        response = client.SdkExecute(request);
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message, "AliPayLogs\\");
                        GetLog().Error(ex.Message + Environment.CommandLine + ex.StackTrace);
                        return(new ApiResult(false, "请求订单失败,请重试").toJson());
                    }
                    if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 1, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                    {
                        return(new ApiResult(false, "生成订单失败").toJson());
                    }
                    return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = response.Body }).toJson());

                    #endregion
                }
                if (payChannel == PayChannelString.WechatPay)
                {
                    WxConfig wxConfig = null;
                    try
                    {
                        wxConfig = Config.GetConfig <WxConfig>(paymentConfig.config);
                        if (null == wxConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }

                    #region 请求微信官方支付
                    #region 获取对应类型的下账地址
                    PaymentNotifyUrl = AppGlobal.GetAppSetting("WxPay_Notify_Url");
                    #endregion
                    WxPayData wxPayData = new WxPayData();
                    wxPayData.SetValue("appid", wxConfig.appid);
                    wxPayData.SetValue("body", FeesMemo);
                    wxPayData.SetValue("mch_id", wxConfig.mch_id);
                    wxPayData.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
                    wxPayData.SetValue("notify_url", PaymentNotifyUrl);
                    wxPayData.SetValue("out_trade_no", OrderSN);
                    wxPayData.SetValue("spbill_create_ip", "8.8.8.8");
                    wxPayData.SetValue("total_fee", Convert.ToInt32(Amt * 100));
                    wxPayData.SetValue("trade_type", "APP");
                    wxPayData.SetValue("sign_type", wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256);
                    wxPayData.SetValue("sign", wxPayData.MakeSign(wxConfig.appkey));
                    try
                    {
                        wxPayData = WxPayApi.UnifiedOrder(wxPayData);
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "请求超时,请重试").toJson());
                    }
                    if (!wxPayData.IsSet("return_code") || !"SUCCESS".Equals(wxPayData.GetValue("return_code").ToString()))
                    {
                        return(new ApiResult(false, "请求支付订单失败").toJson());
                    }
                    if (!wxPayData.IsSet("result_code") || !"SUCCESS".Equals(wxPayData.GetValue("result_code").ToString()))
                    {
                        return(new ApiResult(false, "请求支付订单失败").toJson());
                    }
                    if (!wxPayData.IsSet("prepay_id"))
                    {
                        return(new ApiResult(false, "请求支付订单失败").toJson());
                    }
                    string prepay_id = wxPayData.GetValue("prepay_id").ToString();
                    if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 2, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                    {
                        return(new ApiResult(false, "生成订单失败").toJson());
                    }
                    WxPayData result = new WxPayData();
                    result.SetValue("appid", wxPayData.GetValue("appid").ToString());
                    result.SetValue("partnerid", wxPayData.GetValue("mch_id").ToString());
                    result.SetValue("prepayid", prepay_id);
                    result.SetValue("package", "Sign=WXPay");
                    result.SetValue("noncestr", wxPayData.GetValue("nonce_str").ToString());
                    result.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
                    result.SetValue("sign", result.MakeSign(wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256, wxConfig.appkey));
                    JObject jObj = JObject.Parse(result.ToJson());
                    return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = jObj }).toJson());

                    #endregion
                }
                return(new ApiResult(false, "不支持的支付方式").toJson());
            }
        }
コード例 #19
0
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="setid"></param>
        /// <param name="paytype"></param>
        /// <returns></returns>
        public string createOrder(int setid, int paytype = 2)
        {
            int userid = User.userid;

            //创建订单
            using (shhouseEntities ent = new shhouseEntities())
            {
                ObjectParameter ordernum = new ObjectParameter("ordernum", typeof(string));
                ObjectParameter setname  = new ObjectParameter("setname", typeof(string));
                ObjectParameter state    = new ObjectParameter("state", typeof(int));
                ObjectParameter totals   = new ObjectParameter("totals", typeof(int));
                ObjectParameter msg      = new ObjectParameter("msg", typeof(string));
                ent.order_create_jjr2018(userid, DateTime.Now, DateTime.Now.AddHours(2), setid, 1, paytype, ordernum, setname, totals, state, msg);
                int _state = (int)state.Value;
                if (_state == 1)
                {
                    try
                    {
                        //微信支付
                        NativePay nativePay = new NativePay();
                        WxPayData data      = nativePay.GetPayMsg(setid.ToString(), (string)setname.Value, (string)ordernum.Value, (int)totals.Value);
                        WxPayData ww        = new WxPayData();
                        ww.SetValue("appid", APPconfig.APPID);
                        ww.SetValue("noncestr", data.GetValue("nonce_str"));
                        ww.SetValue("package", "Sign=WXPay");
                        ww.SetValue("partnerid", APPconfig.MCHID);
                        ww.SetValue("prepayid", data.GetValue("prepay_id"));
                        string timestamp = WxPayApi.GenerateTimeStamp();
                        ww.SetValue("timestamp", timestamp);
                        ww.SetValue("sign", data.GetValue("sign"));
                        string sign = ww.MakeSign();

                        if (data == null)
                        {
                            return(JsonConvert.SerializeObject(new repmsg
                            {
                                state = 0,
                                msg = "订单创建失败"
                            }));
                        }

                        return(JsonConvert.SerializeObject(new repmsg
                        {
                            state = 1,
                            msg = "",
                            data = new
                            {
                                tradeno = (string)ordernum.Value,
                                setname = (string)setname.Value,
                                total = (int)totals.Value,
                                json = data.GetValue("result_code"),
                                Sign = sign,
                                prepay_id = data.GetValue("prepay_id"),
                                nonce_str = data.GetValue("nonce_str"),
                                partnerid = APPconfig.MCHID,
                                timestamp = timestamp
                            }
                        }));
                    }
                    catch (Exception e)
                    {
                        return(JsonConvert.SerializeObject(new repmsg
                        {
                            state = 0,
                            msg = e.Message
                        }));
                    }
                }
                else
                {
                    return(JsonConvert.SerializeObject(new repmsg
                    {
                        state = 0,
                        msg = "提交失败,请稍后再试"
                    }));
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// 砍价活动页面
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userActId"></param>
        /// <returns></returns>
        public ActionResult KanJia(string id, string userActId)
        {
            var model = new KanJia();

            if (userActId.IsNotNullOrEmpty())
            {
                var userAct = IUserActivityService.Find(x => x.ID == userActId);
                if (userAct == null)
                {
                    return(Forbidden());
                }
                model = IKanJiaService.Find(userAct.TargetID);
                //帮砍价人列表
                ViewBag.KanJiaList = IUserActivityService.GetList(x => x.TargetID == userAct.TargetID && !string.IsNullOrEmpty(x.TargetUserID) && x.TargetUserID == userAct.JoinUserID);
                ViewBag.Price      = userAct.Amount;
                ViewBag.JoinUserID = userAct.JoinUserID;
                id = userAct.TargetID;
            }
            else
            {
                var userActModel = IUserActivityService.Find(x => x.TargetID == id && string.IsNullOrEmpty(x.TargetUserID) && x.JoinUserID == LoginUser.ID && x.IsDelete);
                if (userActModel != null)
                {
                    var userAct = IUserActivityService.Find(x => x.ID == userActId);
                    if (userAct == null || userAct.IsDelete)
                    {
                        return(Forbidden());
                    }
                    model = IKanJiaService.Find(userAct.TargetID);
                    //帮砍价人列表
                    ViewBag.KanJiaList = IUserActivityService.GetList(x => x.TargetID == userAct.TargetID && !string.IsNullOrEmpty(x.TargetUserID) && x.TargetUserID == userAct.JoinUserID);
                    ViewBag.Price      = userAct.Amount;
                    ViewBag.JoinUserID = userAct.JoinUserID;
                    id = userActModel.TargetID;
                }
                else
                {
                    model = IKanJiaService.Find(id);
                    //帮砍价人列表
                    ViewBag.KanJiaList = new List <UserActivity>();
                    ViewBag.Price      = model.OldPrice;
                    ViewBag.JoinUserID = "";

                    if (model == null)
                    {
                        return(Forbidden());
                    }
                    model.ClickCount++;
                    IKanJiaService.Update(model);
                }
            }

            ViewBag.IsReport = IUserActivityService.IsExits(x => x.TargetID == id && x.JoinUserID == LoginUser.ID && string.IsNullOrEmpty(x.TargetUserID));
            ViewBag.AppId    = Params.WeixinAppId;
            string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret);

            ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp();
            ViewBag.NonceStr  = WxPayApi.GenerateNonceStr();
            ViewBag.Signature = WxPayApi.GetSignature(Request.Url.ToString().Split('#')[0], cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr);
            // LogHelper.WriteDebug($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm")} appid={ViewBag.AppId},TimeStamp={ViewBag.TimeStamp},NonceStr={ViewBag.NonceStr},Signature={ViewBag.Signature}");
            return(View(model));
        }
コード例 #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string outString = "";
            string yqStr     = "";
            string qst       = "";
            string phoneno   = "";
            bool   isallok   = false;

            double         LoginMaxSecond = 120;
            double         TotalSeconds   = 0;
            string         LoginMD5_key   = "";
            DateTime       ddd            = new DateTime();
            bool           wxdebug        = false;
            EGO_Order_List order;
            OrderEgoBLL    orderBLL = new OrderEgoBLL();
            string         orderno  = "";
            string         fileName = "";

            Json_Response_Base.UploadPic_resultPackage jrb = new Json_Response_Base.UploadPic_resultPackage();


            if (!bool.TryParse(Request["debug"] ?? "", out wxdebug))
            {
                wxdebug = false;
            }
            try
            {
                ResultPacket rp = new ResultPacket();
                Json_Response_Base.resultPackage jrp = new Json_Response_Base.resultPackage();
                switch (Request["action"])
                {
                //收货地址验证码
                case "addressvalidcode":
                    rp                = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], JYH_SMSCode.EnumSMSTradeType.SaveAddress);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //收货地址验证码
                case "loginvalidcode":
                    rp                = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], (int)JYH_SMSCode.EnumSMSTradeType.PhoneLogin, Request["piccode"]);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //收货地址验证码
                case "oauthvalidcode":
                    rp                = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], JYH_SMSCode.EnumSMSTradeType.BindMobileAndMobileReg);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //手机注册验证码
                case "registervalidcode":
                    rp                = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], (int)JYH_SMSCode.EnumSMSTradeType.PhoneRegister, Request["piccode"]);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //重新设置密码
                case "passwordreset":
                    phoneno   = Session["UserName"] == null ? (Request["phoneno"] ?? "") : Session["UserName"].ToString();
                    jrp       = new LoginBLL().ResetPassWord(phoneno, Request["validcode"], Request["password"]);
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //重置密码验证码
                case "resetpasswordvalidcode":
                    phoneno           = Session["UserName"] == null ? (Request["mobileno"] ?? "") : Session["UserName"].ToString();
                    rp                = SMSBll.MakeSMSCodeAndSend(phoneno, (int)JYH_SMSCode.EnumSMSTradeType.PasswordReset, Request["piccode"]);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //手机注册验证码
                case "lqfxtqvalidcode":
                    rp                = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], (int)JYH_SMSCode.EnumSMSTradeType.LQFXTQ, Request["piccode"]);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //用户登录
                case "userlogin":
                    try
                    {
                        jrp       = new LoginBLL().CheckLogin(Request["username"], Request["password"]);
                        outString = JsonHelper.ToJsonString(jrp);

                        if (jrp.resultcode == "1")
                        {
                            try
                            {
                                //保存用户信息至本地
                                new LoginBLL().SyncJYHMemberInfo(Request["password"], "wap");
                            }
                            catch (Exception exd)
                            {
                                //记录异常
                                ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        jrp.resultcode    = "98";
                        jrp.resultmessage = ex.ToString();
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    break;

                //手机登录
                case "phonelogin":
                    jrp = new LoginBLL().CheckPhoneLogin(Request["phoneno"], Request["validcode"]);
                    if (jrp.resultcode == "1")
                    {
                        try
                        {
                            //保存用户信息至本地
                            new LoginBLL().SyncJYHMemberInfo("", "wap");
                        }
                        catch (Exception exd)
                        {
                            //记录异常
                            ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]);
                        }
                    }
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //只使用手机号直接登录,from=web的需要验签,安卓和ios直接登录
                case "phoneloginauto":
                    if (Request["type"] == "web")
                    {
                        try
                        {
                            //测试
                            //jrp = new LoginBLL().CheckPhoneLoginApp(Request["phoneno"]);
                            //outString = JsonHelper.ToJsonString(jrp);



                            //验签
                            if (Request["phoneno"] != null && Request["tt"] != null && Request["mac"] != null)
                            {
                                //判断时间是否自有效期内
                                LoginMaxSecond = INITools.GetIniKeyValue("autologinurl", "LoginMaxSecond") == "" ? 0 : double.Parse(INITools.GetIniKeyValue("autologinurl", "LoginMaxSecond"));    // ConfigurationManager.AppSettings["LoginMaxSecond"] == null ? 120 : double.Parse(ConfigurationManager.AppSettings["LoginMaxSecond"].ToString());

                                qst = Request["tt"];
                                if (qst == "")
                                {
                                    jrp.resultcode    = "99";
                                    jrp.resultmessage = "缺少参数";
                                }
                                else
                                {
                                    TimeSpan ts = DateTime.Now - DateTime.Parse("1970-1-1");
                                    TotalSeconds = ts.TotalSeconds;
                                    TotalSeconds = TotalSeconds - double.Parse(qst);

                                    if (TotalSeconds >= LoginMaxSecond || TotalSeconds < 0)
                                    {
                                        jrp.resultcode    = "99";
                                        jrp.resultmessage = "已失效";
                                    }
                                    else
                                    {
                                        LoginMD5_key = INITools.GetIniKeyValue("autologinurl", "LoginMD5_key") == "" ? "" : INITools.GetIniKeyValue("autologinurl", "LoginMD5_key");
                                        yqStr        = Request["phoneno"] + qst + LoginMD5_key;
                                        //验签通过
                                        if (DESHelper.Md5(yqStr) == Request["mac"].ToString())
                                        {
                                            //判断是否有手机号
                                            if (Request["phoneno"] != "")
                                            {
                                            }
                                            else
                                            {
                                                jrp.resultcode    = "99";
                                                jrp.resultmessage = "缺少手机号";
                                            }
                                        }
                                        else
                                        {
                                            jrp.resultcode    = "99";
                                            jrp.resultmessage = "签名错误";
                                        }
                                    }
                                }
                            }
                            else
                            {
                                jrp.resultcode    = "99";
                                jrp.resultmessage = "缺少参数";
                            }
                        }
                        catch (Exception edf) {
                            jrp.resultcode    = "99";
                            jrp.resultmessage = "程序异常";
                        }

                        if (jrp.resultcode != "99")
                        {
                            //登录
                            jrp = new LoginBLL().CheckPhoneLoginApp(Request["phoneno"]);
                            if (jrp.resultcode == "1")
                            {
                                try
                                {
                                    //保存用户信息至本地
                                    new LoginBLL().SyncJYHMemberInfo("", "wap");
                                }
                                catch (Exception exd)
                                {
                                    //记录异常
                                    ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--web登录--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]);
                                }
                            }

                            outString = JsonHelper.ToJsonString(jrp);
                        }
                        else
                        {
                            //用户注销
                            try
                            {
                                new LoginBLL().UserLoginOut();
                            }
                            catch (Exception sse) {
                            }
                        }
                    }
                    else
                    {
                        jrp = new LoginBLL().CheckPhoneLoginApp(Request["phoneno"]);
                        if (jrp.resultcode == "1")
                        {
                            try
                            {
                                //保存用户信息至本地
                                new LoginBLL().SyncJYHMemberInfo("", "wap");
                            }
                            catch (Exception exd)
                            {
                                //记录异常
                                ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--APP登录--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]);
                            }
                        }
                    }
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //用户注销
                case "userlogout":
                    jrp       = new LoginBLL().UserLoginOut();
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //手机注册
                case "phonereg":
                    jrp       = new LoginBLL().CheckPhoneReg(Request["phoneno"], Request["validcode"], Request["password"]);
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                case "phonereg_lqfxtq":
                    jrp       = new LoginBLL().CheckPhoneReg(Request["phoneno"], Request["validcode"], Request["password"], JYH_SMSCode.EnumSMSTradeType.LQFXTQ, Request["sharephone"]);
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //检测是否登录
                case "checklogin":
                    jrp       = new LoginBLL().CheckLoginSession();
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //手机登录
                case "phoneexist":
                    if (LoginBLL.CheckPhoneExist(Request["phoneno"]))
                    {
                        jrp.resultcode    = "99";
                        jrp.resultmessage = "已存在";
                    }
                    else
                    {
                        jrp.resultcode    = "1";
                        jrp.resultmessage = "不存在";
                    }
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //获取地址列表
                case "addresslist":
                    string addressList = "";
                    rp = new OrderBLL().GetAddressList(out addressList);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = addressList;
                    }
                    break;

                //新增收货地址
                case "addressadd":
                    rp                = new OrderBLL().AddAddressForOrder(Request["api_input"], Request["validcode"]);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //修改收货地址
                case "addressedit":
                    rp                = new OrderBLL().EditAddressForOrder(Request["api_input"], Request["validcode"]);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //根据id获得地址
                case "getaddressbyid":
                    string addressByID = "";
                    rp = new OrderBLL().GetAddressByID(Request["addressid"], out addressByID);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = addressByID;
                        if (outString == "")
                        {
                            jrp.resultcode    = "1000";
                            jrp.resultmessage = "收货地址已删除,请重新设置收货地址";
                            outString         = JsonHelper.ToJsonString(jrp);
                        }
                    }
                    break;

                //获取默认收货地址
                case "addressdefault":
                    string addressDetail = "";
                    rp = new OrderBLL().GetAddressDefault(out addressDetail);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = addressDetail;
                        if (outString == "")
                        {
                            jrp.resultcode    = "1000";
                            jrp.resultmessage = "收货地址已删除,请重新设置收货地址";
                            outString         = JsonHelper.ToJsonString(jrp);
                        }
                    }
                    break;

                case "merchant_check":
                    Merchant_PageBLL checkBll = new Merchant_PageBLL();
                    foreach (string key in Request.Form.Keys)
                    {
                        checkBll._paramList.Add(key, HttpUtility.UrlDecode(Request.Form[key]));
                    }
                    string from = Request["merchantcode"].ToString();
                    if (!string.IsNullOrEmpty(from))
                    {
                        outString = checkBll.NotifyMerchantApiData();
                        if (outString == "-1")
                        {
                            from = "";
                        }
                        else
                        {
                            if (JsonHelper.JsonToObject <Json_Response_Base.resultPackage>(outString).resultcode != "1")
                            {
                                from = "";
                            }
                        }
                    }
                    checkBll.CheckMerchantValid(Request["host"].ToString(), Request["refer"].ToString(), from);
                    if (Session["MerchantID_HJY"] != null)
                    {
                        jrp.resultcode    = "1";
                        jrp.resultmessage = from;
                    }
                    else
                    {
                        jrp.resultcode    = "99";
                        jrp.resultmessage = "已失效";
                    }
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                //获取拼团信息
                case "getpininfo":
                    string pinInfo = "";
                    rp = new PinBLL().GetPinListByEventCode(Request["eid"].ToString(), out pinInfo);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = pinInfo;
                    }
                    break;

                //获取我的团信息
                case "mytuans":
                    string myTuans = "";
                    rp = new PinBLL().GetMyTuans(out myTuans);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = myTuans;
                    }
                    break;

                //获取我的订单
                case "myorders":
                    string myOrders = "";
                    rp = new PinBLL().GetMyOrders(out myOrders);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = myOrders;
                    }
                    break;

                //获取我的订单详情
                case "myorderdetail":
                    string myOrderDetail = "";
                    rp = new PinBLL().GetMyOrderDetail(Request.Form["oid"], out myOrderDetail);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = myOrderDetail;
                    }
                    break;

                //获取活动订单
                case "eventorders":
                    string eventOrders = "";
                    rp = new PinBLL().GetEventOrdersByEventCode(Request.Form["eid"], out eventOrders);
                    if (rp.IsError)
                    {
                        jrp.resultcode    = rp.ResultCode;
                        jrp.resultmessage = rp.Description;
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    else
                    {
                        outString = eventOrders;
                    }
                    break;

                //参加拼团
                case "pin":
                    var num     = int.Parse(Request.Form["num"]);
                    var endTime = DateTime.Parse(Request.Form["endTime"].ToString());
                    rp                = new PinBLL().Pin(num, endTime, Request.Form["json"].ToString());
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //监测是否可以参加拼团
                case "iscanpin":
                    rp                = new PinBLL().IsCanPin(int.Parse(Request.Form["Num"].ToString()), DateTime.Parse(Request.Form["endTime"].ToString()), Request.Form["eventCode"].ToString());
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //更新拼团状态
                case "updatetuanstatus":
                    rp                = new PinBLL().UpdatePinTuanStatus(Request.Form["eventCode"].ToString(), (JYH_Pin_List.EnumTuanStatus)(int.Parse(Request.Form["status"])));
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                //更新支付状态
                case "updatepaystatus":
                    rp                = new PinBLL().UpdatePayStatus(Request.Form["order_code"].ToString(), (JYH_Pin_Detail.EnumPayStatus)(int.Parse(Request.Form["status"])));
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;

                case "wxpay":    //不经过支付网关
                    try
                    {
                        JsApiPay jsApiPay = new JsApiPay(this);
                        jsApiPay.openid    = Session["wxPayOpenid"].ToString(); //"oz1WBs_FPv5qbh1cyyoN9fzNZgUw";
                        jsApiPay.total_fee = (int)(decimal.Parse(Request["total_fee"].ToString()) * 100);
                        jsApiPay.orderid   = Request["orderid"];
                        WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                        outString = jsApiPay.GetJsApiParameters();
                        FileHelper.WriteLogFile(Server.MapPath("log"), "wxOpenid", jsApiPay.openid);
                    }
                    catch (Exception ex)
                    {
                        FileHelper.WriteLogFile(Server.MapPath("log"), "wxOpenid", ex.ToString());
                    }
                    break;

                case "test":
                    rp                = new PinBLL().Request_ApiBySendList(0, 0);
                    jrp.resultcode    = rp.ResultCode;
                    jrp.resultmessage = rp.Description;
                    outString         = JsonHelper.ToJsonString(jrp);
                    break;
                ///*创建订单*/
                //case "createorder":
                //    order = new EGO_Order_List();
                //    order.ProductID = int.Parse(Request["ProductID"]);
                //    order.PeriodNum = int.Parse(Request["PeriodNum"]);
                //    order.OrderNo = RunProcedure.Exec_CreateSerialNo(10001);
                //    order.OrderTime = DateTime.Now;
                //    order.BuyerPhone = HttpContext.Current.Session["UserName"].ToString();
                //    order.ChipinNum =int.Parse(Request["ChipinNum"]);;
                //    order.Status =EGO_Order_List.EnumOrderStatus.Init;
                //    order.TotalMoney =decimal.Parse(Request["TotalMoney"]);
                //    order.PayGate =(EnumPaygate)int.Parse(Request["PayGate"]);
                //    order.PayGateType =(EnumPaygateType)int.Parse(Request["PayGateType"]);
                //    if (orderBLL.Insert(order))
                //    {
                //        outString = order.OrderNo;
                //    }
                //    else {
                //        outString = "";
                //    }
                //    break;
                ///*使用支付网关支付*/
                //case "gotopayment":
                //    //取得支付网关的参数
                //    orderno = Request["OrderNo"] ?? "";
                //    order = OrderBLL.GetOrderInfo(orderno);
                //    if (order.PayGate == EnumPaygate.WeiXin_JSAPI)
                //    {
                //        //微信JSAPI
                //        if (order.OpenID != "")
                //        {
                //            order.OpenID = Session["wxPayOpenid"].ToString();
                //            outString = PaygateBLL.GoToPayMent(order);

                //        }
                //        else {
                //            outString = "";
                //        }
                //    }
                //    else
                //    {
                //        //支付宝
                //        outString = PaygateBLL.GoToPayMent(order);
                //    }
                //    break;
                case "wxshare":    //微信内JSAPI分享
                    WX_JSAPI_Config jaapiconfig = new WX_JSAPI_Config();
                    jaapiconfig.resultcode    = "0";
                    jaapiconfig.resultmessage = "操作成功";
                    string jsApiList = Request["jsApiList"] ?? "";
                    string url       = Request["surl"] ?? "";
                    if (jsApiList == "")
                    {
                        jaapiconfig.resultcode    = "1";
                        jaapiconfig.resultmessage = "要调用的接口不能为空";
                    }

                    else if (url == "")
                    {
                        jaapiconfig.resultcode    = "2";
                        jaapiconfig.resultmessage = "当前页面的url不能为空";
                    }
                    else
                    {
                        WX_JSAPI_Ticket_Response ticket = WxJsApiData.GetJsApiTicket("jsapi");
                        if (ticket == null)
                        {
                            jaapiconfig.resultcode    = "3";
                            jaapiconfig.resultmessage = "获取ticket失败.";
                        }
                        else
                        {
                            jaapiconfig.appId     = WxPayConfig.APPID;
                            jaapiconfig.debug     = wxdebug;
                            jaapiconfig.jsApiList = jsApiList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            jaapiconfig.nonceStr  = WxPayApi.GenerateNonceStr();
                            jaapiconfig.timestamp = WxPayApi.GenerateTimeStamp();
                            jaapiconfig.ticket    = ticket.ticket;
                            jaapiconfig.url       = url;
                            jaapiconfig.signature = WxJsApiData.getSign(jaapiconfig);
                        }
                    }
                    outString = JsonHelper.ToJsonString(jaapiconfig);
                    break;

                    #region   图片*
                /*上传图片*/
                case "uploadimg":


                    //====使用服务器物理路径,可实现上传========================================

                    //获取图片控件
                    string file_ID = Request["fileid"];   //.Split('|');
                    //string return_img_path = "";
                    var file = Request.Files[file_ID];
                    //var file =Request.Files[0];
                    //上传图片文件路径【通过虚拟目录获得对应的物理地址,虚拟目录地址需指向文件服务器的共享路径】
                    string temp_filePath = ConfigurationManager.AppSettings["UploadIMG"];
                    //图片上传物理路径(当前服务器上)
                    string filePath = new System.Web.UI.Page().Server.MapPath(temp_filePath);

                    ////图片上传物理路径(相对于文件服务器的地址)
                    //string filePath = ConfigurationManager.AppSettings["UploadIMG"];

                    int    maxSize = 0;
                    string path    = "";
                    if (file == null)
                    {
                        outString = "{\"resultCode\":\"1\",\"resultMessage\":\"请上传图片信息!\"}";
                    }
                    fileName = file.FileName;
                    string aaa    = Encoding.UTF8.GetString(Encoding.Default.GetBytes(file.FileName));
                    string exName = "";
                    if (Path.GetExtension(aaa) == "")
                    {
                        exName = fileName.Substring(fileName.LastIndexOf('?')).Replace("?", ".");
                    }
                    else
                    {
                        exName = fileName.Substring(fileName.LastIndexOf('.'));
                    }

                    if (exName == "")
                    {
                        exName = "." + fileName.Substring(fileName.Length - 3, 3);
                    }
                    //重命名
                    //int seed = Guid.NewGuid().GetHashCode();
                    //var random = new System.Random(seed);
                    string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "" + RandHelper.Next(100000, 999999);
                    if (Directory.Exists(filePath) == false)
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    path = filePath + "\\" + newFileName + exName;
                    file.SaveAs(path);
                    //图片访问路径
                    string baseurl = "";
                    if (Request["saveFullPath"] != null)
                    {
                        baseurl = ConfigurationManager.AppSettings["UploadIMG_YM"];    //Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port;
                    }
                    jrb.resultmessage = baseurl + ConfigurationManager.AppSettings["UploadIMG_Path"] + newFileName + exName;
                    jrb.resultcode    = "1";
                    outString         = JsonHelper.ToJsonString(jrb);
                    break;
                    #endregion

                case "group_back":
                    if (Session["group_back"] != null)
                    {
                        jrp.resultcode    = "1";
                        jrp.resultmessage = "正常";
                    }
                    else
                    {
                        jrp.resultcode    = "99";
                        jrp.resultmessage = "已失效";
                    }
                    outString = JsonHelper.ToJsonString(jrp);
                    break;

                case "merchant_page":

                    if (Session["MerchantID_HJY"] != null || (!string.IsNullOrEmpty(Request["recordact"])))
                    {
                        Merchant_PageBLL pageBll = new Merchant_PageBLL();
                        foreach (string key in Request.Form.Keys)
                        {
                            pageBll._paramList.Add(key, HttpUtility.UrlDecode(Request.Form[key]));
                        }

                        outString = pageBll.NotifyMerchantApiData();
                        if (outString == "-1")
                        {
                            jrp.resultcode    = "99";
                            jrp.resultmessage = "通知失败";
                            outString         = JsonHelper.ToJsonString(jrp);
                        }
                    }
                    else
                    {
                        if (Request["recordact"].ToString() != "")
                        {
                        }
                        jrp.resultcode    = "98";
                        jrp.resultmessage = "已失效";
                        outString         = JsonHelper.ToJsonString(jrp);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                ProjectLogBLL.NotifyProjectLog(string.Format("异常:{0}", ex.ToString()), "api-" + Request["action"]);
            }
            Response.Write(outString);
        }
コード例 #22
0
        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="id"></param>
        /// <param name="openId"></param>
        /// <param name="mark"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult CheckOut(string code, string orderNo)
        {
            string openid = "";

            if (new AppSetting().IsDebug != null &&
                new AppSetting().IsDebug.ToLower() == "true")
            {
                openid = "123";
            }
            else
            {
                if (Request.Cookies[SystemConfig.WXOpenIDCookieKey] != null)
                {
                    openid = Request.Cookies[SystemConfig.WXOpenIDCookieKey].Value;
                }

                if (string.IsNullOrWhiteSpace(openid) && code == null)
                {
                    Response.Redirect(CommonHelper.GetRedirect("WxClass%2fClassList"));
                }
                try
                {
                    if (string.IsNullOrWhiteSpace(openid))
                    {
                        openid = GetOpenId(code).openid;


                        // 合法用户,允许访问
                        Response.Cookies[SystemConfig.WXOpenIDCookieKey].Value   = openid;
                        Response.Cookies[SystemConfig.WXOpenIDCookieKey].Path    = "/";
                        Response.Cookies[SystemConfig.WXOpenIDCookieKey].Expires = DateTime.Now.AddDays(1);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            try
            {
                AppSetting  setting = new AppSetting();
                WxPayClient client  = new WxPayClient();

                OrderBC bc = new OrderBC();

                var order = bc.GetOrderByOrderNo(orderNo);

                string outTradeNumber = string.Format("{0}{1}", orderNo.ToString(), DateTime.Now.ToString("fff"));



                UnifiedOrderRequest req = new UnifiedOrderRequest();
                req.Body   = "万韬财税课程购买";        //商品描述-----------------------
                req.Attach = openid.ToString(); //附加信息,会原样返回,充值人员微信Openid

                req.GoodTag    = "Pay";
                req.TradeType  = "JSAPI";
                req.OpenId     = openid;
                req.OutTradeNo = outTradeNumber;   //---商户订单号----------------
                req.TotalFee   = 1;                //测试总金额
                //req.TotalFee = Convert.ToInt32(order.PayPrice * 100);//总金额
                req.NotifyUrl = setting.NotifyUrl; //异步通知地址-------------------------
                var resp = client.UnifiedOrder(req);

                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", resp.AppId);
                jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
                jsApiParam.SetValue("package", "prepay_id=" + resp.PrepayId);
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

                bc.UpdatePayInfo(outTradeNumber, jsApiParam.ToJson(), orderNo);

                //--给Viewbag赋值,供前台页面jsapi调用
                ViewBag.AppId     = (string)jsApiParam.GetValue("appId");
                ViewBag.Package   = (string)jsApiParam.GetValue("package");
                ViewBag.NonceStr  = (string)jsApiParam.GetValue("nonceStr");
                ViewBag.Paysign   = (string)jsApiParam.GetValue("paySign");
                ViewBag.TimeStamp = (string)jsApiParam.GetValue("timeStamp");
                ViewBag.OpenId    = openid;
                ViewBag.OrderNo   = orderNo;


                ViewBag.OpenId  = openid;
                ViewBag.OrderNo = orderNo;
            }
            catch (Exception ex)
            {
            }
            return(View());
        }
コード例 #23
0
        private void GetPaySign(HttpContext context)
        {
            //定义统一消息体
            Core.Data.Entity.SystemEntity.MessageModel message = new Core.Data.Entity.SystemEntity.MessageModel();
            //定义请求工具
            HttpGetOrPost httpHelper = new HttpGetOrPost();
            //定义重定向URL
            string redirect_url1 = HttpUtility.UrlEncode("https://www.yuming.com.cn/auth.aspx");
            string redirect_url2 = HttpUtility.UrlEncode("https://www.yuming.com.cn/success.html");

            var jsCode = Q("code", context);

            if (string.IsNullOrEmpty(jsCode))
            {
                message.msg  = "0";
                message.data = "";
                context.Response.Write(JsonConvert.SerializeObject(message));
                return;
            }

            #region 第二步,获取openid
            string url2 = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={WechatJSAPIConfig.appid}&secret={WechatJSAPIConfig.appSecret}&code={jsCode}&grant_type=authorization_code";

            /* 正确的json
             *  {
             *  "access_token":"ACCESS_TOKEN",
             *  "expires_in":7200,
             *  "refresh_token":"REFRESH_TOKEN",
             *  "openid":"OPENID",
             *  "scope":"SCOPE"
             *  }
             */
            string response2 = httpHelper.HttpGet(url2);

            WechatOAuthResponse oauth = JsonConvert.DeserializeObject <WechatOAuthResponse>(response2);
            if (oauth == null || !string.IsNullOrEmpty(oauth.errcode))
            {
                message.msg  = "0";
                message.data = "";
                context.Response.Write(JsonConvert.SerializeObject(message));
            }

            //拿到OPENID
            var openid = oauth.openid;
            context.Session["openid"] = oauth.openid;
            #endregion

            #region 第三步获取access_token
            //注意该access_token与授权access_token不一样
            string url3      = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={WechatJSAPIConfig.appid}&secret={WechatJSAPIConfig.appSecret}";
            string response3 = httpHelper.HttpGet(url3);

            WechatAccessResponse access = JsonConvert.DeserializeObject <WechatAccessResponse>(response3);
            if (access == null || access.errcode != 0)
            {
                message.msg  = "0";
                message.data = "";
                context.Response.Write(JsonConvert.SerializeObject(message));
            }

            //拿到OPENID
            string access_token = access.access_token;
            #endregion

            #region 第四步,获取jsapi_ticket
            string url4 = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi";

            /* 正确的json
             * {
             *  "errcode":0,
             *  "errmsg":"ok",
             *  "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
             *  "expires_in":7200
             * }*/
            string response4 = httpHelper.HttpGet(url4);

            WechatTicketResponse ticket = JsonConvert.DeserializeObject <WechatTicketResponse>(response4);
            if (ticket == null || ticket.errcode != 0)
            {
                message.msg  = "0";
                message.data = "";

                context.Response.Write(JsonConvert.SerializeObject(message));
            }

            //记录ticket
            string jsapi_ticket = ticket.ticket;
            #endregion

            string timestamp = WxPayApi.GenerateTimeStamp();
            string nonceStr  = WxPayApi.GenerateNonceStr();
            context.Session["timestamp"] = timestamp;
            context.Session["nonceStr"]  = nonceStr;

            WxPayData configData = new WxPayData();
            configData.SetValue("jsapi_ticket", jsapi_ticket);
            configData.SetValue("noncestr", nonceStr);
            configData.SetValue("timestamp", timestamp);
            configData.SetValue("url", $"https://www.yuming.com.cn/auth.aspx?code={jsCode}&state=STATE");
            string sha1sign = configData.SHA1Sign();

            var jsBridge = new
            {
                msg       = "200",
                appId     = WechatJSAPIConfig.appid,
                timeStamp = timestamp,
                nonceStr  = nonceStr,
                sha1sign  = sha1sign
            };

            string jsApiData = JsonConvert.SerializeObject(jsBridge);

            context.Response.Write(jsApiData);
        }
コード例 #24
0
        private ActionResult WeiXinPay(Users Users, decimal Amount, PayConfig PayConfig, SysControl SysControl)
        {
            if (Users.Token.IsNullOrEmpty())
            {
                Users.Token = DateTime.Now.ToString().GetMD5();
                Entity.SaveChanges();
            }

            int InType = 0;

            if (SysControl.LagEntryNum > 0)
            {
                InType = 1;
            }

            #region 微信支付
            string PostJson = "{amoney:" + Amount.ToString("F2") + ",token:\"" + Users.Token + "\",payid:\"shop\",otype:8,action:\"Create\",x:\"0\",y:\"0\",intype:\"" + InType + "\",payway:\"" + PayConfig.Id + "\",orderaddress:\"网店收银台,IP:" + Utils.GetAddressAndIp() + "\",ip:\"" + Utils.GetIP() + "\"}";
            //提交数据
            string PostData = LokFuEncode.LokFuAPIEncode(PostJson, Shop_Keys);
            PostData = HttpUtility.UrlEncode(PostData);
            //Post参数
            string PostString = "eno=" + Shop_ENO + "&data=" + PostData + "&code=0000";
            //AppPath = "http://localhost:2610";
            string  url       = AppPath + "/API/OrderQC/";
            string  RetString = Utils.PostRequest(url, PostString, "utf-8");
            JObject json      = new JObject();
            try
            {
                json = (JObject)JsonConvert.DeserializeObject(RetString);
            }
            catch (Exception)
            {
                ViewBag.ErrorMsg = "接口数据有误![01]";
                return(View("Error"));
            }
            if (json == null)
            {
                ViewBag.ErrorMsg = "接口数据有误![02]";
                return(View("Error"));
            }
            string code = "";
            string data = "";
            try
            {
                code = json["code"].ToString();
                data = json["data"].ToString();
            }
            catch (Exception)
            {
                ViewBag.ErrorMsg = "接口数据有误![03]";
                return(View("Error"));
            }
            if (code != "0000")
            {
                ViewBag.ErrorMsg = "交易有误![" + code + "]";
                return(View("Error"));
            }
            //解密
            string  RetData = LokFuEncode.LokFuAPIDecode(data, Shop_Keys);
            JObject Json    = new JObject();
            try
            {
                Json = (JObject)JsonConvert.DeserializeObject(RetData);
            }
            catch (Exception)
            {
                ViewBag.ErrorMsg = "数据解析有误![01]";
                return(View("Error"));
            }
            if (Json == null)
            {
                ViewBag.ErrorMsg = "数据解析有误![02]";
                return(View("Error"));
            }
            Orders Orders = new Orders();
            Orders = JsonToObject.ConvertJsonToModel(Orders, Json);
            if (Orders.PayId.IsNullOrEmpty())
            {
                ViewBag.ErrorMsg = "订单信息有误";
                return(View("Error"));
            }
            string   PayId        = Orders.PayId;
            string[] PayConfigArr = PayConfig.QueryArray.Split(new char[] { ',' });
            if (PayConfig.DllName == "WeiXin")
            {
                string AppId  = PayConfigArr[0];
                string AppKey = PayConfigArr[2];

                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", AppId);
                jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
                jsApiParam.SetValue("package", "prepay_id=" + PayId);
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign(AppKey));
                string Parameters = jsApiParam.ToJson();
                ViewBag.Parameters = Parameters;
                Orders             = Entity.Orders.FirstOrNew(n => n.TNum == Orders.TNum);
                ViewBag.Orders     = Orders;
                return(View("WeiXinPay"));
            }
            else if (PayConfig.DllName == "HFWeiXin")
            {
                //提交结算中心
                string merId      = PayConfigArr[0]; //商户号
                string merKey     = PayConfigArr[1]; //商户密钥
                string orderId    = Orders.TNum;     //商户流水号
                string myData     = "{\"merid\":\"" + merId + "\",\"orderid\":\"" + orderId + "\",\"code\":\"" + PayId + "\"}";
                string DataBase64 = LokFuEncode.Base64Encode(myData, "utf-8");
                string Sign       = (DataBase64 + merKey).GetMD5();
                DataBase64 = HttpUtility.UrlEncode(DataBase64);
                string myUrl = string.Format("req={0}&sign={1}", DataBase64, Sign);
                string Url   = "https://api.zhifujiekou.com/wxjsapi/gopay.html?" + myUrl;
                //Response.Redirect(Url);
                return(this.Redirect(Url));
            }
            else
            {
                return(View("Null"));
            }
            //return View("Null");
            #endregion
        }
コード例 #25
0
        public static addCard GetCardExt(Store store, string userCode)
        {
            LogHelper.WriteLog("GetCardExt start");
            IUserStoreService userStoreService = new UserStoreService();

            var     cardId  = ConfigurationManager.AppSettings["cardId"].ToString();
            addCard addCard = new addCard();

            addCard.cardId = cardId;
            CardExt cardExt = new CardExt();

            LogHelper.WriteLog("store.appid:" + store.appid.Trim());
            LogHelper.WriteLog("store.accessToken:" + store.accessToken);
            LogHelper.WriteLog("store.api_ticket:" + store.api_ticket);
            LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime);
            var userStore = userStoreService.GetUserStorebyUserCodestoreCode(userCode, store.StoreCode);

            if (!string.IsNullOrEmpty(store.accessToken) && !string.IsNullOrEmpty(store.api_ticket) && store.accessTokenCreateTime > DateTime.Now.AddHours(-1))
            {
                var api_ticket = store.api_ticket;
                cardExt.code      = WxPayApi.GenerateNonceStr();
                cardExt.openid    = userStore.OpenID;
                cardExt.nonce_str = WxPayApi.GenerateNonceStr();
                cardExt.timestamp = WxPayApi.GenerateTimeStamp();
                cardExt.signature = GetSignature(api_ticket, cardExt.nonce_str, cardExt.timestamp, cardExt.code, cardExt.openid, cardId);
                LogHelper.WriteLog("api_ticket :" + api_ticket);
                LogHelper.WriteLog("nonce_str :" + cardExt.nonce_str);
                LogHelper.WriteLog("timestamp :" + cardExt.timestamp);
                LogHelper.WriteLog("code :" + cardExt.code);
                LogHelper.WriteLog("openid :" + cardExt.openid);
                LogHelper.WriteLog("cardId :" + cardId);
            }
            else
            {
                var accessToken = wxAccessToken(store.appid.Trim(), store.secret.Trim());
                if (accessToken != null)
                {
                    if (!string.IsNullOrEmpty(accessToken.access_token))
                    {
                        var wt = apiticket(accessToken.access_token);
                        if (wt != null)
                        {
                            if (!string.IsNullOrEmpty(wt?.ticket))
                            {
                                IStoreService _stoeservice = new StoreService();
                                store.accessToken           = accessToken.access_token;
                                store.api_ticket            = wt?.ticket;
                                store.accessTokenCreateTime = DateTime.Now;
                                LogHelper.WriteLog("store.accessToken:" + store.accessToken);
                                LogHelper.WriteLog("store.api_ticket:" + store.api_ticket);
                                LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime);
                                _stoeservice.UpdateStoreaccessToken(store);

                                var api_ticket = store.api_ticket;
                                cardExt.code      = WxPayApi.GenerateNonceStr();
                                cardExt.openid    = userStore.OpenID;
                                cardExt.nonce_str = WxPayApi.GenerateNonceStr();
                                cardExt.timestamp = WxPayApi.GenerateTimeStamp();
                                cardExt.signature = GetSignature(api_ticket, cardExt.nonce_str, cardExt.timestamp, cardExt.code, cardExt.openid, ConfigurationManager.AppSettings["Company"].ToString());
                                LogHelper.WriteLog("api_ticket :" + api_ticket);
                                LogHelper.WriteLog("nonce_str :" + cardExt.nonce_str);
                                LogHelper.WriteLog("timestamp :" + cardExt.timestamp);
                                LogHelper.WriteLog("code :" + cardExt.code);
                                LogHelper.WriteLog("openid :" + cardExt.openid);
                                LogHelper.WriteLog("cardId :" + cardId);
                            }
                            else

                            {
                                return(null);
                            }
                        }
                        else

                        {
                            return(null);
                        }
                    }
                    else

                    {
                        return(null);
                    }
                }
                else

                {
                    return(null);
                }
            }
            addCard.cardExt = cardExt;
            LogHelper.WriteLog("GetCardExt end");
            return(addCard);
        }
コード例 #26
0
        public async Task <ActionResult> WXPay([FromServices] TengoDbContext db
                                               , int outTradeNo = 0, string code = null, int orderId = 0, int isDelaySend = 0)
        {
            //如果outTradeNo参数为空,那么是第一次进来的情况
            if (outTradeNo <= 0)
            {
                #region  商场本身业务逻辑 第一次(也就是从订单点击去支付之后)进来的时候会执行这里
                if (orderId <= 0)
                {
                    return(Redirect("/error"));
                }
                var order = await db.Order.FirstOrDefaultAsync(p => p.Id == orderId);

                if (order == null)
                {
                    return(Redirect("/error"));
                }
                if (order.RealAmount == 0)  //如果支付金额是0元,那么有可能是活动啥的不用付钱,那么状态应该是已经支付了的,直接跳回去看看
                {
                    return(Redirect("/order/detail?id=" + order.Id));
                }
                if (order.PayStatus)
                {
                    return(Redirect("/order/detail?id=" + order.Id));
                }

                #endregion

                #region 构造网页授权获取code的URL,并且重定向跳转到微信的地址
                var host = HttpContext.Request.Host;
                var path = Request.Path;
                //指定获取code之后要跳回来的地址,这里我会加上订单流水号
                var redirect_uri = HttpUtility.UrlEncode("https://" + host + "/payment/WXPay?outTradeNo=" + orderId);
                var data         = new WxPayData();
                data.SetValue("appid", WxPayConfig.APPID);
                data.SetValue("redirect_uri", redirect_uri);
                data.SetValue("response_type", "code");
                data.SetValue("scope", "snsapi_base");
                data.SetValue("state", "STATE" + "#wechat_redirect");
                var url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
                //触发微信返回code码
                return(Redirect(url));//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常

                #endregion
            }
            //重定向回来之后包含了code
            else if (!string.IsNullOrWhiteSpace(code))
            {
                #region GetOpenidAndAccessToken 从Url里面拿取上面第一步重定向之后返回来附带的code,然后进一步获取openid和accessToken,接着再统一下单,获取支付参数

                var model = new WXPay();

                #region  GetOpenidAndAccessTokenFromCode(code); 先通过code构造请求来获取openid和accessToken
                try {
                    //构造获取openid及access_token的url
                    var data = new WxPayData();
                    data.SetValue("appid", WxPayConfig.APPID);
                    data.SetValue("secret", WxPayConfig.APPSECRET);
                    //写入code码,以获取openid和access_token
                    data.SetValue("code", code);
                    data.SetValue("grant_type", "authorization_code");
                    string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();

                    //请求url以获取数据
                    string result = HttpService.Get(url);

                    //LogFactory.GetLogger().Info("WXPay", "GetOpenidAndAccessTokenFromCode响应 : " + result);

                    //保存access_token,用于收货地址获取
                    var jd = JsonMapper.ToObject(result);
                    model.access_token = (string)jd["access_token"];

                    //获取用户openid
                    model.openid = (string)jd["openid"];

                    //LogFactory.GetLogger().Info("WXPay", "获取到的openid : " + model.openid);
                    //LogFactory.GetLogger().Info("WXPay", "获取到的access_token : " + model.access_token);
                }
                catch (Exception ex) {
                    //LogFactory.GetLogger().Error("WXPay", ex, remark: "GetOpenidAndAccessTokenFromCode错误");
                    throw new WxPayException(ex.ToString());
                }
                #endregion

                try {
                    //读取订单信息
                    var order = await db.Order.FirstOrDefaultAsync(p => p.Id == outTradeNo);

                    //注意这里的订单号就要设置为流水号了
                    model.out_trade_no = outTradeNo.ToString();
                    model.total_fee    = Convert.ToInt32(order.RealAmount * 100);

                    #region 调用统一下单,获得下单结果 获取prepay_id
                    //统一下单
                    var data = new WxPayData();

                    #region 处理商品前缀
                    var subject = "Teogn电商商品";
                    #endregion

                    data.SetValue("body", subject);   //商品描述
                    data.SetValue("attach", subject); //附加数据

                    data.SetValue("out_trade_no", model.out_trade_no);
                    data.SetValue("total_fee", model.total_fee);

                    data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
                    data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
                    data.SetValue("goods_tag", "");//订单优惠标记
                    data.SetValue("trade_type", "JSAPI");
                    data.SetValue("openid", model.openid);

                    var unifiedOrderResult = WxPayApi.UnifiedOrder(data);
                    if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("prepay_id") || unifiedOrderResult.GetValue("prepay_id").ToString() == "")
                    {
                        //LogFactory.GetLogger().Info("WXPay", "统一下单报错:UnifiedOrder response error!");
                        throw new WxPayException("UnifiedOrder response error!");
                    }


                    #endregion

                    #region  获取H5调起JS API参数
                    //LogFactory.GetLogger().Info("WXPay", "JsApiPay::GetJsApiParam is processing...");
                    var jsApiParam = new WxPayData();
                    jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
                    jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
                    jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
                    jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                    jsApiParam.SetValue("signType", "MD5");
                    jsApiParam.SetValue("paySign", jsApiParam.MakeSign());
                    model.wxJsApiParam = jsApiParam.ToJson();
                    //LogFactory.GetLogger().Info("WXPay", "wxJsApiParam : " + model.wxJsApiParam);
                    #endregion

                    ViewData.Model = model;
                    return(View());
                }
                catch (Exception exp) {
                    //LogFactory.GetLogger().Error("微信支付异常", exp);
                    return(Redirect("/error?msg=微信支付异常..."));
                }
                #endregion
            }
            else  //异常情况,不用理会
            {
                return(Redirect("/error?msg=支付异常..."));
            }
        }
コード例 #27
0
        public static WxConfig GetWxConfig(Store store, string url)
        {
            LogHelper.WriteLog("GetWxConfig start");
            WxConfig wxConfig = new WxConfig();

            LogHelper.WriteLog("store.appid:" + store.appid.Trim());
            LogHelper.WriteLog("store.accessToken:" + store.accessToken);
            LogHelper.WriteLog("store.jsapi_ticket:" + store.jsapi_ticket);
            LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime);
            if (store.accessToken != null && store.jsapi_ticket != null && store.accessTokenCreateTime > DateTime.Now.AddHours(-1))
            {
                url = url.Split('#')[0];
                var jsapi_ticket = store.jsapi_ticket;
                wxConfig.appId     = store.appid.Trim();
                wxConfig.debug     = true;
                wxConfig.nonceStr  = WxPayApi.GenerateNonceStr();
                wxConfig.timestamp = WxPayApi.GenerateTimeStamp();
                wxConfig.jsApiList = new List <string>();
                wxConfig.signature = signature(jsapi_ticket, wxConfig.nonceStr, wxConfig.timestamp, url);
            }
            else
            {
                var accessToken = wxAccessToken(store.appid.Trim(), store.secret.Trim());
                if (accessToken != null)
                {
                    if (!string.IsNullOrEmpty(accessToken.access_token))
                    {
                        var wt = wxticket(accessToken.access_token);
                        if (wt != null)
                        {
                            if (!string.IsNullOrEmpty(wt?.ticket))
                            {
                                IStoreService _stoeservice = new StoreService();
                                store.accessToken           = accessToken.access_token;
                                store.jsapi_ticket          = wt?.ticket;
                                store.accessTokenCreateTime = DateTime.Now;
                                LogHelper.WriteLog("store.accessToken:" + store.accessToken);
                                LogHelper.WriteLog("store.jsapi_ticket:" + store.jsapi_ticket);
                                LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime);
                                var api_ticketwx = apiticket(accessToken.access_token);
                                store.api_ticket = api_ticketwx?.ticket;
                                LogHelper.WriteLog("store.api_ticket:" + store.api_ticket);
                                _stoeservice.UpdateStoreaccessToken(store);
                                url = url.Split('#')[0];
                                var jsapi_ticket = wt?.ticket;
                                wxConfig.appId     = store.appid.Trim();
                                wxConfig.debug     = true;
                                wxConfig.nonceStr  = WxPayApi.GenerateNonceStr();
                                wxConfig.timestamp = WxPayApi.GenerateTimeStamp();
                                wxConfig.jsApiList = new List <string>();


                                wxConfig.signature = signature(jsapi_ticket, wxConfig.nonceStr, wxConfig.timestamp, url);
                            }
                            else

                            {
                                return(null);
                            }
                        }
                        else

                        {
                            return(null);
                        }
                    }
                    else

                    {
                        return(null);
                    }
                }
                else

                {
                    return(null);
                }
            }
            LogHelper.WriteLog("GetWxConfig end");
            return(wxConfig);
        }
コード例 #28
0
ファイル: bus.cs プロジェクト: sanxianlee/WeChatMiniProgram
        public exterData Sign(string openid, string nickname, string UserHostAddress, string city)
        {
            city = (city == null) ? "" : city;
            var Entrustinfo = this.GetEntrustinfo(openid, WxPayConfig.APPID(city), WxPayConfig.getMCHID(city));
            var wxuser      = this.GetUserInfo(openid, WxPayConfig.APPID(city));
            var wxpay       = new WxPayApi();
            var exdata      = new exterData();

            exdata.appid  = WxPayConfig.APPID(city);
            exdata.mch_id = WxPayConfig.getMCHID(city);

            exdata.contract_code  = WxPayConfig.getCityCode(city) + Convert.ToString(long.Parse("10000") + Entrustinfo.Id) + DateTime.Now.ToString("ssfff");
            exdata.request_serial = Entrustinfo.Id.ToString();
            string display_account = string.Empty;

            if (!string.IsNullOrEmpty(wxuser.Mobile) && wxuser.Mobile.Length == 11)
            {
                display_account = wxuser.Mobile.Substring(0, 3) + "****" + wxuser.Mobile.Substring(7, 4);
            }
            else
            {
                display_account = nickname;
            }
            exdata.contract_display_account = display_account;
            switch (city)
            {
            case "福州市":
                exdata.notify_url = "https://www.cmeeol.com/wechat/FZReceiveSign";
                break;

            case "杭州市":
                exdata.notify_url = "https://wx.hzgolong.com/wechat/HZReceiveSign";
                break;

            case "杭州市2":
                exdata.notify_url = "https://wx.hzgolong.com/wechat/wccReceiveSign";
                break;

            default:
                exdata.notify_url = "https://wx.hzgolong.com/wechat/ReceiveSign";
                break;
            }
            //exdata.notify_url = HttpUtility.UrlEncode(exdata.notify_url);
            exdata.plan_id   = WxPayConfig.getPlanID(city);
            exdata.openid    = openid;
            exdata.timestamp = WxPayApi.GenerateTimeStamp();
            exdata.clientip  = UserHostAddress;
            exdata.deviceid  = "";
            exdata.mobile    = "";
            exdata.email     = "";
            exdata.qq        = "";
            exdata.creid     = "";
            exdata.outerid   = "";
            WxPayData inputObj = new WxPayData(city);

            inputObj.SetValue("appid", WxPayConfig.APPID(city));
            inputObj.SetValue("contract_code", exdata.contract_code);
            inputObj.SetValue("contract_display_account", exdata.contract_display_account);
            inputObj.SetValue("mch_id", exdata.mch_id);
            inputObj.SetValue("notify_url", exdata.notify_url);
            inputObj.SetValue("plan_id", exdata.plan_id);
            inputObj.SetValue("request_serial", exdata.request_serial);
            inputObj.SetValue("timestamp", exdata.timestamp);
            inputObj.SetValue("clientip", exdata.clientip);
            inputObj.SetValue("deviceid", "");
            inputObj.SetValue("mobile", "");
            inputObj.SetValue("email", "");
            inputObj.SetValue("qq", "");
            inputObj.SetValue("openid", openid);
            inputObj.SetValue("creid", "");
            inputObj.SetValue("outerid", "");
            if (wxuser.Mobile == "13588861726")
            {
                Log.Write("luo sign inputObj json:", inputObj.ToJson());
            }
            exdata.sign = inputObj.MakeSign();
            return(exdata);
        }
コード例 #29
0
ファイル: WxPay.cs プロジェクト: dmhai/dxpay
        /// <summary>
        /// 微信支付通道安卓调用方式
        /// </summary>
        /// <param name="appid">应用id</param>
        /// <param name="code">订单编号</param>
        /// <param name="goodsname">商品名称</param>
        /// <param name="price">商品价格</param>
        /// <param name="orderid">订单id</param>
        /// <param name="apptype">风控配置表id</param>
        /// <returns></returns>
        private InnerResponse PayWxAz(int appid, string code, string goodsname, decimal price, int orderid, string ip, int apptype, int infoTimes)
        {
            InnerResponse   inn  = new InnerResponse();
            SelectInterface SeIn = new SelectInterface();

            try
            {
                string wxappidzfjk = "wxappidzfjk" + appid;//组装缓存key值

                SeIn = SelectUserInfo(wxappidzfjk, appid, apptype, infoTimes);
                if (SeIn == null || SeIn.PayId <= 0)
                {
                    inn = inn.ToResponse(ErrorCode.Code106);
                    return(inn);
                }
                if (SeIn.PayId > 0)
                {
                    WxPayConfig       wx  = new WxPayConfig(SeIn.PayId);
                    JMP.BLL.jmp_order bll = new JMP.BLL.jmp_order();
                    if (!UpdateOrde.OrdeUpdateInfo(orderid, SeIn.PayId))
                    {
                        inn = inn.ToResponse(ErrorCode.Code101);
                        return(inn);
                    }
                    if (!JudgeMoney.JudgeMinimum(price, SeIn.minmun))
                    {
                        inn = inn.ToResponse(ErrorCode.Code8990);
                        return(inn);
                    }
                    if (!JudgeMoney.JudgeMaximum(price, SeIn.maximum))
                    {
                        inn = inn.ToResponse(ErrorCode.Code8989);
                        return(inn);
                    }
                    WxPayData data = new WxPayData();
                    data.SetValue("body", goodsname);                                                                                             //商品名称
                    data.SetValue("out_trade_no", code);                                                                                          //我们的订单号
                    data.SetValue("total_fee", (Convert.ToInt32(price * 100)).ToString());                                                        //价格
                    data.SetValue("notify_url", ConfigurationManager.AppSettings["WxTokenUrl"].ToString().Replace("{0}", SeIn.PayId.ToString())); //回调地址
                    data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
                    data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss"));
                    data.SetValue("trade_type", "APP");
                    WxPayData result    = WxPayApi.UnifiedOrder(data, SeIn.PayId);
                    string    noncestr  = WxPayApi.GenerateNonceStr();
                    string    timestamp = WxPayApi.GenerateTimeStamp();
                    WxPayData data1     = new WxPayData();
                    data1.SetValue("appid", wx.APPID);
                    data1.SetValue("noncestr", noncestr);
                    data1.SetValue("package", "Sign=WXPay");
                    data1.SetValue("partnerid", wx.MCHID);
                    data1.SetValue("prepayid", result.GetValue("prepay_id"));
                    data1.SetValue("timestamp", timestamp);
                    string sign  = data1.MakeSign(SeIn.PayId);
                    string wxstr = "{\"appid\":\"" + result.GetValue("appid") + "\",\"partnerid\":\"" + result.GetValue("mch_id") + "\",\"prepayid\":\"" + result.GetValue("prepay_id") + "\",\"pkg\":\"Sign=WXPay\",\"noncestr\":\"" + noncestr + "\",\"timestamp\":\"" + timestamp + "\",\"sign\":\"" + sign + "\",\"PaymentType\":\"5\",\"SubType\":\"1\",\"IsH5\":\"0\"}";
                    // str = "{\"message\":\"成功\",\"result\":100,\"data\":" + wxstr + "}";
                    inn           = inn.ToResponse(ErrorCode.Code100);
                    inn.ExtraData = JMP.TOOL.AesHelper.AesEncrypt(wxstr, ConfigurationManager.AppSettings["encryption"].ToString());
                }
                else
                {
                    PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:支付通道异常", summary: "微信appid支付接口错误信息", channelId: SeIn.PayId);
                    inn = inn.ToResponse(ErrorCode.Code104);
                }
            }
            catch (Exception E)
            {
                PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:" + E.ToString(), summary: "微信appid支付接口错误信息", channelId: SeIn.PayId);
                inn = inn.ToResponse(ErrorCode.Code104);
            }
            return(inn);
        }
コード例 #30
0
 public string GenerateTimeStamp()
 {
     return(WxPayApi.GenerateTimeStamp());
 }