Esempio n. 1
0
    /**
     * 生成扫描支付模式一URL
     * @param productId 商品ID
     * @return 模式一URL
     */
    public string GetPrePayUrl(string productId)
    {
        Log.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;

        Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
        return(url);
    }
Esempio n. 2
0
 /// <summary>
 /// 查询订单的支付结果
 /// </summary>
 /// <param name="orderId">订单编号</param>
 /// <param name="tradeNo">交易流水号</param>
 /// <returns></returns>
 public string Query(string orderId = "", string tradeNo = "")
 {
     try
     {
         var reqData = new WxPayData();
         reqData.SetValue("out_trade_no", orderId);
         reqData.SetValue("transaction_id", tradeNo);
         var queryData = WxPayApi.OrderQuery(reqData);
         var jsonStr   = queryData.ToJson();
         var json      = Newtonsoft.Json.Linq.JObject.Parse(jsonStr);
         jsonStr = JsonHelper.Serialize(json, true);
         return(jsonStr);
     }
     catch (Exception ex)
     {
         return("系统执行时发生异常:" + ex.Message);
     }
 }
        /**
         *
         * 从统一下单成功返回的数据中获取微信浏览器调起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 key = WxPayConfig.KEY)
        {
            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(key));

            string parameters = jsApiParam.ToJson();

            Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return(parameters);
        }
Esempio n. 4
0
        public void WeiXinPay()
        {
            M_Payment payMod = payBll.SelModelByPayNo(PayNo);

            if (string.IsNullOrEmpty(PayNo))
            {
                function.WriteErrMsg("0x53,支付单号或为空");
            }
            else if (payMod == null)
            {
                function.WriteErrMsg("支付单号不存在");
            }
            else if (payMod.Status != (int)M_Payment.PayStatus.NoPay)
            {
                function.WriteErrMsg("0x14,支付单已付过款,不能重复支付");
            }
            else if (payMod.MoneyReal <= 0)
            {
                function.WriteErrMsg("0x56,支付单金额异常");
            }
            string    code      = Request.QueryString["code"];
            string    resultStr = APIHelper.GetWebResult("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appMod.APPID + "&secret=" + appMod.Secret + "&code=" + code + "&grant_type=authorization_code");
            JObject   obj       = (JObject)JsonConvert.DeserializeObject(resultStr);
            WxPayData wxdata    = new WxPayData(appMod.Pay_Key);

            wxdata.SetValue("out_trade_no", payMod.PayNo);
            wxdata.SetValue("body", string.IsNullOrEmpty(payMod.Remark) ? "微信支付" : payMod.Remark);
            wxdata.SetValue("total_fee", (int)(payMod.MoneyReal * 100));//(int)(payMod.MoneyReal * 100)
            wxdata.SetValue("trade_type", "JSAPI");
            wxdata.SetValue("notify_url", notifyUrl);
            wxdata.SetValue("product_id", "123");                //必填
            wxdata.SetValue("openid", obj["openid"].ToString()); //公众号支付必填
            wxdata.SetValue("nonce_str", WxAPI.nonce);
            //获取预支付单号

            WxPayData result = WxPayApi.UnifiedOrder(wxdata, appMod);

            if (result.GetValue("return_code").ToString().Equals("FAIL"))
            {
                function.WriteErrMsg("商户" + result.GetValue("return_msg"));
            }
            prepay_id = result.GetValue("prepay_id").ToString();
            payBll.UpdatePlat(payMod.PaymentID, M_PayPlat.Plat.WXPay, appMod.ID.ToString());
        }
Esempio n. 5
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());
        }
Esempio n. 6
0
        /**
         * 生成直接支付url,支付url有效期为2小时,模式二
         * @param productId 商品ID
         * @return 模式二URL
         */
        public string GetPayUrl(string productId)
        {
            WxPayData data = new WxPayData();

            data.SetValue("body", "广东雅达电子股份有限公司");                                                //商品描述
            data.SetValue("attach", "附加信息,用于后台或者存入数据库,做自己的判断");                                   //附加数据
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());                         //随机字符串
            data.SetValue("total_fee", 1);                                                        //总金额
            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", "NATIVE");                                                //交易类型
            data.SetValue("product_id", productId);                                               //商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);                                       //调用统一下单接口
            string    url    = result.GetValue("code_url").ToString();                            //获得统一下单接口返回的二维码链接

            return(url);
        }
Esempio n. 7
0
        // GET: Mob/Home
        public async Task <ActionResult> Index(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                MemberHelper memberHelper = new MemberHelper();
                await memberHelper.SetMemberReferee(id);
            }

            //if (string.IsNullOrEmpty(_Member.Phone))
            //{
            //    return Redirect("/Mob/Home/Bind");
            //}

            WxPayData data = await WxPayApi.GetJSSDKConfig();

            ViewBag.WxConfig = data == null ? "" : SerializationHelper.ToJson(data.GetValues());

            return(View());
        }
Esempio n. 8
0
        public JsonResult WxPay(string money, string tradetitle = "订单支付")
        {
            var result = new ReturnMessage(false)
            {
                Message = "订单支付失败!"
            };

            try
            {
                if (string.IsNullOrWhiteSpace(money))
                {
                    result.Message = "请输入金额";
                    return(Json(result));
                }
                if (LoginUser == null)
                {
                    result.Message = "获取当前用户信息失败";
                    return(Json(result));
                }
                var      openid   = LoginUser.OpenId;
                JsApiPay jsApiPay = new JsApiPay(this);
                jsApiPay.openid    = openid;
                jsApiPay.total_fee = (int)(Converter.ParseDecimal(money) * 100);//Converter.ParseDecimal(money, 0) * 100;//单位为分 所以在此*100
                //JSAPI支付预处理
                var tradeNo = WxPayApi.GenerateOutTradeNo();
                Log.Debug(this.GetType().Name, "用户订单支付!openid:" + LoginUser.OpenId);
                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(tradeNo, "订单支付", "订单支付", openid, jsApiPay.total_fee, "ticket");
                WriteDebug("aaa");
                var appid = unifiedOrderResult.GetValue("appid").ToString();
                WriteDebug("bbb" + appid);
                var prepayid = unifiedOrderResult.GetValue("prepay_id").ToString();
                var param    = jsApiPay.GetJsApiParameters(appid, prepayid);
                result.IsSuccess          = true;
                result.Message            = "支付成功!";
                result.ResultData["data"] = new { tradeNo = tradeNo, param = param };
            }
            catch (Exception ex)
            {
                ex.Data["Method"] = "PurseController>>WxPay";
                new ExceptionHelper().LogException(ex);
            }
            return(Json(result));
        }
Esempio n. 9
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);
        }
Esempio n. 10
0
        public WxPayData getToken(string contract_id, string city, string qrcode_hashs, int token_count = 1)
        {
            string    url  = "https://api.mch.weixin.qq.com/transit/gettoken";
            WxPayData data = new WxPayData();

            data.SetValue("appid", WxPayConfig.APPID(city));
            data.SetValue("mch_id", WxPayConfig.getMCHID(city));
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("contract_id", contract_id);
            data.SetValue("sign_type", "HMAC-SHA256");
            data.SetValue("sign", data.MakeSign_SHA256());
            data.SetValue("token_count", token_count);
            data.SetValue("qrcode_hashs", qrcode_hashs);
            string    xml = HttpService.Post(data.ToXml(), url, false, 10);
            WxPayData res = new WxPayData();

            res.FromXml(xml);
            return(res);
        }
Esempio n. 11
0
        private WxPayData UnifiedOrder(string openId, string productId)
        {
            //统一下单
            WxPayData req = new WxPayData();

            req.SetValue("body", "test");
            req.SetValue("attach", "test");
            req.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
            req.SetValue("total_fee", 1);
            req.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            req.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            req.SetValue("goods_tag", "test");
            req.SetValue("trade_type", "NATIVE");
            req.SetValue("openid", openId);
            req.SetValue("product_id", productId);
            WxPayData result = WxPayApi.UnifiedOrder(req);

            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// 申请退款
        /// </summary>
        /// <returns></returns>
        public WxPayData GetRefundOrderResult()
        {
            WxPayData data = new WxPayData();

            data.SetValue("out_trade_no", order_no);       //商户订单号
            data.SetValue("out_refund_no", out_refund_no); //商户退款单号
            data.SetValue("total_fee", total_fee);
            data.SetValue("refund_fee", refund_fee);
            data.SetValue("op_user_id", op_user_id);

            WxPayData result = WxPayApi.Refund(data);

            if (!result.IsSet("return_code") || result.GetValue("return_code").ToString() != "SUCCESS")
            {
                Log.Error(this.GetType().ToString(), "RefundOrder response error!");
                throw new WxPayException("RefundOrder response error!");
            }
            return(result);
        }
Esempio n. 13
0
        public (Stream, string) NativeCreateOrder(string openId, IOrderBase order, string notifyUrl)
        {
            NativePay nativePay  = new NativePay();
            var       outTradeNo = WxPayApi.GenerateOutTradeNo();

            var orderDict = new Dictionary <string, string>();

            orderDict.Add("fee", order.Fee.ToString());
            orderDict.Add("name", order.Name);
            orderDict.Add("notify_url", notifyUrl);
            orderDict.Add("tag", order.Tag ?? String.Empty);
            orderDict.Add("desc", order.Desc ?? String.Empty);
            orderDict.Add("out_trade_no", outTradeNo);
            orderDict.Add("productId", order.Id.ToString());

            var payUrl = nativePay.GetPayUrl(orderDict);

            return(MakeQRCode(payUrl), outTradeNo);
        }
Esempio n. 14
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));
        }
        public Order WxPayNoMoneyOrder(string productCode, string userCode, string peopleCount, DateTime dateTime, decimal money, string orderCode = "", string couponCode = "")
        {
            IProductInfoService _productInfoService = new ProductInfoService();
            DateTime            now = DateTime.Now;

            IOrderService     _orderService     = new OrderService();
            IUserStoreService _userStoreService = new UserStoreService();


            var   userSotre = _userStoreService.GetUserStorebyUserCode(userCode);
            var   tempOrder = _orderService.GetOrderByCode(orderCode);
            Order order     = new Order();

            if (tempOrder != null && tempOrder.UserCode == userCode)
            {
                order.CreateTime = tempOrder.CreateTime;
                order.OrderCode  = tempOrder.OrderCode;
                order.OrderNO    = tempOrder.OrderNO;
            }
            else
            {
                order.OrderCode  = Guid.NewGuid().ToString();
                order.OrderNO    = WxPayApi.GenerateOutTradeNo().ToString();
                order.CreateTime = now;
            }
            order.Money = money;
            int ss = 0;

            if (int.TryParse(peopleCount, out ss))
            {
                order.Number = ss;
            }
            order.PayTime               = DateTime.Now;
            order.StoreCode             = userSotre.MembershipCardStore;
            order.UserCode              = userCode;
            order.ProductCode           = productCode;
            order.ExperienceVoucherCode = couponCode;
            order.AppointmentTime       = dateTime;
            LogHelper.WriteLog("订单编码OrderCode " + order.OrderCode);
            LogHelper.WriteLog("订单号OrderNO " + order.OrderNO);
            _orderService.InsertOrder(order);
            return(order);
        }
Esempio n. 16
0
        public static bool WxPayRefundRequest(string trade_no, int total_fee, string out_refund_no, out string response)
        {
            response = string.Empty;
            if (string.IsNullOrEmpty(out_refund_no))
            {
                out_refund_no = WxPayApi.GenerateOutTradeNo();
            }
            string    url       = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            string    wx_appid  = PaymentConfig.WeiXinConfig.MobileAppID;
            string    wx_mch_id = PaymentConfig.WeiXinConfig.MobileMCHID;
            WxPayData data      = new WxPayData();

            data.SetValue("out_trade_no", trade_no);
            data.SetValue("total_fee", total_fee);                                  //订单总金额
            data.SetValue("refund_fee", total_fee);                                 //退款金额
            data.SetValue("out_refund_no", out_refund_no);                          //随机生成商户退款单号
            data.SetValue("op_user_id", wx_mch_id);                                 //操作员,默认为商户号
            data.SetValue("appid", wx_appid);                                       //公众账号ID
            data.SetValue("mch_id", wx_mch_id);                                     //商户号
            data.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串
            data.SetValue("sign", data.MakeAPPSign());                              //签名

            string xml = data.ToXml();

            response = HttpService.Post(xml, url, true, 6, SSLCERT_PATH: PaymentConfig.WeiXinConfig.MobileSSLCERT_PATH, SSLCERT_PASSWORD: PaymentConfig.WeiXinConfig.MobileSSLCERT_PASSWORD);//调用HTTP通信接口提交数据到API
            WxPayData result = new WxPayData();

            result.FromXml(response);
            if (result.IsSet("return_code"))
            {
                if (result.GetValue("return_code").ToString().Equals("SUCCESS"))
                {
                    return(true);
                }
                return(false);
            }
            else
            {
                response = result.GetValue("return_msg").ToString();
            }
            return(false);
        }
Esempio n. 17
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>");
        }
Esempio n. 18
0
        public ActionResult wxPay(string total_fee, string sb)
        {
            string guid = Request["userId"];
            var    user = Common.CacheHelper.Get(guid) as PersonalUser;

            if (user == null)
            {
                return(Json(new { success = "false", str = "您还没登陆,请先登陆后操作!" }, JsonRequestBehavior.AllowGet));
            }
            string xml      = null;
            string trade_no = WxPayApi.GenerateOutTradeNo();

            try
            {
                xml = new WXPay()
                {
                    body         = "爽赞网(爽币)充值",                           //费用名称,这会显示
                    detail       = "爽赞网",                                 //微信名称
                    attach       = string.Format("{0},{1}", user.Id, sb), //自定义数据,这里给充值数量和用户ID
                    out_trade_no = trade_no,                              //商户订单号
                    total_fee    = int.Parse(total_fee) * 100
                                                                          // total_fee=1  用户测试数据
                }.pay();
                if (xml.IsNullOrEmpty())
                {
                    return(Json(new { success = "false", str = "微信下单超时失败!" }, JsonRequestBehavior.AllowGet));
                }

                XElement xe = XElement.Parse(xml);
                if (xe.Element("code_url") == null)
                {
                    LogHelper.WriteLog(xml);
                    return(Json(new { success = "false", str = "微信统一下单失败!" }, JsonRequestBehavior.AllowGet));
                }
                return(Json(new { success = "true", trade_no = trade_no, url = xe.Element("code_url").Value }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(xml + "\r\n" + e.ToString());
                return(Json(new { success = "false", str = "微信下单失败!" }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 19
0
        /***
         * 申请退款完整业务流程逻辑
         * @param transaction_id 微信订单号(优先使用)
         * @param out_trade_no 商户订单号
         * @param total_fee 订单总金额
         * @param refund_fee 退款金额
         * @return 退款结果(xml格式)
         */
        public static async Task <string> Run(string transactionId, string outTradeNo, int totalFee, int refundFee, string outRefundNo)
        {
            var data = new WxPayData();

            if (!string.IsNullOrEmpty(transactionId)) //微信订单号存在的条件下,则已微信订单号为准
            {
                data.SetValue("transaction_id", transactionId);
            }
            else //微信订单号不存在,才根据商户订单号去退款
            {
                data.SetValue("out_trade_no", outTradeNo);
            }
            data.SetValue("total_fee", totalFee);           //订单总金额
            data.SetValue("refund_fee", refundFee);         //退款金额
            data.SetValue("out_refund_no", outRefundNo);    //随机生成商户退款单号
            data.SetValue("op_user_id", WxPayConfig.MCHID); //操作员,默认为商户号
            var result = await WxPayApi.Refund(data);       //提交退款申请给API,接收返回数据

            return(result.ToJson());
        }
Esempio n. 20
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()));
        }
Esempio n. 21
0
        /**
         * 生成直接支付url,支付url有效期为2小时,模式二
         * @param productId 商品ID
         * @return 模式二URL
         */
        public WxPayData GetPayUrl(Flw_Order order, decimal amount, string subject)
        {
            WxPayData data = new WxPayData();

            data.SetValue("body", subject);                                                       //商品描述
            data.SetValue("attach", order.Note);                                                  //附加数据
            data.SetValue("out_trade_no", order.OrderID);                                         //订单号
            //data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//订单号
            data.SetValue("total_fee", Convert.ToInt32(amount * 100));                            //总金额,单位:分
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                 //交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
            data.SetValue("goods_tag", order.ID.ToString());                                      //商品标记
            data.SetValue("trade_type", "NATIVE");                                                //交易类型
            data.SetValue("product_id", order.OrderID);                                           //商品ID,商户自定义

            WxPayData result = WxPayApi.UnifiedOrder(data);                                       //调用统一下单接口

            //qr_url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
            return(result);
        }
Esempio n. 22
0
        public string GeneratePrepayId()
        {
            //统一下单
            WxPayData data = new WxPayData();

            data.SetValue("body", "test");
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
            data.SetValue("total_fee", total_fee);
            data.SetValue("trade_type", "APP");

            WxPayData result = WxPayApi.UnifiedOrder(data);

            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                throw new WxPayException("UnifiedOrder response error!");
            }

            return(result.GetValue("prepay_id").ToString());
        }
Esempio n. 23
0
        public int InsertTopupOrder(string userCode, string prepayid, string typeCode, decimal?money = 0)
        {
            DynamicParameters paras = new DynamicParameters();

            paras.Add("@TopupOrderCode", Guid.NewGuid().ToString(), System.Data.DbType.String);
            paras.Add("@UserCode", userCode, System.Data.DbType.String);
            paras.Add("@RecordsOfConsumptionCode", Guid.NewGuid().ToString(), System.Data.DbType.String);
            paras.Add("@WallePrCode", prepayid, System.Data.DbType.String);
            paras.Add("@OutTradeNo", WxPayApi.GenerateOutTradeNo().ToString(), System.Data.DbType.String);
            paras.Add("@PayDatetime", null, System.Data.DbType.DateTime);
            paras.Add("@RechargeTypeCode", typeCode, System.Data.DbType.String);
            paras.Add("@RecordsMoney", money, System.Data.DbType.String);
            paras.Add("@CreateTime", null, System.Data.DbType.DateTime);
            string sql = @"insert into [dbo].[TopupOrder](TopupOrderCode,UserCode,RecordsOfConsumptionCode,
                    WallePrCode,OutTradeNo,PayDatetime,RechargeTypeCode,RecordsMoney,CreateTime)
                    values(@TopupOrderCode,@UserCode,@RecordsOfConsumptionCode,@WallePrCode,
                    @OutTradeNo,@PayDatetime,@RechargeTypeCode,@RecordsMoney,@CreateTime)";

            return(DapperSqlHelper.ExcuteNonQuery <Order>(sql, paras, false));
        }
Esempio n. 24
0
        /***
         * 订单查询完整业务流程逻辑
         * @param transaction_id 微信订单号(优先使用)
         * @param out_trade_no 商户订单号
         * @return 订单查询结果(xml格式)
         */
        public static string Run(string transaction_id, string out_trade_no)
        {
            Log.Info("OrderQuery", "OrderQuery is processing...");

            WxPayData data = new WxPayData();

            if (!string.IsNullOrEmpty(transaction_id))//如果微信订单号存在,则以微信订单号为准
            {
                data.SetValue("transaction_id", transaction_id);
            }
            else//微信订单号不存在,才根据商户订单号去查单
            {
                data.SetValue("out_trade_no", out_trade_no);
            }

            WxPayData result = WxPayApi.OrderQuery(data);//提交订单查询请求给API,接收返回数据

            Log.Info("OrderQuery", "OrderQuery process complete, result : " + result.ToXml());
            return(result.ToPrintStr());
        }
Esempio n. 25
0
        private void Pay_Click(object sender, RoutedEventArgs e)
        {
            NativePay nativePay = new NativePay();
            //生成扫码支付模式二url
            //string tmp = priceTB.Text.Trim();
            //double price = 0.01;
            //double.TryParse(tmp, out price);

            int totalFee = 1;

            string out_trade_no = WxPayApi.GenerateOutTradeNo();

            WxPayData data = new WxPayData();

            data.SetValue("body", "张裕DIY流程演示用");                                                  //商品描述
            data.SetValue("attach", "张裕DIY流程演示用");                                                //附加数据
            data.SetValue("out_trade_no", out_trade_no);                                          //随机字符串
            data.SetValue("total_fee", totalFee);                                                 //总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                 //交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
            data.SetValue("goods_tag", "jjj");                                                    //商品标记
            data.SetValue("trade_type", "NATIVE");                                                //交易类型
            data.SetValue("product_id", "123456789");                                             //商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);                                       //调用统一下单接口
            string    url    = result.GetValue("code_url").ToString();                            //获得统一下单接口返回的二维码链接



            //string url2 = nativePay.GetPayUrl("123456789", totalFee);

            //string ss = HttpUtility.UrlEncode(url2);

            //CreateQrCode(url2);

            QrCodeDisplay dis = new WeChatDemo.QrCodeDisplay(out_trade_no);

            dis.Owner = this;
            dis.SetQR(url);
            dis.Show();
        }
Esempio n. 26
0
        }                                               //H5调起JS API参数
        protected void Page_Load(object sender, EventArgs e)
        {
            Log.Info(this.GetType().ToString(), "page load");
            if (!IsPostBack)
            {
                string openid    = "oN3xdxP75aDqm6WMHCwNgmR1OLCk";
                string total_fee = "1";
                //检测是否给当前页面传递了相关参数
                if (string.IsNullOrEmpty(openid) || string.IsNullOrEmpty(total_fee))
                {
                    Response.Write("<span style='color:#FF0000;font-size:20px'>" + "页面传参出错,请返回重试" + "</span>");
                    Log.Error(this.GetType().ToString(), "This page have not get params, cannot be inited, exit...");
                    //submit.Visible = false;
                    return;
                }

                //若传递了相关参数,则调统一下单接口,获得后续相关接口的入口参数
                JsApiPay jsApiPay = new JsApiPay(this);
                jsApiPay.openid    = openid;
                jsApiPay.total_fee = int.Parse(total_fee);

                //JSAPI支付预处理
                try
                {
                    var       company            = WebUtil.GetCompany(this.Context);
                    string    body               = company != null ? company.CompanyName : ConfigurationManager.AppSettings["CompanyName"];
                    string    tradeno            = WxPayApi.GenerateOutTradeNo();
                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(body, tradeno);
                    wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数
                    Log.Debug(this.GetType().ToString(), "wxJsApiParam : " + wxJsApiParam);
                    //在页面上显示订单信息
                    result.InnerHtml  = "<span style='color:#00CD00;font-size:20px'>订单详情:</span><br/>";
                    result.InnerHtml += "<span style='color:#00CD00;font-size:20px'>" + unifiedOrderResult.ToPrintStr() + "</span>";
                }
                catch (Exception ex)
                {
                    Response.Write("<span style='color:#FF0000;font-size:20px'>" + "下单失败,请返回重试" + "</span>");
                    //submit.Visible = false;
                }
            }
        }
Esempio n. 27
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));
        }
Esempio n. 28
0
        /// <summary>
        /// 统一下单,返回下单结果
        /// </summary>
        /// <returns></returns>
        public RequestResult GetUnifiedOrderResult(UnifiedPayData payData)
        {
            #region
            RequestResult result = new RequestResult
            {
                retCode = ReqResultCode.failed,
                retMsg  = ""
            };
            if (payData == null)
            {
                result.retMsg = "请求参数不能为空";
            }
            //统一下单
            WxPayData data = new WxPayData();
            data.SetValue("body", payData.body ?? string.Empty);
            data.SetValue("attach", payData.attach ?? string.Empty);
            data.SetValue("out_trade_no", payData.out_trade_no ?? string.Empty);
            data.SetValue("total_fee", payData.total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", payData.goods_tag ?? string.Empty);
            data.SetValue("trade_type", payData.trade_type ?? "JSAPI");
            data.SetValue("openid", payData.openid ?? string.Empty);

            WxPayData ret = WxPayApi.UnifiedOrder(data);
            if (!ret.IsSet("appid") || !ret.IsSet("prepay_id") || ret.GetValue("prepay_id").ToString() == "")
            {
                Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                throw new WxPayException("UnifiedOrder response error!");
            }
            else
            {
                result.retCode    = ReqResultCode.success;
                result.retMsg     = "请求成功";
                result.objectData = ret;//把结果返回到业务层
            }

            return(result);

            #endregion
        }
Esempio n. 29
0
        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();
        }
Esempio n. 30
0
        public ActionResult SubmitRefundApply(string OrderID, string Remark, decimal?Amount)
        {
            string RefundNo   = WxPayApi.GenerateOutTradeNo();
            var    resultData = new RefundService().AddRefundApply(OrderID, RefundNo, SessionTools.UserID, Remark, Amount);

            if (resultData != null && resultData.status > 0)
            {
                // 修改订单状态为退款中
                var resultOrderStatus = new RecordService().RefundOrder(OrderID);
                // 退款申请提交成功后,(修改订单状态为退款中),向管理员发送退款申请验证码
                // 消息携带链接:/User/ValidateRefund?OrderID=&TelePhone=&CodeStr=
                // 管理员点击退款申请信息后,跳转至link,验证通过,管理员输入允许的退款金额
                // 然后调用 POST - /User/RefundAmount 进行退款
                // 退款成功后,修改订单状态、退款单状态、使用券状态
                if (resultOrderStatus != null && resultOrderStatus.status > 0)
                {
                    this.SendCode(OrderID, (int)Code_Type.Refund);
                }
            }
            return(Content(JsonHelper.SerializeObject(resultData)));
        }