예제 #1
0
        /// <summary>
        /// 获取code_url  扫二维码支付使用
        /// </summary>
        public static string getCode_url(UnifiedOrder order, string key)
        {
            string code_url     = "";
            string post_data    = getUnifiedOrderXml(order, key);
            string request_data = PostXmlToUrl(UnifiedPayUrl, post_data);



            SortedDictionary <string, string> requestXML = GetInfoFromXml(request_data);

            foreach (KeyValuePair <string, string> k in requestXML)
            {
                if (k.Key == "code_url")
                {
                    code_url = k.Value;
                    break;
                }
            }
            return(code_url);
        }
예제 #2
0
        /// <summary>
        /// 获取prepay_id
        /// </summary>
        public static string getPrepay_id(UnifiedOrder order, string key)
        {
            string prepay_id    = "";
            string post_data    = getUnifiedOrderXml(order, key);
            string request_data = PostXmlToUrl(UnifiedPayUrl, post_data);



            SortedDictionary <string, string> requestXML = GetInfoFromXml(request_data);

            foreach (KeyValuePair <string, string> k in requestXML)
            {
                if (k.Key == "prepay_id")
                {
                    prepay_id = k.Value;
                    break;
                }
            }
            return(prepay_id);
        }
예제 #3
0
        /// <summary>
        /// 微信统一下单接口xml参数整理
        /// </summary>
        /// <param name="order">微信支付参数实例</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        protected static string getUnifiedOrderXml(UnifiedOrder order, string key)
        {
            string return_string = string.Empty;
            SortedDictionary <string, string> sParams = new SortedDictionary <string, string>();

            sParams.Add("appid", order.appid);
            sParams.Add("attach", order.attach);
            sParams.Add("body", order.body);
            sParams.Add("device_info", order.device_info);
            sParams.Add("mch_id", order.mch_id);
            sParams.Add("nonce_str", order.nonce_str);
            sParams.Add("notify_url", order.notify_url);
            sParams.Add("openid", order.openid);
            sParams.Add("out_trade_no", order.out_trade_no);
            sParams.Add("spbill_create_ip", order.spbill_create_ip);
            sParams.Add("total_fee", order.total_fee.ToString());
            sParams.Add("trade_type", order.trade_type);
            order.sign = getsign(sParams, key);
            sParams.Add("sign", order.sign);


            //    <xml>
            //    <sign></sign>
            //    <mch_billno></mch_billno>
            //    <mch_id></mch_id>
            //    <wxappid></wxappid>
            //    <nick_name></nick_name>
            //    <send_name></send_name>
            //    <re_openid></re_openid>
            //    <total_amount></total_amount>
            //    <min_value></min_value>
            //    <max_value></max_value>
            //    <total_num></total_num>
            //    <wishing></wishing>
            //    <client_ip></client_ip>
            //    <act_name></act_name>
            //    <act_id></act_id>
            //    <remark></remark>
            //    <logo_imgurl></logo_imgurl>
            //    <share_content></share_content>
            //</xml>

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();

            foreach (KeyValuePair <string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
            byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
            return_string = Encoding.GetEncoding("GBK").GetString(byteArray);
            return(return_string);
        }
예제 #4
0
        /// <summary>
        /// 微信统一下单接口xml参数整理
        /// </summary>
        /// <param name="order">微信支付参数实例</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        private string getUnifiedOrderXml(UnifiedOrder order, string key)
        {
            string return_string = string.Empty;
            SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
            sParams.Add("appid", order.appid);
            sParams.Add("attach", order.attach);
            sParams.Add("body", order.body);
            sParams.Add("device_info", order.device_info);
            sParams.Add("mch_id", order.mch_id);
            sParams.Add("nonce_str", order.nonce_str);
            sParams.Add("notify_url", order.notify_url);
            sParams.Add("openid", order.openid);
            sParams.Add("out_trade_no", order.out_trade_no);
            sParams.Add("spbill_create_ip", order.spbill_create_ip);
            sParams.Add("total_fee", order.total_fee.ToString());
            sParams.Add("trade_type", order.trade_type);
            order.sign = CreateSign(sParams, key);
            sParams.Add("sign", order.sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();
            foreach (KeyValuePair<string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
            byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
            return_string = Encoding.GetEncoding("GBK").GetString(byteArray);
            return return_string;

        }
예제 #5
0
 /// <summary>
 /// 获取prepay_id
 /// </summary>
 public string getPrepay_id(UnifiedOrder order, string key)
 {
     string prepayId = "";
     string postData = getUnifiedOrderXml(order, key);
     LogHelper.WriteInfoLog("微信支付统一接口post请求data:" + postData);
     string requestData = PostDataToUrl(UnifiedPayUrl, postData);
     LogHelper.WriteInfoLog("微信支付统一接口post请求返回:" + requestData);
     SortedDictionary<string, string> requestXML = GetInfoFromXml(requestData);
     foreach (KeyValuePair<string, string> k in requestXML)
     {
         if (k.Key == "prepay_id")
         {
             prepayId = k.Value;
             break;
         }
     }
     return prepayId;
 }
예제 #6
0
        protected override string GetAjaxResult(HttpContext context)
        {
            PayLogBll payBll = new PayLogBll();
            var rsp = new object();

            string action = context.Request["action"];
            string baseUrl = ConfigurationManager.AppSettings["BaseUrl"];
            //三段逻辑:发起支付、支付成功、支付失败
            switch (action)
            {
                case "0": //发起支付:由payOrder.aspx调用

                    #region 准备微信支付所需参数

                    #region 相关配置参数

                    TenpayUtil tenpay = new TenpayUtil();
                    string paySignKey = ConfigurationManager.AppSettings["PaySignKey"];
                    string appSecret = ConfigurationManager.AppSettings["AppSecret"];
                    string mchId = ConfigurationManager.AppSettings["mch_id"];
                    string appId = ConfigurationManager.AppSettings["AppId"];

                    #endregion

                    #region 获取前台传值

                    string code = context.Request["code"];
                    string state = context.Request["state"]; //支付金额_报名开始时间_报名截止时间,例如:1_2016-01-01
                    string[] strState = state.Split('_');
                    string school = context.Request["schoolName"];
                    string nm = context.Request["name"];
                    string sex = context.Request["sx"];
                    string identity = context.Request["id"];
                    string telNo = context.Request["tel"];

                    #endregion

                    #region 活动时间过期判断

                    DateTime endTime = Convert.ToDateTime(strState[1]);
                    if (DateTime.Now > endTime)
                        throw new Exception("亲,本次活动报名已经结束啦,请您继续关注休行最新活动!");

                    #endregion

                    #region 用户报名重复验证

                    PayLogInfo p0 = new PayLogInfo { IdentityNo = identity };
                    var payList = payBll.SearchLogById(p0);
                    if (payList.Count > 0)
                    {
                        DateTime dt = DateTime.Now; //当前时间        
                        DateTime startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d"))).Date;
                        //本周周一  
                        var lst1 = payList.Where(i => i.CreateTime > startWeek).ToList();
                        var lst2 = lst1.Where(i => i.PayStatus == 1).ToList();
                        if (lst2.Count > 0)
                        {
                            throw new Exception("亲,您已经报过名啦");
                        }
                    }

                    #endregion

                    #region 根据code获取用户openid

                    string postData = "appid=" + appId + "&secret=" + appSecret + "&code=" + code +
                                      "&grant_type=authorization_code";
                    string requestData = TenpayUtil.PostDataToUrl(TenpayUtil.getOauth2Access_tokenUrl(), postData);
                    LogHelper.WriteInfoLog("获取用户openid返回:" + requestData);
                    Authorization auth = JsonConvert.DeserializeObject<Authorization>(requestData);
                    //将json数据转化为对象类型并赋值给auth

                    #endregion

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

                    #region 通过统一支付接口获取JSAPI支付所需的prepay_id

                    UnifiedOrder order = new UnifiedOrder();
                    order.appid = appId;
                    order.attach = "vinson";
                    order.body = "报名费用";
                    order.device_info = telNo;
                    order.mch_id = mchId;
                    order.nonce_str = TenpayUtil.GetNoncestr();
                    order.notify_url = baseUrl + "WxCallback.aspx";
                    order.openid = auth.openid;
                    order.out_trade_no = "ck" + timeStamp;
                    order.trade_type = "JSAPI";
                    order.spbill_create_ip = context.Request.UserHostAddress;
                    order.total_fee = int.Parse(strState[0]);
                    //order.total_fee = 600;
                    string prepayId = tenpay.getPrepay_id(order, paySignKey);

                    #endregion

                    LogHelper.WriteInfoLog("prepay_id:" + prepayId);

                    #region 获取微信sign

                    SortedDictionary<string, string> sParams = new SortedDictionary<string, string>
                        {
                            {"appId", appId},
                            {"timeStamp", timeStamp},
                            {"nonceStr", nonceStr},
                            {"package", "prepay_id=" + prepayId},
                            {"signType", "MD5"}
                        };
                    var paySign = TenpayUtil.CreateSign(sParams, paySignKey);

                    #endregion

                    #endregion

                    #region 支付记录入库

                    Task tk = new Task(() =>
                    {
                        PayLogInfo paylog = new PayLogInfo
                        {
                            CustName = nm,
                            IdentityNo = identity,
                            OpenId = auth.openid,
                            PayMoney = order.total_fee / 100.0,
                            SchoolName = school,
                            Sex = int.Parse(sex),
                            TelNo = telNo,
                            TradeNo = order.out_trade_no,
                            PayStatus = 0,
                            CreateTime = DateTime.Now, //切记:mongogdb中显示的是GMT时间
                            Remark = "初始"
                        };
                        payBll.InsertLog(paylog);
                    });
                    tk.Start();

                    #endregion

                    LogHelper.WriteInfoLog("paySign:" + paySign);
                    //由pay.aspx页面发起微信支付请求
                    string url = baseUrl + "pay.aspx?showwxpaytitle=1&appId=" + appId + "&timeStamp=" + timeStamp +
                                 "&nonceStr=" + nonceStr + "&prepay_id=" + prepayId + "&signType=MD5&paySign=" +
                                 paySign +
                                 "&OrderID=" + order.out_trade_no;
                    rsp = new { ErrCode = "0000", WxPayUrl = url };
                    break;
                case "1": //支付成功:由pay.aspx调用
                    string orderId1 = context.Request["orderId"];
                    PayLogInfo p1 = new PayLogInfo { TradeNo = orderId1 };
                    var rst1 = payBll.SearchLogByOrderId(p1); //获取支付记录
                    Task t = new Task(() =>
                    {
                        rst1.PayStatus = 1;
                        rst1.Remark = "支付成功";
                        payBll.UpdaPayLogInfo(rst1); //更新支付状态

                        #region 发送报名成功消息

                        string openid = rst1.OpenId;
                        string content = string.Format(ConfigurationManager.AppSettings["SMsg"], rst1.CustName, rst1.SchoolName, rst1.IdentityNo, rst1.TelNo);//短信模板
                        string token = new TenpayUtil().GetAccessToken();
                        string data = "{";
                        data += "\"touser\" : \"" + openid + "\",";
                        data += "\"msgtype\" : \"text\",";
                        data += "\"text\" : {\"content\":\"" + content + "\"}";
                        data += "}";


                        HttpHelper.PostData(
                            "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token,
                            data);

                        #endregion
                    });
                    t.Start();
                    rsp =
                        new
                        {
                            ErrCode = "0000",
                            WxPayUrl =
                                baseUrl + "success.aspx?n=" + rst1.CustName + "&&o=" + rst1.TradeNo + "&&m=" +
                                rst1.PayMoney
                        };
                    break;
                case "2": //支付失败:由pay.aspx调用
                    string orderId2 = context.Request["orderId"];
                    string errMsg = context.Request["ErrMsg"];
                    PayLogInfo p2 = new PayLogInfo { TradeNo = orderId2 };
                    var rst2 = payBll.SearchLogByOrderId(p2);
                    if (rst2.PayStatus == 1)
                    {
                        //用户支付成功后点击返回依然跳成功页面
                        rsp = new
                        {
                            ErrCode = "0000",
                            WxPayUrl =
                                baseUrl + "success.aspx?n=" + rst2.CustName + "&&o=" + rst2.TradeNo + "&&m=" +
                                rst2.PayMoney
                        };
                    }
                    else
                    {
                        rst2.PayStatus = -1;
                        rst2.Remark = "支付失败:" + errMsg;//数据库中保存详细错误信息
                        string showMsg = "支付失败";//默认显示
                        if (errMsg == "get_brand_wcpay_request:cancel")
                            showMsg = "取消支付";
                        payBll.UpdaPayLogInfo(rst2);
                        rsp = new { ErrCode = "0000", WxPayUrl = baseUrl + "fail.aspx?msg=" + showMsg };
                    }
                    break;
            }

            return JsonConvert.SerializeObject(rsp);
        }