Exemple #1
0
        /** 获取带参数的请求URL  @return String */
        public virtual string getRequestURL()
        {
            this.createSign();

            StringBuilder sb    = new StringBuilder();
            ArrayList     akeys = new ArrayList(parameters.Keys);

            akeys.Sort();
            foreach (string k in akeys)
            {
                string v = (string)parameters[k];
                if (null != v && "key".CompareTo(k) != 0)
                {
                    sb.Append(k + "=" + TenpayUtil.UrlEncode(v, getCharset()) + "&");
                }
            }

            //去掉最后一个&
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }

            return(this.getGateUrl() + "?" + sb.ToString());
        }
Exemple #2
0
        public virtual string getRequestURL()
        {
            this.createSign();
            StringBuilder builder = new StringBuilder();
            ArrayList     list    = new ArrayList(this.parameters.Keys);

            list.Sort();
            foreach (string str in list)
            {
                string instr = (string)this.parameters[str];
                if (((instr != null) && ("key".CompareTo(str) != 0)) && ("spbill_create_ip".CompareTo(str) != 0))
                {
                    builder.Append(str + "=" + TenpayUtil.UrlEncode(instr, this.getCharset()) + "&");
                }
                else if ("spbill_create_ip".CompareTo(str) == 0)
                {
                    builder.Append(str + "=" + instr.Replace(".", "%2E") + "&");
                }
            }
            if (builder.Length > 0)
            {
                builder.Remove(builder.Length - 1, 1);
            }
            return(this.getGateUrl() + "?" + builder.ToString());
        }
Exemple #3
0
        /// <summary>
        /// 同步关注公众号的用户到数据库
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            LogHelper.WriteInfoLog("开始同步微信用户信息...");
            TenpayUtil tp = new TenpayUtil();
            WxUserBll userBll = new WxUserBll();
            #region 获取关注订阅号的用户openid列表
            string token = tp.GetAccessToken();
            string rsp1 = HttpHelper.GetResponse(
                            "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token
                            );
            if (rsp1.Contains("errcode"))
                return;

            UserListJsonResult jsob = JsonConvert.DeserializeObject<UserListJsonResult>(rsp1);
            List<string> openidList = jsob.data.openid;
            #endregion
            foreach (var openid in openidList)
            {
                #region 获取用户基本信息
                string rsp2 =
                    HttpHelper.GetResponse("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token +
                                           "&openid=" + openid + "&lang=zh_CN ");//限制500w次/每天
                if (rsp1.Contains("errcode"))
                    continue;

                WxUserInfo user = JsonConvert.DeserializeObject<WxUserInfo>(rsp2);
                #endregion
                #region 同步用户信息
                //upsert
                var u = userBll.SearchUserByOpenid(user);
                if (u == null)
                {
                    userBll.UpdateUserInfo(user);
                }
                else
                {
                    userBll.InsertUser(user);
                }
                #endregion
            }
            if (jsob.total > 10000)
            {
                LogHelper.WriteInfoLog("卧槽,粉丝过万了!程序该升级了...");
            }
        }
Exemple #4
0
        protected void btn_setKf_Click(object sender, EventArgs e)
        {
            string token = new TenpayUtil().GetAccessToken();
            string account = txt_account.Text.Trim();
            string name = txt_Name.Text.Trim();
            string psd = Md5Helper.SpMd5(txt_psd.Text.Trim());

            string data = "{";
            data += "\"kf_account\" : \"" + account + "\",";
            data += "\"nickname\" : \"" + name + "\",";
            data += "\"password\" : \"" + psd + "\"";
            data+="}";
            string rst =
                TenpayUtil.PostDataToUrl("https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" + token,
                    data);

            Response.Write("添加客服信息返回:" + rst);
        }
Exemple #5
0
        public override void setContent(string content)
        {
            this.content = content;

            Regex r = new Regex("window.location.href[ \t]*=[ \t]*[\'\"]([^\'\"]*)[\'\"]", RegexOptions.IgnoreCase);
            Match m = r.Match(content);

            if (m.Success)
            {
                string url = m.Groups[1].ToString();

                char[] seps1 = new char[] { '?' };
                char[] seps2 = new char[] { '&' };
                char[] seps3 = new char[] { '=' };

                string[] urls = url.Split(seps1);
                if (urls != null && urls.Length >= 2)
                {
                    string[] paras = urls[1].Split(seps2);
                    foreach (string para in paras)
                    {
                        string[] kav = para.Split(seps3);
                        if (kav.Length == 2)
                        {
                            this.setParameter(kav[0], TenpayUtil.UrlDecode(kav[1], this.getCharset()));
                        }
                    }
                }
                else
                {
                    this.setParameter("pay_result", "99");
                    this.setParameter("pay_info", "返回包格式错误,请检查协议是否改变!");
                }
            }
            else
            {
                this.setParameter("pay_result", "99");
                this.setParameter("pay_info", "返回包格式错误,请检查协议是否改变!");
            }
        }
        protected override string GetAjaxResult(HttpContext context)
        {
            string timestamp = TenpayUtil.GetTimestamp();//生成签名的时间戳
            string nonceStr = TenpayUtil.GetNoncestr();//生成签名的随机串
            string page = context.Request["Pagepath"];
            string url = "http://ck-sh.com/ck/" + page;//当前的地址
            string accsToken = new TenpayUtil().GetAccessToken();
            string appid = ConfigurationManager.AppSettings["AppId"];

            string jsapiTicke;
            //ticket 缓存7200秒
            if (context.Session["jsapi_ticket"] == null)
            {
                jsapiTicke =
                HttpHelper.WxApiPost(
                    "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accsToken + "&type=jsapi", "");
                context.Session["jsapi_ticket"] = jsapiTicke;
                context.Session.Timeout = 7200;
            }
            else
            {
                jsapiTicke = context.Session["jsapi_ticket"].ToString();
            }

            Dictionary<string, object> respDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsapiTicke);
            jsapiTicke = respDic["ticket"].ToString();//获取ticket
            string[] arrayList = { "jsapi_ticket=" + jsapiTicke, "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + url };
            Array.Sort(arrayList);
            string signature = string.Join("&", arrayList);
            LogHelper.WriteInfoLog("加密前的signature:" + signature);
            signature = FormsAuthentication.HashPasswordForStoringInConfigFile(signature, "SHA1").ToLower();
            string rst = "{\"appId\":\"" + appid + "\", \"timestamp\":" + timestamp + ",\"nonceStr\":\"" + nonceStr +
                         "\",\"signature\":\"" + signature + "\"}";
            LogHelper.WriteInfoLog("获取JsApi权限配置的参数--" + rst);
            return rst;
        }
Exemple #7
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (IsNum(Request.QueryString["s"]))
            {
                SiteId = Request.QueryString["s"];
                Member_Valicate MCheck = new Member_Valicate();
                MCheck.Member_Check(true, int.Parse(SiteId));
                UserName = MCheck._UserName;
            }
            else
            {
                UserName = "";
                SiteId   = "";
                Response.Write("<script type='text/javascript'>alert('invalid siteid!');</script>");
                Response.End();
            }

            if (IsFloat(Request.Form["pay_fee"]))
            {
                Get_TenPay();
                float Total_Fee = float.Parse(Request.Form["pay_fee"]) * 100;

                //当前时间 yyyyMMdd
                string date = DateTime.Now.ToString("yyyyMMdd");

                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                string strReq = "" + DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(4);

                //商户订单号,不超过32位,财付通只做记录,不保证唯一性
                string sp_billno = DateTime.Now.ToString("yyyyMMddHHmmss") + TenpayUtil.BuildRandomStr(4);

                //财付通订单号,10位商户号+8位日期+10位序列号,需保证全局唯一
                string transaction_id = bargainor_id + date + strReq;
                string return_url     = "http://" + url + "/e/member/onlinepay/tenpay/return_url.aspx";

                //创建PayRequestHandler实例
                PayRequestHandler reqHandler = new PayRequestHandler(Context);

                //设置密钥
                reqHandler.setKey(key);

                //初始化
                reqHandler.init();

                //-----------------------------
                //设置支付参数
                //-----------------------------
                reqHandler.setParameter("bargainor_id", bargainor_id);                  //商户号
                reqHandler.setParameter("sp_billno", sp_billno);                        //商家订单号
                reqHandler.setParameter("transaction_id", transaction_id);              //财付通交易单号
                reqHandler.setParameter("return_url", return_url);                      //支付通知url
                reqHandler.setParameter("desc", "订单号:" + transaction_id);               //商品名称
                reqHandler.setParameter("total_fee", Total_Fee.ToString("f0"));         //商品金额,以分为单位
                reqHandler.setParameter("cs", "utf-8");
                reqHandler.setParameter("attach", UserName + "," + SiteId);
                reqHandler.setParameter("spbill_create_ip", Page.Request.UserHostAddress);       //用户ip,测试环境时不要加这个ip参数,正式环境再加此参数
                string requestUrl = reqHandler.getRequestURL();
                Response.Redirect(requestUrl);

                //获取请求带参数的url

                /*
                 * string a_link = "<a target=\"_blank\" href=\"" + requestUrl + "\">" + "财付通支付" + "</a>";
                 *
                 * Response.Write(a_link);
                 */

                //post实现方式

                /*
                 * reqHandler.getRequestURL();
                 * Response.Write("<form method=\"post\" action=\""+ reqHandler.getGateUrl() + "\" >\n");
                 * Hashtable ht = reqHandler.getAllParameters();
                 * foreach(DictionaryEntry de in ht)
                 * {
                 *      Response.Write("<input type=\"hidden\" name=\"" + de.Key + "\" value=\"" + de.Value + "\" >\n");
                 * }
                 * Response.Write("<input type=\"submit\" value=\"财付通支付\" >\n</form>\n");
                 */

                //获取debug信息
                //string debuginfo = reqHandler.getDebugInfo();
                //Response.Write("<br/>" + debuginfo + "<br/>");

                //重定向到财付通支付
                //reqHandler.doSend();
            }
        }
        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);
        }