Exemplo n.º 1
0
        public override void ProcessNotify()
        {
            WxPayData notifyData = GetNotifyData();

            //检查openid和product_id是否返回
            if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "回调数据异常");
                Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            //调统一下单接口,获得下单结果
            string openid = notifyData.GetValue("openid").ToString();
            string product_id = notifyData.GetValue("product_id").ToString();
            WxPayData unifiedOrderResult = new WxPayData();
            try
            {
                unifiedOrderResult = UnifiedOrder(openid, product_id);
            }
            catch(Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "统一下单失败");
                Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            //若下单失败,则立即返回结果给微信支付后台
            if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "统一下单失败");
                Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            //统一下单成功,则返回成功结果给微信支付后台
            WxPayData data = new WxPayData();
            data.SetValue("return_code", "SUCCESS");
            data.SetValue("return_msg", "OK");
            data.SetValue("appid", Config.APPID);
            data.SetValue("mch_id", Config.MCHID);
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id"));
            data.SetValue("result_code", "SUCCESS");
            data.SetValue("err_code_des", "OK");
            data.SetValue("sign", data.MakeSign());

            Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
            page.Response.Write(data.ToXml());
            page.Response.End();
        }
Exemplo n.º 2
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", Config.APPID);//公众帐号id
            data.SetValue("mch_id", Config.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;
        }
Exemplo n.º 3
0
        /// <summary>
        /// 获取审核结果
        /// </summary>
        /// <param name="business_code"></param>
        /// <returns></returns>
        public static string Getstate(string business_code)

        {
            WxPayData inputObj = new WxPayData();

            inputObj.SetValue("version", "1.0");                             //接口版本号
            inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID()); //商户号
            inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr());     //随机字符串
            inputObj.SetValue("business_code", business_code);               //

            inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256); //签名类型
            inputObj.SetValue("sign", inputObj.MakeSign());                  //签名

            string xml     = inputObj.ToXml();
            string url     = "https://api.mch.weixin.qq.com/applyment/micro/getstate";
            int    timeOut = 10;

            Log.Debug("申请入驻", "request : " + xml);
            string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口以提交数据到API

            Log.Debug("申请入驻", "response : " + response);

            return(response);
        }
        public string GetPayUrl(Order order, string ip)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            WxPayData data = new WxPayData();

            data.SetValue("appid", WxPayConfig.APPID);
            data.SetValue("mch_id", WxPayConfig.MCHID);
            // data.SetValue("device_info", "iphone4s");
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("body", "好油菜充值");                                                       //商品描述
            data.SetValue("detail", "好油菜充值");                                                     //商品描述
            data.SetValue("attach", "北京好油菜");                                                     //附加数据
            data.SetValue("out_trade_no", order.TradeNumber);                                     //随机字符串
            // data.SetValue("total_fee", Convert.ToInt32(order.OrderTotal * 100));//总金额
            data.SetValue("total_fee", (int)order.Amount * 100);                                  //总金额
            // data.SetValue("spbill_create_ip",ip);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                 //交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss")); //交易结束时间
            data.SetValue("goods_tag", "好油菜充值");                                                  //商品标记
            data.SetValue("notify_url", "http://www.yoursite.com/Checkout/ResultNotify");         //通知地址
            data.SetValue("trade_type", "NATIVE");                                                //交易类型
            data.SetValue("product_id", 121);                                                     //商品ID
            data.SetValue("sign", data.MakeSign());                                               //签名
            //Logger.Info("获得签名" + data.GetValue("sign"));

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

            //Logger.Info("pay url:" + url);
            return(url);
        }
Exemplo n.º 5
0
    /**
     *
     * 查询订单
     * @param WxPayData inputObj 提交给查询订单API的参数
     * @param int timeOut 超时时间
     * @throws WxPayException
     * @return 成功时返回订单查询结果,其他抛异常
     */
    public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 6)
    {
        string url = "https://api.mch.weixin.qq.com/pay/orderquery";

        //检测必填参数
        if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
        {
            throw new WxPayException("订单查询接口中,out_trade_no、transaction_id至少填一个!");
        }

        inputObj.SetValue("appid", WxPayConfig.APPID);               //公众账号ID
        inputObj.SetValue("mch_id", WxPayConfig.MCHID);              //商户号
        inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串
        inputObj.SetValue("sign", inputObj.MakeSign());              //签名

        string xml = inputObj.ToXml();

        var start = DateTime.Now;

        Log.Debug("WxPayApi", "OrderQuery request : " + xml);
        string response = HttpService.Post(xml, url, false, timeOut);    //调用HTTP通信接口提交数据

        Log.Debug("WxPayApi", "OrderQuery response : " + response);

        var end      = DateTime.Now;
        int timeCost = (int)((end - start).TotalMilliseconds);    //获得接口耗时

        //将xml格式的数据转化为对象以返回
        WxPayData result = new WxPayData();

        result.FromXml(response);

        ReportCostTime(url, timeCost, result);    //测速上报

        return(result);
    }
Exemplo n.º 6
0
        private PrepayInfoModel PreparePrepayInfo(string prepayId, int orderId)
        {
            var payData = new WxPayData(_WeixinPaymentSetting.MchKey);

            payData.SetValue("appId", _WeixinPaymentSetting.AppId);
            payData.SetValue("timeStamp", WxPayData.GenerateTimeStamp());
            payData.SetValue("nonceStr", WxPayData.GenerateNonceStr());
            payData.SetValue("package", $"prepay_id={prepayId}");
            payData.SetValue("signType", "MD5");
            payData.SetValue("paySign", payData.MakeSign());
            var model = new PrepayInfoModel()
            {
                AppId     = payData.GetValue("appId"),
                TimeStamp = payData.GetValue("timeStamp"),
                NonceStr  = payData.GetValue("nonceStr"),
                Package   = payData.GetValue("package"),
                SignType  = payData.GetValue("signType"),
                PaySign   = payData.GetValue("paySign"),
                PrepayId  = prepayId,
                OrderId   = orderId,
            };

            return(model);
        }
Exemplo n.º 7
0
        /**
         * 下载对账单
         * @param WxPayData inputObj 提交给下载对账单API的参数
         * @param int timeOut 接口超时时间
         * @throws WxPayException
         * @return 成功时返回,其他抛异常
         */
        public static WxPayData DownloadBill(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/downloadbill";

            //检测必填参数
            if (!inputObj.IsSet("bill_date"))
            {
                throw new WxPayException("对账单接口中,缺少必填参数bill_date!");
            }

            inputObj.SetValue("appid", WxPayConfig.APPID);      //公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);     //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign());     //签名

            string xml = inputObj.ToXml();

            //Log.Debug("WxPayApi", "DownloadBill request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API
            //Log.Debug("WxPayApi", "DownloadBill result : " + response);

            WxPayData result = new WxPayData();

            //若接口调用失败会返回xml格式的结果
            if (response.Substring(0, 5) == "<xml>")
            {
                result.FromXml(response);
            }
            //接口调用成功则返回非xml格式的数据
            else
            {
                result.SetValue("result", response);
            }

            return(result);
        }
Exemplo n.º 8
0
        //private ILogger _logger;
        //public UnifiedOrderResponse UnifiedOrder(UnifiedOrderRequest request)
        //{

        //    //_logger = new LoggerFactory().SetCurrent(new Log4NetLoggerFactory("Wechat_Verify")).CreateLogger();
        //    UnifiedOrderResponse resp = new UnifiedOrderResponse();
        //    //统一下单
        //    try
        //    {
        //        //_logger.Debug("exPay:in");
        //        WxPayData data = new WxPayData();
        //        data.SetValue("body", request.Body);
        //        data.SetValue("attach", request.Attach);
        //        data.SetValue("out_trade_no", request.OutTradeNo);
        //        data.SetValue("total_fee", request.TotalFee);
        //        data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
        //        data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
        //        data.SetValue("goods_tag", request.GoodTag);
        //        data.SetValue("trade_type", request.TradeType);
        //        data.SetValue("openid", request.OpenId);


        //        data.SetValue("notify_url", request.NotifyUrl);//异步通知url
        //        data.SetValue("appid", WxPayConfig.APPID);//公众账号ID
        //        data.SetValue("mch_id", WxPayConfig.MCHID);//商户号
        //        data.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip
        //        data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串

        //        //签名
        //        data.SetValue("sign", data.MakeSign());

        //        string xml = data.ToXml();
        //        LogHelp.WriteLog(DateTime.Now + "payInxml:" + xml);
        //        RestClient client = new RestClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        //        RestRequest req = new RestRequest(Method.POST);
        //        req.RequestFormat = DataFormat.Xml;
        //        req.AddParameter("text/xml", xml, ParameterType.RequestBody);

        //        var content = client.Execute(req).Content;
        //        LogHelp.WriteLog(DateTime.Now + "payIn:" + content);
        //        WxPayData result = new WxPayData();
        //        result.FromXml(content);


        //        if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
        //        {
        //            resp.Success = false;

        //            if (result.IsSet("return_msg"))
        //            {
        //                resp.ErrMsg = (string)result.GetValue("return_msg");
        //            }

        //            return resp;
        //        }

        //        resp.Success = (string)result.GetValue("return_code") == "SUCCESS";
        //        if (!resp.Success)
        //        {
        //            resp.ErrMsg = (string)result.GetValue("return_msg");
        //            return resp;
        //        }
        //        else
        //            resp.ErrMsg = string.Empty;

        //        resp.AppId = (string)result.GetValue("appid");
        //        resp.MchId = (string)result.GetValue("mch_id");
        //        resp.NonceStr = (string)result.GetValue("nonce_str");
        //        resp.Sign = (string)result.GetValue("sign");
        //        resp.PrepayId = (string)result.GetValue("prepay_id");
        //        resp.TradeType = (string)result.GetValue("trade_type");
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelp.WriteLog(DateTime.Now + "UnifiedOrderError:" + ex.Message);
        //    }

        //    return resp;
        //}

        //public RefundOrderResponse RefundOrder(RefundOrderRequest request)
        //{
        //    RefundOrderResponse resp = new RefundOrderResponse();

        //    RestClient client = new RestClient("https://api.mch.weixin.qq.com/secapi/pay/refund");

        //    X509Certificate2[] certs = new X509Certificate2[] {
        //        new X509Certificate2(request.SSLCertRootPath + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD)
        //        };

        //    client.ClientCertificates = new X509CertificateCollection(certs);

        //    WxPayData data = new WxPayData();
        //    data.SetValue("transaction_id", request.TransactionId);
        //    data.SetValue("out_refund_no", request.OutRefundNo);
        //    data.SetValue("total_fee", request.TotalFee);
        //    data.SetValue("refund_fee", request.RefundFee);
        //    data.SetValue("op_user_id", WxPayConfig.MCHID);

        //    data.SetValue("appid", WxPayConfig.APPID);
        //    data.SetValue("mch_id", WxPayConfig.MCHID);
        //    data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
        //    data.SetValue("sign", data.MakeSign());

        //    string xml = data.ToXml();

        //    RestRequest req = new RestRequest(Method.POST);
        //    req.RequestFormat = DataFormat.Xml;
        //    req.AddParameter("text/xml", xml, ParameterType.RequestBody);

        //    var content = client.Execute(req).Content;

        //    WxPayData result = new WxPayData();
        //    result.FromXml(content);

        //    resp.Success = (string)result.GetValue("return_code") == "SUCCESS";
        //    if (!resp.Success)
        //    {
        //        resp.ErrCode = (string)result.GetValue("err_code");
        //        resp.ErrMsg = (string)result.GetValue("err_code_des");
        //        return resp;
        //    }
        //    else
        //    {
        //        resp.ErrCode = string.Empty;
        //        resp.ErrMsg = string.Empty;
        //    }


        //    resp.AppId = (string)result.GetValue("appid");
        //    resp.MchId = (string)result.GetValue("mch_id");

        //    resp.TransactionId = (string)result.GetValue("transaction_id");
        //    resp.OutTradeNo = (string)result.GetValue("out_trade_no");
        //    resp.OutRefundNo = (string)result.GetValue("out_refund_no");
        //    resp.RefundId = (string)result.GetValue("refund_id");
        //    resp.RefundChannel = (string)result.GetValue("refund_channel");
        //    resp.RefundFee = int.Parse((string)result.GetValue("refund_fee"));
        //    resp.TotalFee = int.Parse((string)result.GetValue("total_fee"));

        //    return resp;
        //}


        public WxPayData Refund(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

            //检测必填参数
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!");
            }
            else if (!inputObj.IsSet("out_refund_no"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数total_fee!");
            }
            else if (!inputObj.IsSet("refund_fee"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!");
            }

            inputObj.SetValue("op_user_id", WxPayConfig.MCHID);
            inputObj.SetValue("appid", WxPayConfig.APPID);                              //公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);                             //商户号
            inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串

            inputObj.SetValue("sign", inputObj.MakeSign());                             //签名

            string xml   = inputObj.ToXml();
            var    start = DateTime.Now;

            LogHelp.WriteLog(DateTime.Now + "Refund request:" + xml);

            byte[]         data       = System.Text.Encoding.UTF8.GetBytes(xml);
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);

            webrequest.Method        = "POST";
            webrequest.ContentType   = "application/x-www-form-urlencoded";
            webrequest.Timeout       = 6 * 1000;;
            webrequest.ContentLength = data.Length;

            //string path = "/cert/apiclient_cert.p12";
            X509Certificate2 cert = new X509Certificate2(WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);

            webrequest.ClientCertificates.Add(cert);

            webrequest.KeepAlive       = false;
            webrequest.ProtocolVersion = HttpVersion.Version10;
            Stream stream = webrequest.GetRequestStream();

            stream.Write(data, 0, data.Length);
            stream.Close();
            HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    sr          = new StreamReader(webresponse.GetResponseStream(), Encoding.UTF8);
            string          response    = sr.ReadToEnd();

            //string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API
            LogHelp.WriteLog(DateTime.Now + "Refund response:" + response);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时

            //将xml格式的结果转换为对象以返回
            WxPayData result = new WxPayData();

            result.FromXml(response);



            return(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 生成银行及物业订单
        /// </summary>
        /// <param name="Row"></param>
        /// <returns></returns>
        public string GenerateOrder(DataRow Row)
        {
            bool   IsBankOk        = false;
            bool   IsPropertyOk    = false;
            string PropertyOrderId = "";
            string BankOrderId     = "";

            string CommunityId = Row["CommunityId"].ToString();
            string CostID      = Row["CostID"].ToString();
            string RoomID      = Row["RoomID"].ToString();

            if (!Row.Table.Columns.Contains("HandID") || !long.TryParse(Row["HandID"].ToString(), out long HandID))
            {
                HandID = 0;
            }
            string txnTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string CustID  = Row["CustID"].ToString();
            string Amount  = Row["Amount"].ToString();
            //2017-06-05添加可选参数openId
            //用于区分是否来自于微信H5支付
            //默认为空
            string      openId      = Row.Table.Columns.Contains("openId") ? Row["openId"].ToString() : "";
            WxPayConfig wxPayConfig = GenerateConfig(CommunityId);

            if (null == wxPayConfig)
            {
                return(JSONHelper.FromString(false, "未配置证书文件"));
            }

            string erpConnStr = GetConnection(CommunityId);

            PubConstant.hmWyglConnectionString = erpConnStr;

            //生成物业账单
            string PropertyResult = GeneratePropertyOrder(CommunityId, CostID, RoomID, txnTime, CustID, ref IsPropertyOk, ref Amount, ref PropertyOrderId, wxPayConfig);

            if (IsPropertyOk == true)
            {
                #region 物业订单创建成功就保存车位ID
                if (HandID != 0)
                {
                    if (!Tb_OL_ParkCar_Insert(erpConnStr, PropertyOrderId, HandID))
                    {
                        return(JSONHelper.FromString(false, "保存车位预存明细失败"));
                    }
                }
                #endregion

                //生成银行订单,返回银行流水号
                WxPayData Data       = new WxPayData();
                string    BankResult = GenerateBankOrder(CommunityId, CustID, RoomID, PropertyOrderId, txnTime, Amount, ref IsBankOk, ref BankOrderId, ref Data, wxPayConfig, openId);
                if (IsBankOk == false)
                {
                    return(JSONHelper.FromString(false, BankResult));
                }
                else
                {
                    //更新订单银行流水号
                    IDbConnection Conn  = new SqlConnection(GetConnection(CommunityId));
                    string        Query = "UPDATE Tb_OL_WeiXinPayOrder SET prepay_id=@prepay_id WHERE out_trade_no = @out_trade_no ";
                    Conn.Execute(Query, new { prepay_id = Data.GetValue("prepay_id").ToString(), out_trade_no = PropertyOrderId });
                    //向手机端返回银行记录
                    WxPayData result = new WxPayData();
                    result.SetValue("appid", Data.GetValue("appid"));
                    result.SetValue("partnerid", Data.GetValue("mch_id"));
                    result.SetValue("prepayid", Data.GetValue("prepay_id"));
                    result.SetValue("noncestr", Data.GetValue("nonce_str"));
                    result.SetValue("package", "Sign=WXPay");
                    result.SetValue("timestamp", (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
                    result.SetValue("sign", result.MakeSign());
                    result.SetValue("out_trade_no", PropertyOrderId);
                    return(JSONHelper.FromJsonString(true, result.ToJson()));
                }
            }
            else
            {
                return(JSONHelper.FromString(false, PropertyResult));
            }
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Ds"></param>
        /// <returns></returns>
        public string GenerateOrder(DataSet Ds)
        {
            DataRow Row = Ds.Tables[0].Rows[0];

            bool   IsBankOk     = false;
            bool   IsBusinessOk = false;
            string OrderId      = "";


            string txnTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string UserId  = Row["UserId"].ToString();
            string BussId  = Row["BussId"].ToString();

            WxPayConfig wxPayConfig = GenerateConfig(BussId);

            if (null == wxPayConfig)
            {
                return(JSONHelper.FromString(false, "未配置证书文件"));
            }

            string Name           = Row["Name"].ToString();
            string Mobile         = Row["Mobile"].ToString();
            string DeliverAddress = Row["DeliverAddress"].ToString();
            string subject        = "";

            int Amount       = 0;
            int CouponAmount = 0;

            // 俊发需求5896
            string communityId = null;

            if (Row.Table.Columns.Contains("CommunityId") && !string.IsNullOrEmpty(Row["CommunityId"].ToString()))
            {
                communityId = Row["CommunityId"].ToString();
            }

            //生成商家账单
            string BussinessResult = GenerateBusinessOrder(Ds, communityId, BussId, UserId, txnTime, ref IsBusinessOk, ref Amount, ref CouponAmount, ref OrderId, Name, Mobile, DeliverAddress, wxPayConfig);

            if (IsBusinessOk == true)
            {
                using (IDbConnection Conn = new SqlConnection(ConnectionDb.GetBusinessConnection()))
                {
                    Tb_System_BusinessCorp bussInfo = Conn.Query <Tb_System_BusinessCorp>(@"SELECT * FROM Tb_System_BusinessCorp WHERE BussId=@BussId",
                                                                                          new { BussId = BussId }).FirstOrDefault();

                    if (bussInfo != null)
                    {
                        subject = bussInfo.BussName + "订单,共" + Ds.Tables["Product"].Rows.Count + "种商品";
                    }
                }

                //生成银行订单,返回银行流水号
                WxPayData Data = new WxPayData();

                string BankResult = GenerateBankOrder(BussId, OrderId, txnTime, (Amount - CouponAmount), ref IsBankOk, ref Data, wxPayConfig);
                if (IsBankOk == false)
                {
                    return(JSONHelper.FromString(false, BankResult));
                }
                else
                {
                    using (IDbConnection conn = new SqlConnection(ConnectionDb.GetBusinessConnection()))
                    {
                        string sql;
                        if ((Amount - CouponAmount) == 0)
                        {
                            sql = string.Format(@"UPDATE Tb_Charge_Receipt SET PrepayStr=@prepay_str,Method='微信',IsPay='已付款',ReturnCode='TRADE_FINISHED',ReturnMsg='TRADE_FINISHED',PayDate=GetDate(),Amount={0:###.##},CouponAmount={1:###.##},RealAmount=0 WHERE OrderId = @OrderId", Amount / 100, CouponAmount / 100);
                        }
                        else
                        {
                            sql = @"UPDATE Tb_Charge_Receipt SET PrepayStr=@prepay_str WHERE OrderId = @OrderId";
                        }

                        conn.Execute(sql, new { prepay_str = Data.GetValue("prepay_id").ToString(), OrderId = OrderId });
                    }

                    //向手机端返回银行记录
                    WxPayData result = new WxPayData();
                    result.SetValue("appid", Data.GetValue("appid"));
                    result.SetValue("partnerid", Data.GetValue("mch_id"));
                    result.SetValue("prepayid", Data.GetValue("prepay_id"));
                    result.SetValue("noncestr", Data.GetValue("nonce_str"));
                    result.SetValue("package", "Sign=WXPay");
                    result.SetValue("timestamp", (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
                    result.SetValue("sign", result.MakeSign());
                    // 上面的顺序不允许变动
                    result.SetValue("total_fee", Amount);
                    return(JSONHelper.FromJsonString(true, result.ToJson()));
                }
            }
            else
            {
                return(JSONHelper.FromString(false, BussinessResult));
            }
        }
Exemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //读取站点配置信息
            Model.sysconfig sysConfig       = new BLL.sysconfig().loadConfig();
            int             site_payment_id = 0; //订单支付方式

            //=============================获得订单信息================================
            order_no = DTRequest.GetFormString("pay_order_no").ToUpper();
            decimal order_amount = DTRequest.GetFormDecimal("pay_order_amount", 0);
            string  user_name    = DTRequest.GetFormString("pay_user_name");
            string  subject      = DTRequest.GetFormString("pay_subject");

            //检查参数是否正确
            if (string.IsNullOrEmpty(order_no) || order_amount == 0)
            {
                Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您提交的参数有误!")));
                return;
            }
            //===============================判断订单==================================
            if (order_no.StartsWith("R")) //R开头为在线充值订单
            {
                Model.user_recharge model = new BLL.user_recharge().GetModel(order_no);
                if (model == null)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您充值的订单号不存在或已删除!")));
                    return;
                }
                if (model.amount != order_amount)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您充值的订单金额与实际金额不一致!")));
                    return;
                }
                if (model.status == 1)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("payment", "?action=succeed&order_no=" + order_no));
                    return;
                }
                site_payment_id = model.payment_id; //站点支付方式ID
            }
            else //B开头为商品订单
            {
                Model.orders model = new BLL.orders().GetModel(order_no);
                if (model == null)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您支付的订单号不存在或已删除!")));
                    return;
                }
                if (model.order_amount != order_amount)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您支付的订单金额与实际金额不一致!")));
                    return;
                }
                if (model.payment_status == 2)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("payment", "?action=succeed&order_no=" + order_no));
                    return;
                }
                site_payment_id = model.payment_id; //站点支付方式ID
            }
            if (user_name != "")
            {
                user_name = "支付会员:" + user_name;
            }
            else
            {
                user_name = "匿名用户";
            }

            //===========================调用统一下单接口==============================
            string       sendUrl      = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            NativeConfig nativeConfig = new NativeConfig(site_payment_id);
            WxPayData    data         = new WxPayData();

            data.SetValue("body", user_name);                                              //商品描述
            data.SetValue("detail", sysConfig.webname + "-" + subject);                    //商品详情
            data.SetValue("out_trade_no", order_no);                                       //商户订单号
            data.SetValue("total_fee", (Convert.ToDouble(order_amount) * 100).ToString()); //订单总金额,以分为单位
            data.SetValue("trade_type", "NATIVE");                                         //交易类型
            data.SetValue("product_id", order_no);                                         //商品ID
            data.SetValue("notify_url", nativeConfig.Notify_url);                          //异步通知url
            data.SetValue("spbill_create_ip", DTRequest.GetIP());                          //终端IP
            data.SetValue("appid", nativeConfig.AppId);                                    //公众账号ID
            data.SetValue("mch_id", nativeConfig.Partner);                                 //商户号
            data.SetValue("nonce_str", NativePay.GenerateNonceStr());                      //随机字符串
            data.SetValue("sign", data.MakeSign(nativeConfig.Key));                        //签名
            string    xml       = data.ToXml();                                            //转换成XML
            var       startTime = DateTime.Now;                                            //开始时间
            string    response  = HttpService.Post(xml, sendUrl, false, 6);                //发送请求
            var       endTime   = DateTime.Now;                                            //结束时间
            int       timeCost  = (int)((endTime - startTime).TotalMilliseconds);          //计算所用时间
            WxPayData result    = new WxPayData();

            result.FromXml(response, nativeConfig.Key);
            NativePay.ReportCostTime(site_payment_id, sendUrl, timeCost, result); //测速上报

            string codeUrl = result.GetValue("code_url").ToString();              //获得统一下单接口返回的二维码链接

            imgQRCode.ImageUrl = "qrcode.aspx?data=" + HttpUtility.UrlEncode(codeUrl);
            litText.Text       = order_amount.ToString("#0.00");
        }
Exemplo n.º 13
0
        /// <summary>
        /// 生成银行及物业订单
        /// </summary>
        /// <param name="Row"></param>
        /// <returns></returns>
        public string GenerateOrder(DataRow Row)
        {
            bool   IsBankOk        = false;
            bool   IsPropertyOk    = false;
            string PropertyOrderId = "";
            string BankOrderId     = "";

            string CommunityId = Row["CommunityId"].ToString();
            string FeesIds     = Row["FeesIds"].ToString();
            string txnTime     = DateTime.Now.ToString("yyyyMMddHHmmss");
            string CustID      = Row["CustID"].ToString();
            //2017-06-05添加可选参数openId
            //用于区分是否来自于微信H5支付
            //默认为空
            string openId = Row.Table.Columns.Contains("openId") ? Row["openId"].ToString() : "";

            string UserId = null;

            if (Row.Table.Columns.Contains("UserID") && !string.IsNullOrEmpty(Row["UserID"].ToString()))
            {
                UserId = Row["UserID"].ToString();
            }

            int UsePoints = 0;

            if (Row.Table.Columns.Contains("UsePoints") && !string.IsNullOrEmpty(Row["UsePoints"].ToString()))
            {
                UsePoints = AppGlobal.StrToInt(Row["UsePoints"].ToString());
            }

            //增加FeesIds重复验证
            if (FeesIds == "")
            {
                return(JSONHelper.FromString(false, "未选择任何费用"));
            }
            string[] feesArray = FeesIds.Split(',').Distinct().ToArray();
            FeesIds = string.Join(",", feesArray.ToArray());

            WxPayConfig wxPayConfig = GenerateConfig(CommunityId);

            if (null == wxPayConfig)
            {
                return(JSONHelper.FromString(false, "该小区不支持微信支付"));
            }

            PubConstant.hmWyglConnectionString = GetConnection(CommunityId);

            using (var appConn = new SqlConnection(PubConstant.UnifiedContionString))
            {
                if (appConn.State == ConnectionState.Closed)
                {
                    appConn.Open();
                }

                var appTrans = appConn.BeginTransaction();

                // 检查数据
                string useHistoryID = null;

                int     Amount         = 0;                 // 缴费总额
                decimal propertyAmount = 0.0m;              // 物业费缴费总额
                decimal parkingAmount  = 0.0m;              // 车位费缴费总额

                decimal deductionAmount            = 0.0m;  // 积分可抵扣金额
                decimal propertyMaxDiscountsAmount = 0.0m;  // 物管费最大可抵用金额
                decimal parkingMaxDiscountsAmount  = 0.0m;  // 车位费最大可抵用金额

                int pointBalance    = 0;                    // 积分余额
                var deductionObject = new List <string>();  // 积分可抵扣对象

                #region 获取积分抵扣规则
                // 要使用的积分是否大于用户积分余额
                pointBalance = appConn.Query <int>("SELECT PointBalance FROM Tb_App_UserPoint WHERE UserID=@UserID", new { UserID = UserId }, appTrans).FirstOrDefault();
                if (pointBalance < UsePoints)
                {
                    return(new ApiResult(false, "积分余额不足").toJson());
                }

                // 企业编号
                short corpId = appConn.Query <short>("SELECT CorpID FROM Tb_Community WHERE Id=@CommunityId",
                                                     new { CommunityId = CommunityId }, appTrans).FirstOrDefault();

                // 积分权限控制
                var controlInfo = appConn.Query <Tb_Control_AppPoint>(@"SELECT * FROM Tb_Control_AppPoint WHERE CorpID=@CorpID AND IsEnable=1 
                                                                            AND (CommunityID=@CommunityId OR CommunityID IS NULL) ORDER BY CommunityID DESC",
                                                                      new { CorpID = corpId, CommunityId = CommunityId }, appTrans).FirstOrDefault();

                if (controlInfo == null || controlInfo.IsEnable == false)
                {
                    controlInfo             = Tb_Control_AppPoint.DefaultControl;
                    controlInfo.CorpID      = corpId;
                    controlInfo.CommunityID = Guid.Empty.ToString();
                }

                // 允许抵用物业费
                if (controlInfo.AllowDeductionPropertyFees)
                {
                    deductionObject.Add($@"'{AppPointUsableObjectConverter.GetKey(AppPointUsableObject.PropertyFee)}'");
                }
                // 允许抵用车位费
                if (controlInfo.AllowDeductionParkingFees)
                {
                    deductionObject.Add($@"'{AppPointUsableObjectConverter.GetKey(AppPointUsableObject.ParkingFee)}'");
                }
                #endregion

                #region 获取缴费列表,读取欠费总额
                using (IDbConnection erpConn = new SqlConnection(PubConstant.hmWyglConnectionString))
                {
                    try
                    {
                        IEnumerable <dynamic> arrearsList = erpConn.Query($@"SELECT * FROM view_HSPR_Fees_Filter WHERE FeesID IN({FeesIds})");

                        // 允许抵用物业费
                        if (controlInfo.AllowDeductionPropertyFees)
                        {
                            foreach (dynamic item in arrearsList)
                            {
                                if (item.SysCostSign != null && item.SysCostSign.ToString() == "B0001")
                                {
                                    propertyAmount += item.DebtsAmount;
                                }
                            }
                        }

                        // 允许抵用车位费
                        if (controlInfo.AllowDeductionParkingFees)
                        {
                            foreach (dynamic item in arrearsList)
                            {
                                if (item.SysCostSign != null && item.SysCostSign.ToString() == "B0002")
                                {
                                    parkingAmount += item.DebtsAmount;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        appTrans.Rollback();
                        return(new ApiResult(false, "验证欠费列表失败").toJson());
                    }
                }
                #endregion

                if (UsePoints > 0 && !string.IsNullOrEmpty(UserId))
                {
                    #region 判断积分是否足够
                    try
                    {
                        if (deductionObject.Count == 0)
                        {
                            return(new ApiResult(false, "暂不支持积分抵用功能").toJson());
                        }

                        // 积分抵用规则
                        var ruleInfo = appConn.Query($@"SELECT IID,ConditionAmount,DiscountsAmount,DeductionObject,b.Remark AS SysCostSign,StartTime,EndTime 
                                        FROM Tb_App_Point_PropertyDeductionRule a LEFT JOIN Tb_Dictionary_Point_UsableObject b
                                        ON a.DeductionObject=b.[Key] 
                                        WHERE CommunityID=@CommunityId AND DeductionObject IN({string.Join(", ", deductionObject) }) 
                                        AND getdate() BETWEEN StartTime AND EndTime AND a.IsDelete=0 ORDER BY ConditionAmount,DiscountsAmount",
                                                     new { CommunityId = CommunityId }, appTrans);

                        if (ruleInfo.Count() == 0)
                        {
                            return(new ApiResult(false, "积分抵用规则未设置或已失效").toJson());
                        }

                        // 确定物管费可抵用金额
                        if (propertyAmount > 0)
                        {
                            string key = AppPointUsableObjectConverter.GetKey(AppPointUsableObject.PropertyFee);
                            foreach (var item in ruleInfo)
                            {
                                if (item.DeductionObject == key && propertyAmount >= item.ConditionAmount)
                                {
                                    propertyMaxDiscountsAmount = item.DiscountsAmount;
                                }
                            }
                        }

                        // 确定车位费可抵用金额
                        if (parkingAmount > 0)
                        {
                            string key = AppPointUsableObjectConverter.GetKey(AppPointUsableObject.ParkingFee);
                            foreach (var item in ruleInfo)
                            {
                                if (item.DeductionObject == key && parkingAmount >= item.ConditionAmount)
                                {
                                    parkingMaxDiscountsAmount = item.DiscountsAmount;
                                }
                            }
                        }

                        // 要使用积分抵用的金额
                        deductionAmount = UsePoints / (decimal)controlInfo.PointExchangeRatio;

                        // 积分数量不正常
                        if (deductionAmount > (parkingMaxDiscountsAmount + propertyMaxDiscountsAmount))
                        {
                            return(new ApiResult(false, "使用积分超过可抵用最大金额").toJson());
                        }
                        else
                        {
                            decimal tmp = deductionAmount;

                            // 部分抵扣物业费
                            if (propertyMaxDiscountsAmount != 0)
                            {
                                if (tmp <= propertyMaxDiscountsAmount)
                                {
                                    propertyMaxDiscountsAmount = tmp;
                                    tmp = 0;
                                }
                                else
                                {
                                    tmp -= propertyMaxDiscountsAmount;
                                }
                            }

                            // 部分抵扣车位费
                            if (parkingMaxDiscountsAmount != 0 && tmp > 0)
                            {
                                if (tmp <= parkingMaxDiscountsAmount)
                                {
                                    parkingMaxDiscountsAmount = tmp;
                                    tmp = 0;
                                }
                                else
                                {
                                    tmp -= parkingMaxDiscountsAmount;
                                }
                            }

                            if (tmp != 0)
                            {
                                return(new ApiResult(false, "积分抵用出错").toJson());
                            }
                        }

                        if (UsePoints > 0 && deductionAmount > 0)
                        {
                            useHistoryID = Guid.NewGuid().ToString();
                        }
                    }
                    catch (Exception)
                    {
                        appTrans.Rollback();
                        return(new ApiResult(false, "积分验证失败").toJson());
                    }
                    #endregion
                }

                // 积分数量正常,生成订单
                try
                {
                    // 生成ERP账单
                    string PropertyResult = GeneratePropertyOrder(CommunityId, FeesIds, txnTime, CustID, ref IsPropertyOk, ref Amount, ref PropertyOrderId, wxPayConfig);

                    // ERP订单生成成功
                    if (IsPropertyOk == true)
                    {
                        // 应缴总金额
                        Amount = Amount - (int)(deductionAmount * 100);

                        // 微信签名订单信息
                        WxPayData Data       = new WxPayData();
                        string    BankResult = GenerateBankOrder(CommunityId, UserId, feesArray.First(), PropertyOrderId, txnTime, Amount, ref IsBankOk, ref BankOrderId, ref Data, wxPayConfig, openId);

                        if (IsBankOk == true)
                        {
                            // 微信订单信息
                            WxPayData result = new WxPayData();
                            result.SetValue("appid", Data.GetValue("appid"));
                            result.SetValue("partnerid", Data.GetValue("mch_id"));
                            result.SetValue("prepayid", Data.GetValue("prepay_id"));
                            result.SetValue("noncestr", Data.GetValue("nonce_str"));
                            result.SetValue("package", "Sign=WXPay");
                            result.SetValue("timestamp", (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
                            result.SetValue("sign", result.MakeSign());

                            // 计算预赠送积分
                            new AppPoint().CalcPresentedPointForPropertyFees(CommunityId, propertyAmount - propertyMaxDiscountsAmount, parkingAmount - parkingMaxDiscountsAmount, out int p1, out int p2);
                            result.SetValue("presented_points", (p1 + p2));

                            if (!string.IsNullOrEmpty(useHistoryID))
                            {
                                result.SetValue("out_trade_no", PropertyOrderId);
                                result.SetValue("deduction_amount", deductionAmount);
                                result.SetValue("point_use_history_id", useHistoryID);

                                appConn.Execute($@"UPDATE Tb_App_UserPoint SET PointBalance=(PointBalance-@UsePoints) WHERE UserID=@UserID;
                                                    INSERT INTO Tb_App_Point_UseHistory(IID, UserID, UseWay, UsePoints, PointBalance, DeductionAmount, Remark)
                                                        VALUES(@UseHistoryID, @UserID, @UseWay, @UsePoints, @PointBalance, @DeductionAmount, @Remark);
                                                    INSERT INTO Tb_App_Point_Locked(UserID, UseHistoryID, LockedPoints) 
                                                        VALUES (@UserID, @UseHistoryID, @LockedPoints);",
                                                new
                                {
                                    UsePoints       = UsePoints,
                                    UserID          = UserId,
                                    UseHistoryID    = useHistoryID,
                                    UseWay          = AppPointUseWayConverter.GetKey(AppPointUseWay.PropertyFeeDeduction),
                                    PointBalance    = pointBalance - UsePoints,
                                    DeductionAmount = deductionAmount,
                                    Remark          = AppPointUseWayConverter.GetValue(AppPointUseWay.PropertyFeeDeduction),
                                    LockedPoints    = UsePoints
                                }, appTrans);

                                string usableObject = string.Join(",", deductionObject.Select(obj => AppPointUsableObjectConverter.GetValue(obj.Replace("'", ""))));

                                // 存储积分使用记录与订单关联关系
                                appConn.Execute(@"INSERT INTO Tb_App_Point_UseHistoryOrder(UseHistoryID, OrderID, Payment, UsableObject) 
                                                    VALUES(@UseHistoryID, @OrderID, '微信', @UsableObject)",
                                                new
                                {
                                    UseHistoryID = useHistoryID,
                                    OrderID      = PropertyOrderId,
                                    UsableObject = usableObject
                                }, appTrans);
                            }

                            using (var erpConn = new SqlConnection(PubConstant.hmWyglConnectionString))
                            {
                                // 更新订单
                                erpConn.Execute(@"UPDATE Tb_OL_WeiXinPayOrder SET prepay_id=@prepay_id WHERE out_trade_no = @out_trade_no ",
                                                new { prepay_id = Data.GetValue("prepay_id").ToString(), out_trade_no = PropertyOrderId });
                            }

                            appTrans?.Commit();
                            return(JSONHelper.FromJsonString(true, result.ToJson()));
                        }
                        else
                        {
                            appTrans?.Rollback();
                            return(JSONHelper.FromString(false, BankResult));
                        }
                    }
                    else
                    {
                        appTrans?.Rollback();
                        return(JSONHelper.FromString(false, PropertyResult));
                    }
                }
                catch (Exception ex)
                {
                    appTrans?.Rollback();
                    return(JSONHelper.FromString(false, ex.Message + ex.StackTrace));
                }
            }
        }
Exemplo n.º 14
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());
            }
        }
Exemplo n.º 15
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=支付异常..."));
            }
        }
        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
        }
Exemplo n.º 17
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());
        }
Exemplo n.º 18
0
        public ActionResult Callback(FormCollection form)
        {
            try
            {
                var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.WeiXin") as WeiXinPaymentProcessor;
                if (processor == null ||
                    !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
                {
                    throw new NopException("Payments.WeiXin Not Found");
                }

                var s       = Request.InputStream;
                var count   = 0;
                var buffer  = new byte[1024];
                var builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, 1024)) > 0)
                {
                    builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();

                _logger.InsertLog(LogLevel.Information, GetType() + "Receive data from WeChat : " + builder);
                var data = new WxPayData();
                data.FromXml(builder.ToString(), _weiXinPaymentSettings.AppSecret);


                if (!data.IsSet("product_id"))
                {
                    var res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "支付结果中微信订单号不存在");
                    Response.Write(res.ToXml());
                    Response.End();
                }
                else if (!data.IsSet("appid") || !data.IsSet("appid") || !data.IsSet("appid") || !data.IsSet("appid") ||
                         !data.IsSet("appid") || !data.IsSet("appid"))
                {
                    var res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "缺少参数");
                    Response.Write(res.ToXml());
                    Response.End();
                }
                else
                {
                    var orderIdStr = data.GetValue("product_id").ToString();
                    int orderId;
                    if (!int.TryParse(orderIdStr, out orderId))
                    {
                        return(Content("error"));
                    }

                    var order = _orderService.GetOrderById(orderId);

                    if (order == null)
                    {
                        var res = new WxPayData();
                        res.SetValue("return_code", "FAIL");
                        res.SetValue("return_msg", "订单号错误");
                        Response.Write(res.ToXml());
                        Response.End();
                    }
                    else
                    {
                        var result = processor.Unifiedorder(orderIdStr, "宁尼可在线商城订单" + orderId, "宁尼可在线商城订单" + orderId, orderIdStr,
                                                            ((int)(order.OrderTotal * 100)).ToString(CultureInfo.InvariantCulture));

                        var wxModel = new WxPayData();
                        wxModel.FromXml(result, _weiXinPaymentSettings.AppSecret);

                        if (wxModel.IsSet("return_code") && (string)wxModel.GetValue("return_code") != "SUCCESS")
                        {
                            Response.Write(wxModel.ToXml());
                            Response.End();
                        }
                        else if (!wxModel.IsSet("prepay_id"))
                        {
                            var res = new WxPayData();
                            res.SetValue("return_code", "FAIL");
                            res.SetValue("return_msg", "预支付ID	不存在");
                            Response.Write(res.ToXml());
                            Response.End();
                        }
                        else
                        {
                            var res = new WxPayData();
                            res.SetValue("return_code", "SUCCESS");
                            res.SetValue("appid", _weiXinPaymentSettings.AppId);
                            res.SetValue("mch_id", _weiXinPaymentSettings.MchId);
                            res.SetValue("nonce_str", Guid.NewGuid().ToString("N"));
                            res.SetValue("prepay_id", wxModel.GetValue("prepay_id"));
                            res.SetValue("result_code", "SUCCESS");
                            var sign = res.MakeSign(_weiXinPaymentSettings.AppSecret);
                            res.SetValue("sign", sign);

                            Response.Write(res.ToXml());
                            Response.End();
                        }
                    }
                }
            }
            catch (NopException ex)
            {
                var res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);

                Response.Write(res.ToXml());
                Response.End();
            }


            return(Content(""));
        }
Exemplo n.º 19
0
        public string ChargeByWeixin(string productName, decimal amount, string orderNo, string notifyUrl)
        {
            var config = ConfigInfo;

            WxPayConfig.APPID     = config.WeixinAppId;
            WxPayConfig.MCHID     = config.WeixinMchId;
            WxPayConfig.KEY       = config.WeixinKey;
            WxPayConfig.APPSECRET = config.WeixinAppSecret;

            //=======【支付结果通知url】=====================================

            /* 支付结果通知回调url,用于商户接收支付结果
             */
            WxPayConfig.NOTIFY_URL = notifyUrl;

            //=======【商户系统后台机器IP】=====================================

            /* 此参数可手动配置也可在程序中自动获取
             */
            WxPayConfig.IP = "8.8.8.8";


            //=======【代理服务器设置】===================================

            /* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置)
             */
            WxPayConfig.PROXY_URL = "http://10.152.18.220:8080";

            //=======【上报信息配置】===================================

            /* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报
             */
            WxPayConfig.REPORT_LEVENL = 1;

            //=======【日志级别】===================================

            /* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
             */
            WxPayConfig.LOG_LEVENL = 0;

            var data = new WxPayData();

            data.SetValue("body", productName);                                                   //商品描述
            data.SetValue("attach", string.Empty);                                                //附加数据
            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", "jjj");                                                    //商品标记
            data.SetValue("trade_type", "NATIVE");                                                //交易类型
            data.SetValue("product_id", "productId");                                             //商品ID

            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            //检测必填参数
            if (!data.IsSet("out_trade_no"))
            {
                throw new WxPayException("缺少统一支付接口必填参数out_trade_no!");
            }
            if (!data.IsSet("body"))
            {
                throw new WxPayException("缺少统一支付接口必填参数body!");
            }
            if (!data.IsSet("total_fee"))
            {
                throw new WxPayException("缺少统一支付接口必填参数total_fee!");
            }
            if (!data.IsSet("trade_type"))
            {
                throw new WxPayException("缺少统一支付接口必填参数trade_type!");
            }

            //关联参数
            if (data.GetValue("trade_type").ToString() == "JSAPI" && !data.IsSet("openid"))
            {
                throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
            }
            if (data.GetValue("trade_type").ToString() == "NATIVE" && !data.IsSet("product_id"))
            {
                throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
            }

            //异步通知url未设置,则使用配置文件中的url
            if (!data.IsSet("notify_url"))
            {
                data.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url
            }

            data.SetValue("appid", WxPayConfig.APPID);                              //公众账号ID
            data.SetValue("mch_id", WxPayConfig.MCHID);                             //商户号
            data.SetValue("spbill_create_ip", WxPayConfig.IP);                      //终端ip
            data.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串

            //签名
            data.SetValue("sign", data.MakeSign());
            var xml      = data.ToXml();
            var response = HttpService.Post(xml, url, false, 6);
            var result   = new WxPayData();

            result.FromXml(response);

            Log.Info(GetType().ToString(), "ChargeByWeixin : " + response);
            Log.Info(GetType().ToString(), "notify_url : " + data.GetValue("notify_url"));

            if (!result.IsSet("code_url"))
            {
                throw new Exception($"code: {result.GetValue("return_code")}, msg: {result.GetValue("return_msg")}");
            }
            return(result.GetValue("code_url").ToString()); //获得统一下单接口返回的二维码链接
        }
Exemplo n.º 20
0
        /// <summary>
        /// 订单继续支付
        /// </summary>
        public string GoOnGenerateOrder(DataSet Ds)
        {
            DataRow Row = Ds.Tables[0].Rows[0];

            bool   IsBankOk     = false;
            bool   IsBusinessOk = true;//商家订单是否生成成功
            string OrderId      = Row["OrderId"].ToString();
            string prepay_str   = "";


            //取得上一次商家订单信息
            IDbConnection ConnOrder  = new SqlConnection(ConnectionDb.GetBusinessConnection());
            string        OrderQuery = "SELECT * FROM Tb_Charge_Receipt WHERE OrderId=@OrderId";

            Model.Model.Buss.Tb_Charge_Receipt TOrder = ConnOrder.Query <Model.Model.Buss.Tb_Charge_Receipt>(OrderQuery, new { OrderId = OrderId }).SingleOrDefault();

            if (TOrder != null)
            {
                IsBusinessOk = true;
            }
            string txnTime = TOrder.txnTime.ToString();
            string BussId  = TOrder.BussId.ToString();

            WxPayConfig wxPayConfig = GenerateConfig(BussId);

            if (null == wxPayConfig)
            {
                return(JSONHelper.FromString(false, "未配置证书文件"));
            }

            decimal realAmount = 0.0m;

            string sql = @"SELECT * FROM Tb_Charge_ReceiptDetail WHERE ReceiptCode=@ReceiptCode";

            IEnumerable <Tb_Charge_ReceiptDetail> ReceiptDetails = ConnOrder.Query <Tb_Charge_ReceiptDetail>(sql, new { ReceiptCode = TOrder.Id });

            foreach (Tb_Charge_ReceiptDetail item in ReceiptDetails)
            {
                // 计算此时应该多少钱
                sql = @"SELECT * FROM Tb_Resources_Details WHERE ResourcesID=@ResourcesID";
                Tb_Resources_Details resources = ConnOrder.Query <Tb_Resources_Details>(sql, new { ResourcesID = item.ResourcesID }).FirstOrDefault();

                if (resources != null)
                {
                    if (resources.IsGroupBuy == "是" && resources.GroupBuyEndDate.HasValue && resources.GroupBuyEndDate.Value > DateTime.Now)
                    {
                        realAmount += (resources.GroupBuyPrice.Value + item.Quantity);
                    }
                    else
                    {
                        realAmount += (resources.ResourcesSalePrice - resources.ResourcesDisCountPrice) * item.Quantity;
                    }

                    if (item.OffsetMoney.HasValue)
                    {
                        realAmount -= item.OffsetMoney.Value;
                    }

                    if (item.OffsetMoney2.HasValue)
                    {
                        realAmount -= item.OffsetMoney2.Value;
                    }
                }
            }

            if (IsBusinessOk == true)
            {
                sql = "SELECT * FROM Tb_System_BusinessCorp WHERE BussId=@BussId";
                Tb_System_BusinessCorp bussInfo = ConnOrder.Query <Tb_System_BusinessCorp>(sql, new { BussId = TOrder.BussId }).FirstOrDefault();

                //生成银行订单,返回银行流水号
                WxPayData Data = new WxPayData();

                string BankResult = GenerateBankOrder(BussId, OrderId, txnTime, (int)(realAmount * 100), ref IsBankOk, ref Data, wxPayConfig);
                if (IsBankOk == false)
                {
                    return(JSONHelper.FromString(false, BankResult));
                }
                else
                {
                    //更新订单银行流水号
                    IDbConnection Conn  = new SqlConnection(ConnectionDb.GetBusinessConnection());
                    string        Query = "UPDATE Tb_Charge_Receipt SET PrepayStr=@prepay_str WHERE OrderId = @OrderId ";
                    Conn.Execute(Query, new { prepay_str = prepay_str.ToString(), OrderId = OrderId });
                    //返回请求字符串

                    //向手机端返回银行记录
                    WxPayData result = new WxPayData();
                    result.SetValue("appid", Data.GetValue("appid"));
                    result.SetValue("partnerid", Data.GetValue("mch_id"));
                    result.SetValue("prepayid", Data.GetValue("prepay_id"));
                    result.SetValue("noncestr", Data.GetValue("nonce_str"));
                    result.SetValue("package", "Sign=WXPay");
                    result.SetValue("timestamp", (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
                    result.SetValue("sign", result.MakeSign());
                    return(JSONHelper.FromJsonString(true, result.ToJson()));
                }
            }
            return(JSONHelper.FromString(false, "生成订单失败"));
        }
Exemplo n.º 21
0
        /// <summary>
        /// 第一步:用户同意授权,获取code
        /// 第二步:通过code换取网页授权access_token
        /// 第三步:刷新access_token(如果需要)
        /// 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        /// 第五步:获取openid
        /// 第六步:调用微信统一下单
        /// 第七步:拿到prepay_id
        /// 第八步:构造请求URL
        /// 第九步:唤起微信支付
        /// 第十步:支付成功跳转
        /// </summary>
        /// <param name="context"></param>
        private void UnifiedOrder(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");
            string ip            = context.Request.ServerVariables.Get("Remote_Addr").ToString();

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

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

            try
            {
                BillRepository service = new BillRepository();
                var            bill    = service.CreateBill("id", mobile);
                if (!string.IsNullOrEmpty(bill))
                {
                    //logger.Error("创建订单结果:");
                    //logger.Error(bill);
                    BillAddResponse billData = JsonConvert.DeserializeObject <BillAddResponse>(bill);
                    if (billData != null)
                    {
                        #region 第二步,发起预支付统一下单

                        string timestamp = context.Session["timestamp"].ToString();
                        string nonceStr  = context.Session["nonceStr"].ToString();
                        string openid    = context.Session["openid"].ToString();

                        //logger.Error("支付步骤timestamp:" + timestamp);
                        //logger.Error("支付步骤nonceStr:" + nonceStr);
                        //logger.Error("支付步骤openid:" + openid);

                        WxPayData data = new WxPayData();
                        data.SetValue("body", billData.ProductName);                                          //商品描述
                        data.SetValue("out_trade_no", billData.BillNumber);                                   //订单号
                        data.SetValue("total_fee", (int)(billData.BillAmount * 100));                         //总金额,微信是以分为单位
                        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", openid);                                                      //用户OPENID
                        data.SetValue("product_id", billData.ProductID);                                      //商品ID
                        data.SetValue("spbill_create_ip", ip);                                                //中端IP
                        data.SetValue("sign_type", "MD5");                                                    //中端IP
                        data.SetValue("notify_url", WechatJSAPIConfig.notify_url);
                        data.SetValue("nonce_str", nonceStr);

                        WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
                        if (result == null)
                        {
                            message.msg  = "0";
                            message.data = "";

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

                        string prepay_id = result.GetValue("prepay_id").ToString();//获得统一下单接口返回的二维码链接

                        #endregion

                        //logger.Error("支付步骤订单结构:" + result.ToXml());

                        #region 第三步,生成支付签名

                        WxPayData payData = new WxPayData();
                        payData.SetValue("appId", WechatJSAPIConfig.appid);
                        payData.SetValue("timeStamp", timestamp);
                        payData.SetValue("nonceStr", nonceStr);
                        payData.SetValue("package", $"prepay_id={prepay_id}");
                        payData.SetValue("signType", "MD5");

                        string md5sign = payData.MakeSign();

                        //logger.Error("支付步骤签名:" + md5sign);

                        var jsBridge = new
                        {
                            msg       = "200",
                            appId     = WechatJSAPIConfig.appid,
                            timeStamp = timestamp,
                            nonceStr  = nonceStr,
                            mypackage = $"prepay_id={prepay_id}",
                            md5sign   = md5sign
                        };

                        string jsApiData = JsonConvert.SerializeObject(jsBridge);

                        //logger.Error("支付步骤json:" + jsApiData);

                        context.Response.Write(jsApiData);

                        #endregion
                    }
                    else
                    {
                        message.msg  = "0";
                        message.data = "";
                        context.Response.Write(JsonConvert.SerializeObject(message));
                    }
                }
            }
            catch (Exception ex)
            {
                message.msg  = "0";
                message.data = "";
                context.Response.Write(JsonConvert.SerializeObject(message));
            }
        }
Exemplo n.º 22
0
        protected void Button3_Click(object sender, EventArgs e)
        {
            string transaction_id = Transaction_id.Text.Trim();
            string out_trade_no   = Out_trade_no.Text.Trim();
            string out_refund_no  = Out_refund_no.Text.Trim();
            string total_fee      = Total_fee.Text.Trim();
            string refund_fee     = Refund_fee.Text.Trim();


            //根据订单id得到支付信息,进而得到公司的微信支付设置信息
            B2b_pay modelb2pay = new B2bPayData().GetPayByoId(out_trade_no.ConvertTo <int>(0));

            if (modelb2pay == null)
            {
                Label1.Text = "支付信息不存在";
                return;
            }

            B2b_finance_paytype model = new B2b_finance_paytypeData().GetFinancePayTypeByComid(modelb2pay.comid);

            if (model == null)
            {
                Label1.Text = "微信支付设置信息不存在";
                return;
            }


            WxPayConfig config = new WxPayConfig
            {
                APPID            = model.Wx_appid,
                APPSECRET        = model.Wx_appkey,
                KEY              = model.Wx_paysignkey,
                MCHID            = model.Wx_partnerid,
                IP               = CommonFunc.GetRealIP(),
                SSLCERT_PATH     = model.wx_SSLCERT_PATH,
                SSLCERT_PASSWORD = model.wx_SSLCERT_PASSWORD,
                PROXY_URL        = "http://115.28.38.65:80",
                LOG_LEVENL       = 3, //日志级别
                REPORT_LEVENL    = 0  //上报信息配置
            };


            lock (lockobj)
            {
                ////根据商户退款单号 判断退款是否已经申请成功
                //bool issuc = new B2b_pay_wxrefundlogData().JudgerefundByout_refund_no(out_refund_no);

                //string r = "";
                //if (issuc)
                //{
                //    r = "退款已经申请成功";
                //}
                //else
                //{
                //r = Refund.Run(transaction_id, out_trade_no, total_fee, refund_fee, out_refund_no, config);
                //}
                B2b_pay_wxrefundlog refundlog = new B2b_pay_wxrefundlog
                {
                    id             = 0,
                    out_refund_no  = out_refund_no,
                    out_trade_no   = out_trade_no,
                    transaction_id = transaction_id,
                    total_fee      = int.Parse(total_fee),
                    refund_fee     = int.Parse(refund_fee),
                    send_xml       = "",
                    send_time      = DateTime.Parse("1970-01-01 00:00:00"),
                    return_code    = "",
                    return_msg     = "",
                    err_code       = "",
                    err_code_des   = "",
                    refund_id      = "",
                    return_xml     = "",
                    return_time    = DateTime.Parse("1970-01-01 00:00:00"),
                };
                try
                {
                    WxPayData data = new WxPayData();

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

                    string xml   = data.ToXml(config);
                    var    start = DateTime.Now;

                    refundlog.send_xml  = xml;
                    refundlog.send_time = start;

                    int ee = new B2b_pay_wxrefundlogData().Editwxrefundlog(refundlog);
                    refundlog.id = ee;
                    if (ee == 0)
                    {
                        Label1.Text = "记录微信退款日志出错";
                        return;
                    }

                    string r = Refund.Run(transaction_id, out_trade_no, total_fee, refund_fee, out_refund_no, config);



                    string[] str = r.Replace("<br>", ",").Split(',');
                    Dictionary <string, string> dic = new Dictionary <string, string>();
                    foreach (string s in str)
                    {
                        if (s != "")
                        {
                            dic.Add(s.Split('=')[0], s.Split('=')[1]);
                        }
                    }
                    string return_code = dic["return_code"];
                    refundlog.return_code = return_code;
                    if (dic.ContainsKey("return_msg"))
                    {
                        string return_msg = dic["return_msg"];
                        refundlog.return_msg = return_msg;
                    }
                    if (dic.ContainsKey("err_code"))
                    {
                        string err_code = dic["err_code"];
                        refundlog.err_code = err_code;
                    }
                    if (dic.ContainsKey("err_code_des"))
                    {
                        string err_code_des = dic["err_code_des"];
                        refundlog.err_code_des = err_code_des;
                    }
                    if (dic.ContainsKey("refund_id"))
                    {
                        string refund_id = dic["refund_id"];
                        refundlog.refund_id = refund_id;
                    }
                    refundlog.return_xml  = r;
                    refundlog.return_time = DateTime.Now;
                    new B2b_pay_wxrefundlogData().Editwxrefundlog(refundlog);
                    Label1.Text = r;
                }
                catch (Exception ef)
                {
                    Label1.Text = "记录微信退款日志出错:" + ef.Message;
                    return;
                }
            }
        }
Exemplo n.º 23
0
    /**
     *
     * 统一下单
     * @param WxPaydata inputObj 提交给统一下单API的参数
     * @param int timeOut 超时时间
     * @throws WxPayException
     * @return 成功时返回,其他抛异常
     */
    public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6)
    {
        string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        //检测必填参数
        if (!inputObj.IsSet("out_trade_no"))
        {
            throw new Exception("缺少统一支付接口必填参数out_trade_no!");
        }
        else if (!inputObj.IsSet("body"))
        {
            throw new Exception("缺少统一支付接口必填参数body!");
        }
        else if (!inputObj.IsSet("total_fee"))
        {
            throw new Exception("缺少统一支付接口必填参数total_fee!");
        }
        else if (!inputObj.IsSet("trade_type"))
        {
            throw new Exception("缺少统一支付接口必填参数trade_type!");
        }

        //关联参数
        if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
        {
            throw new Exception("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
        }
        if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
        {
            throw new Exception("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
        }

        //异步通知url未设置,则使用配置文件中的url
        if (!inputObj.IsSet("notify_url"))
        {
            inputObj.SetValue("notify_url", ApiHelper.GetWebLocation() + "/api/pay/alinotify");//异步通知url
        }

        inputObj.SetValue("appid", WxPayConfig.APPID);                  //公众账号ID
        inputObj.SetValue("mch_id", WxPayConfig.MCHID);                 //商户号
        inputObj.SetValue("spbill_create_ip", ApiHelper.GetClientIP()); //终端ip
        inputObj.SetValue("nonce_str", GenerateNonceStr());             //随机字符串

        //签名
        inputObj.SetValue("sign", inputObj.MakeSign());
        string xml = "";

        xml = inputObj.ToXml();
        var    start    = DateTime.Now;
        string response = "";

        try
        {
            response = HttpService.Post(xml, url, false, timeOut);
        }
        catch (Exception eeee)
        {
        }
        var end      = DateTime.Now;
        int timeCost = (int)((end - start).TotalMilliseconds);

        WxPayData result = new WxPayData();

        result.FromXml(response);
        ReportCostTime(url, timeCost, result);//测速上报

        return(result);
    }
Exemplo n.º 24
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 = "提交失败,请稍后再试"
                    }));
                }
            }
        }
Exemplo n.º 25
0
        public override void ProcessNotify(Action <NotifyModel> action)
        {
            WxPayData notifyData = GetNotifyData();

            //检查openid和product_id是否返回
            if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "回调数据异常");
                Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            //调统一下单接口,获得下单结果
            string    openid             = notifyData.GetValue("openid").ToString();
            string    product_id         = notifyData.GetValue("product_id").ToString();
            WxPayData unifiedOrderResult = new WxPayData();

            try
            {
                unifiedOrderResult = UnifiedOrder(openid, product_id);
            }
            catch (Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "统一下单失败");
                Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            //若下单失败,则立即返回结果给微信支付后台
            if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "统一下单失败");
                Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            //统一下单成功,则返回成功结果给微信支付后台
            WxPayData data = new WxPayData();

            data.SetValue("return_code", "SUCCESS");
            data.SetValue("return_msg", "OK");
            data.SetValue("appid", WxPayConfig.APPID);
            data.SetValue("mch_id", WxPayConfig.MCHID);
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id"));
            data.SetValue("result_code", "SUCCESS");
            data.SetValue("err_code_des", "OK");
            data.SetValue("sign", data.MakeSign());

            Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
            page.Response.Write(data.ToXml());
            page.Response.End();
        }
Exemplo n.º 26
0
        }                                            //支付成功跳转的地址
        protected void Page_Load(object sender, EventArgs e)
        {
            string  openid       = DTRequest.GetQueryString("openid");
            string  order_no     = DTRequest.GetQueryString("order_no");
            decimal order_amount = 0;            //订单金额
            string  subject1     = string.Empty; //订单备注1
            string  subject2     = string.Empty; //订单备注2

            //检查参数是否正确
            if (string.IsNullOrEmpty(openid) || string.IsNullOrEmpty(order_no))
            {
                Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,获取OPENID参数有误!")));
                return;
            }
            if (order_no.StartsWith("R")) //R开头为在线充值订单
            {
                Model.user_recharge model = new BLL.user_recharge().GetModel(order_no);
                if (model == null)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您充值的订单号不存在或已删除!")));
                    return;
                }
                order_amount = model.amount; //订单金额
                subject1     = "充值订单";
                subject2     = "用户名:" + model.user_name;
            }
            else //B开头为商品订单
            {
                Model.orders model = new BLL.orders().GetModel(order_no);
                if (model == null)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,您支付的订单号不存在或已删除!")));
                    return;
                }
                order_amount = model.order_amount; //订单金额
                subject1     = "商品订单";
                if (model.user_id > 0)
                {
                    subject2 = "用户名:" + model.user_name;
                }
                else
                {
                    subject2 = "匿名用户";
                }
            }

            //JSAPI支付预处理
            try
            {
                //统一下单
                string      sendUrl     = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                JsApiConfig jsApiConfig = new JsApiConfig();
                WxPayData   data        = new WxPayData();
                data.SetValue("body", subject1);                                               //商品描述
                data.SetValue("detail", subject2);                                             //商品详情
                data.SetValue("out_trade_no", order_no);                                       //商户订单号
                data.SetValue("total_fee", (Convert.ToDouble(order_amount) * 100).ToString()); //订单总金额,以分为单位
                data.SetValue("trade_type", "JSAPI");                                          //交易类型
                data.SetValue("openid", openid);                                               //公众账号ID
                data.SetValue("appid", jsApiConfig.AppId);                                     //公众账号ID
                data.SetValue("mch_id", jsApiConfig.Partner);                                  //商户号
                data.SetValue("nonce_str", JsApiPay.GenerateNonceStr());                       //随机字符串
                data.SetValue("notify_url", jsApiConfig.Notify_url);                           //异步通知url
                data.SetValue("spbill_create_ip", DTRequest.GetIP());                          //终端IP
                data.SetValue("sign", data.MakeSign(jsApiConfig.Key));                         //签名
                string    xml       = data.ToXml();                                            //转换成XML
                var       startTime = DateTime.Now;                                            //开始时间
                string    response  = HttpService.Post(xml, sendUrl, false, 6);                //发送请求
                var       endTime   = DateTime.Now;                                            //结束时间
                int       timeCost  = (int)((endTime - startTime).TotalMilliseconds);          //计算所用时间
                WxPayData result    = new WxPayData();
                result.FromXml(response, jsApiConfig.Key);
                JsApiPay.ReportCostTime(sendUrl, timeCost, result);//测速上报

                //获取H5调起JS API参数
                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", result.GetValue("appid"));
                jsApiParam.SetValue("timeStamp", JsApiPay.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", JsApiPay.GenerateNonceStr());
                jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id"));
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign(jsApiConfig.Key));
                wxJsApiParam = jsApiParam.ToJson();

                //支付成功后跳转的URL
                returnUrl = new Web.UI.BasePage().linkurl("payment", "?action=succeed&order_no=" + order_no);
            }
            catch (Exception ex)
            {
                Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("调用JSAPI下单失败,请检查微信授权目录是否已注册!")));
                return;
            }
        }
Exemplo n.º 27
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
        * 
        */
        public 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;
        }
Exemplo n.º 28
0
        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));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var customerValues = postProcessPaymentRequest.Order.DeserializeCustomValues();
            var isJsPay        = false;

            if (_httpContext.Session["isJsPay"] != null)
            {
                isJsPay = _httpContext.Session["isJsPay"].ToString().ToLower() == "true";
            }

            string openId = null;

            if (isJsPay)
            {
                var weiXinAuthentication =
                    _workContext.CurrentCustomer.ExternalAuthenticationRecords.FirstOrDefault(
                        q => q.ProviderSystemName == "ExternalAuth.WeiXin");
                if (weiXinAuthentication != null)
                {
                    openId = weiXinAuthentication.ExternalIdentifier;
                }
                else
                {
                    isJsPay = false;
                }
            }


            string productId, body;
            var    firstProduct = postProcessPaymentRequest.Order.OrderItems.FirstOrDefault();

            if (firstProduct != null)
            {
                productId = firstProduct.Product.Id.ToString(CultureInfo.InvariantCulture);
                body      = firstProduct.Product.GetLocalized(q => q.Name);
            }
            else
            {
                productId = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
                body      = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
            }

            string detail = string.Join(", ",
                                        postProcessPaymentRequest.Order.OrderItems.Select(q => q.Product.GetLocalized(p => p.Name)));
            string orderId = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
            string total   = ((int)(postProcessPaymentRequest.Order.OrderTotal * 100)).ToString(CultureInfo.InvariantCulture);

            var post = new RemotePost();

            post.FormName = "weixinpayment";
            post.Method   = "POST";
            post.Add("orderid", postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture));
            post.Add("total", postProcessPaymentRequest.Order.OrderTotal.ToString("0.00"));
            if (isJsPay && !string.IsNullOrWhiteSpace(openId))
            {
                var jsApiPay = new JsApiPay(_weiXinPaymentSettings, Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "onepagecheckout"));
                jsApiPay.Openid   = openId;
                jsApiPay.TotalFee = total;

                var unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(postProcessPaymentRequest.Order.Id, _webHelper.GetCurrentIpAddress(), _notifyUrl);

                var data = new WxPayData();


                var timestamp = CommonExtension.GetCurrentTimeStamp().ToString();
                var nonceStr  = Guid.NewGuid().ToString("N");



                data.SetValue("appId", _weiXinPaymentSettings.AppId);
                data.SetValue("timeStamp", timestamp);
                data.SetValue("nonceStr", nonceStr);
                data.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                data.SetValue("signType", "MD5");
                var sign = data.MakeSign(_weiXinPaymentSettings.AppSecret);


                post.Add("appId", _weiXinPaymentSettings.AppId);
                post.Add("timeStamp", timestamp);
                post.Add("nonceStr", nonceStr);
                post.Add("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                post.Add("signType", "MD5");
                post.Add("paySign", sign);

                post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/JsApiPayment/");
                post.Post();
            }
            else
            {
                post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/ProcessPayment");
                post.Add("nativeUrl", GetUrlForMethodOne(postProcessPaymentRequest.Order.Id));
                //var result = Unifiedorder(productId, body, detail, orderId, total);
                //post.Add("result", HttpUtility.HtmlEncode(result));
                post.Post();
            }
        }
Exemplo n.º 30
0
        //
        // GET: /Weixin/WXPay/

        // 微信支付授权目录 /weixin/wxpay

        public ActionResult OrderPayView(string orderNo, int?isFullPrice)
        {
            // 校验数据
            if (!String.IsNullOrEmpty(orderNo) && isFullPrice.HasValue)
            {
                if ((isFullPrice.Value != 0 && isFullPrice != 1))
                {
                    return(Content("参数错误!"));
                }

                bool bIsFullPrice = isFullPrice.Value == 1;

                OrderInfo order = OperateContext.Current.BLLSession.IOrderInfoBLL.GetListBy(m => m.OrderNo == orderNo).FirstOrDefault();

                if (order == null || (order.State != 0 && order.State != 1))
                {
                    return(Content("未查询到订单信息或订单已完成!"));
                }

                // 支付金额
                decimal price = bIsFullPrice ? order.BalancePayment : order.DownPayment;

                #region 子订单

                string strRand = "";
                Random rand    = new Random();
                for (int i = 0; i < 6; i++)
                {
                    strRand += rand.Next(0, 10);
                }

                // 生成订单编号
                string newOrderNo = DateTime.Now.ToString("yyyyMMddHHmmss") + strRand;

                OrderItem orderItem = new OrderItem()
                {
                    OrderId        = order.ID,
                    OrderNo        = newOrderNo,
                    Price          = price,
                    BalancePayment = order.BalancePayment - price,
                    State          = 0,
                    CreateTime     = DateTime.Now
                };

                OperateContext.Current.BLLSession.IOrderItemBLL.Add(orderItem);

                #endregion

                order.PayType     = 2;
                order.IsFullPrice = bIsFullPrice;

                int result = OperateContext.Current.BLLSession.IOrderInfoBLL.Modify(order, "Price", "BalancePayment", "PayType", "IsFullPrice");

                if (result == 1)
                {
                    if (Session["OpenID"] == null)
                    {
                        return(Content("获取用户信息失败,请从微信公众账号进入!"));
                    }

                    try
                    {
                        // 微信支付
                        WxPayData data = new WxPayData();
                        data.SetValue("body", order.HouseTitle);                                              //商品描述
                        data.SetValue("attach", "");                                                          //附加数据
                        data.SetValue("out_trade_no", orderItem.OrderNo);                                     //订单号
                        data.SetValue("total_fee", Convert.ToInt32((price * 100)).ToString());                //总金额
                        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("product_id", orderNo);                                                 //商品ID
                        data.SetValue("openid", Session["OpenID"].ToString());

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

                        if (orderResult.GetValue("return_msg").ToString() == "OK" && orderResult.GetValue("result_code").ToString() == "SUCCESS" && orderResult.GetValue("return_code").ToString() == "SUCCESS")
                        {
                            TimeSpan ts        = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                            string   appid     = orderResult.GetValue("appid").ToString();
                            string   timeStamp = Convert.ToInt64(ts.TotalSeconds).ToString();
                            string   nonceStr  = orderResult.GetValue("nonce_str").ToString();
                            string   package   = "prepay_id=" + orderResult.GetValue("prepay_id").ToString();

                            string jsApiTicket = WXJsApiTicket.GetJsApiTicket();
                            if (String.IsNullOrEmpty(jsApiTicket))
                            {
                                return(Content("微信接口权限失效,请重新登录!"));
                            }
                            string strTemp = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + Request.Url.ToString();
                            ViewBag.ConfigSingn = FormsAuthentication.HashPasswordForStoringInConfigFile(strTemp, "SHA1");

                            WxPayData newPayData = new WxPayData();
                            newPayData.SetValue("appId", appid);
                            newPayData.SetValue("timeStamp", timeStamp);
                            newPayData.SetValue("nonceStr", nonceStr);
                            newPayData.SetValue("package", package);
                            newPayData.SetValue("signType", "MD5");

                            string paySign = newPayData.MakeSign();

                            ViewBag.AppID     = appid;
                            ViewBag.TimeStamp = timeStamp;
                            ViewBag.NonceStr  = nonceStr;
                            ViewBag.Package   = package;
                            ViewBag.PaySign   = paySign;
                            return(View());
                        }
                        else
                        {
                            ViewBag.IsFail = "1";
                            return(View());
                        }
                    }
                    catch (Exception)
                    {
                        ViewBag.IsFail = "1";
                        return(View());
                    }
                }
            }

            return(Content("请使用正确方式提交订单!"));
        }
Exemplo n.º 31
0
        public ActionResult GetRedPacket()
        {
            ViewBag.state = "2";
            ViewBag.err   = "";
            string flow    = Request["flow"];
            string redcode = Request["redcode"];
            string rurl    = Request["rurl"];//成功后的返回页
            //红包相关检测
            M_WX_RedDetail detMod = new M_WX_RedDetail();

            try
            {
                detMod = detBll.SelModelByCode(redcode);
                M_UserAPP uaMod = uaBll.SelModelByUid(mu.UserID, "wechat");
                if (detMod == null)
                {
                    ViewBag.err = "红包不存在";
                }
                else if (detMod.ZStatus != 1)
                {
                    ViewBag.err = "该红包已经被使用";
                }
                else if (detMod.Amount < 1 || detMod.Amount > 200)
                {
                    ViewBag.err = "红包金额不正确";
                }
                if (!string.IsNullOrEmpty(ViewBag.err))
                {
                    return(View("RedPacket"));
                }
                M_WX_RedPacket redMod = redBll.SelReturnModel(detMod.MainID);
                if (!redMod.Flow.Equals(flow))
                {
                    ViewBag.err = "匹配码不正确";
                }
                else if (redMod.SDate > DateTime.Now)
                {
                    ViewBag.err = "活动尚未开始";
                }
                else if (redMod.EDate < DateTime.Now)
                {
                    ViewBag.err = "活动已经结束";
                }
                if (!string.IsNullOrEmpty(ViewBag.err))
                {
                    return(View("RedPacket"));
                }
                WxAPI api = WxAPI.Code_Get(redMod.AppID);
                WxAPI.AutoSync(Request.RawUrl, api.AppId);
                if (mu.IsNull)
                {
                    ViewBag.err = "用户不存在";
                }
                if (uaMod == null)
                {
                    ViewBag.err = "用户信息不存在";
                }
                if (!string.IsNullOrEmpty(ViewBag.err))
                {
                    return(View("RedPacket"));
                }
                //-------------------
                string apiUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
                //生成提交参数
                WxPayData wxdata = new WxPayData();
                wxdata.SetValue("nonce_str", WxAPI.nonce);
                wxdata.SetValue("mch_billno", api.AppId.Pay_AccountID + DateTime.Now.ToString("yyyyMMdd") + function.GetRandomString(10, 2));
                wxdata.SetValue("mch_id", api.AppId.Pay_AccountID);
                wxdata.SetValue("wxappid", api.AppId.APPID);
                wxdata.SetValue("send_name", SiteConfig.SiteInfo.SiteName);
                //接受红包的用户用户在wxappid下的openid
                wxdata.SetValue("re_openid", uaMod.OpenID);//oDTTbwLa7WuySP0WcJJzYJmErCQ4
                wxdata.SetValue("total_amount", (int)(detMod.Amount * 100));
                wxdata.SetValue("total_num", 1);
                wxdata.SetValue("wishing", redMod.Wishing);   //红包祝福语
                wxdata.SetValue("client_ip", "58.215.75.11"); //调用接口的机器IP地址
                wxdata.SetValue("act_name", redMod.Name);     //活动名称
                wxdata.SetValue("remark", redMod.Remind);
                wxdata.SetValue("sign", wxdata.MakeSign());
                //随机码,签名
                string xml      = wxdata.ToXml();
                string response = HttpService.Post(xml, apiUrl, true, 60, api.AppId);
                //------------------------发放完成(不论成功失败均算已领取,记录好返回)
                detMod.UserID   = mu.UserID;
                detMod.UserName = mu.UserName;
                detMod.UseTime  = DateTime.Now.ToString();
                //WxPayData result = new WxPayData(api.AppId.Pay_Key);
                //result.FromXml(response);
                //if (result.GetValue("return_code").ToString().Equals("SUCCESS"))//return_msg
                //{
                //    detMod.ZStatus = 99;
                //}
                //else
                //{
                //    detMod.ZStatus = -1;
                //    detMod.Remind = response;
                //}
                detMod.ZStatus = 99; detMod.Remind = response;
                detBll.UpdateByID(detMod);
                ViewBag.state  = "3";
                ViewBag.amount = detMod.Amount.ToString("f2");
                return(View("RedPacket"));
            }
            catch (Exception ex)
            {
                ZLLog.L(ZLEnum.Log.pay, "微信红包异常,领取码:" + redcode + ",原因:" + ex.Message);
                ViewBag.state = "3";
                ViewBag.err   = ex.Message;
                //如异常,该红包禁用,等待管理员审核
                detMod.ZStatus = -1;
                detMod.Remind  = ex.Message;
                detBll.UpdateByID(detMod);
                return(View("RedPacket"));
            }
        }
Exemplo n.º 32
0
Arquivo: WxPay.cs Projeto: 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);
        }
Exemplo n.º 33
0
        }                                            //支付成功跳转的地址
        protected void Page_Load(object sender, EventArgs e)
        {
            string  openid       = DTRequest.GetQueryString("openid");
            string  order_no     = DTRequest.GetQueryString("order_no");
            decimal order_amount = 9.28M;  //订单金额
            string  subject1     = "在线支付"; //订单备注1
            string  subject2     = "在线支付"; //订单备注2

            //检查参数是否正确
            if (string.IsNullOrEmpty(openid) || string.IsNullOrEmpty(order_no))
            {
                Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode("对不起,获取OPENID参数有误!")));
                return;
            }


            //JSAPI支付预处理
            try
            {
                //统一下单
                string      sendUrl     = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                JsApiConfig jsApiConfig = new JsApiConfig();
                WxPayData   data        = new WxPayData();
                data.SetValue("body", subject1);                                               //商品描述
                data.SetValue("detail", subject2);                                             //商品详情
                data.SetValue("out_trade_no", order_no);                                       //商户订单号
                data.SetValue("total_fee", (Convert.ToDouble(order_amount) * 100).ToString()); //订单总金额,以分为单位
                data.SetValue("trade_type", "JSAPI");                                          //交易类型
                data.SetValue("openid", openid);                                               //公众账号ID
                data.SetValue("appid", jsApiConfig.AppId);                                     //公众账号ID
                data.SetValue("mch_id", jsApiConfig.Partner);                                  //商户号
                data.SetValue("nonce_str", JsApiPay.GenerateNonceStr());                       //随机字符串
                data.SetValue("notify_url", jsApiConfig.Notify_url);                           //异步通知url
                data.SetValue("spbill_create_ip", DTRequest.GetIP());                          //终端IP
                data.SetValue("sign", data.MakeSign(jsApiConfig.Key));                         //签名
                string    xml       = data.ToXml();                                            //转换成XML
                var       startTime = DateTime.Now;                                            //开始时间
                string    response  = HttpService.Post(xml, sendUrl, false, 6);                //发送请求
                var       endTime   = DateTime.Now;                                            //结束时间
                int       timeCost  = (int)((endTime - startTime).TotalMilliseconds);          //计算所用时间
                WxPayData result    = new WxPayData();
                result.FromXml(response, jsApiConfig.Key);
                JsApiPay.ReportCostTime(sendUrl, timeCost, result);//测速上报
                LogHelper.WriteDebugLog("[pay]:" + result.ToString());
                //获取H5调起JS API参数
                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", result.GetValue("appid"));
                jsApiParam.SetValue("timeStamp", JsApiPay.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", JsApiPay.GenerateNonceStr());
                jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id"));
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign(jsApiConfig.Key));
                wxJsApiParam = jsApiParam.ToJson();

                LogHelper.WriteDebugLog("[ApiParam]:" + jsApiParam.ToJson());
                //支付成功后跳转的URL
                returnUrl = new Web.UI.BasePage().linkurl("payment", "?action=succeed&order_no=" + order_no);
                //Response.Redirect(returnUrl);
            }
            catch (Exception ex)
            {
                Response.Redirect(new Web.UI.BasePage().linkurl("error", "?msg=" + Utils.UrlEncode(ex.Message)));
                return;
            }
        }