private void save() { if (base.e_usertype != Common.enumUserType.host && base.e_usertype != Common.enumUserType.admin) { Response.Write("<script>alert('你没有编辑此分站信息的权限');history.go(-1);</script>"); return; } wx_configInfo pinfo = new wx_configInfo(); pinfo.AppId = txbAppId.Text.Trim(); pinfo.MchId = txbMchId.Text.Trim(); pinfo.AppKey = txbAppKey.Text.Trim(); pinfo.AppSecret = txbAppSecret.Text.Trim(); string resultmsg = ""; int result = wx_configBLL.edit(pinfo, ref resultmsg); if (result > 0) { bind(); Response.Write("<script>alert('保存成功');</script>"); } else { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), DateTime.Now.ToString(), "alert('保存失败," + resultmsg.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true); } }
/// <summary> /// 处理请求,产生响应 /// </summary> /// <returns></returns> public string Response() { cinfo = BLL.wx_configBLL.getInfo(); if (cinfo == null) { return("微信配置参数未填写"); } string method = Request.HttpMethod.ToUpper(); //验证签名 if (method == "GET") { if (CheckSignature()) { return(Request.QueryString[ECHOSTR]); } else { return("error"); } } //处理消息 if (method == "POST") { return(ResponseMsg()); } else { return("无法处理"); } }
/// <summary> /// 发布 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnrelease_Click(object sender, EventArgs e) { try { wx_configInfo cinfo = wx_configBLL.getInfo(); if (cinfo == null) { Response.Write("<script>parent.fail('参数未配置');</script>"); return; } string AccessToken = com.weixin.Utility.Context.GetAccessToken(cinfo.AppId, cinfo.AppSecret); string strHtml = BLL.wx_diymenuBLL.getjson(); //Common.LogUtil.WriteLog("", "微信菜单生成xml_", strHtml); string result = com.weixin.Menu.MenuManager.CreateMenu(strHtml.ToString(), AccessToken); //System.Xml.Linq.XDocument doc = com.weixin.Utility.XmlUtility.ParseJson(result, "root"); //System.Xml.Linq.XElement root = doc.Root; JObject resultjo = (JObject)JsonConvert.DeserializeObject(result); if (resultjo != null) { string errcode = resultjo["errcode"] != null ? resultjo["errcode"].ToString() : ""; string errmsg = resultjo["errmsg"] != null ? resultjo["errmsg"].ToString() : ""; //string errcode = root.Element("errcode").Value; //string errmsg = root.Element("errmsg").Value; if (errcode.ToString() == "0") { Response.Write("<script>parent.success('发布成功');</script>"); return; } else { Response.Write("<script>parent.fail('发布失败," + errmsg + "');</script>"); return; } } else { Response.Write("<script>parent.fail('发布失败');</script>"); return; } } catch (Exception exc) { Response.Write("<script>parent.fail('" + exc.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');</script>"); } }
/// <summary> /// 判断用户是否已经创建,如果创建则修改账户的状态,没有则创建新用户 /// </summary> /// <param name="FromUserName"></param> /// <param name="lng"></param> /// <param name="lat"></param> /// <param name="SourceType">用户来源:1平台自然发展,2分销商发展</param> /// <param name="SourceID">用户来源ID:SourceType=1时为0,SourceType=2时为分销商ID</param> /// <returns></returns> public static int CreateUser(string FromUserName, string lng, string lat, int SourceType, string SourceID) { wx_configInfo cinfo = wx_configBLL.getInfo(); if (cinfo != null) { FileUtility.WriteLog("获取分站信息错误:" + DateTime.Now.ToString() + " \r\n"); return(0); } string AccessToken = Context.GetAccessToken(cinfo.AppId, cinfo.AppSecret); if (AccessToken.Trim().Length == 0) { FileUtility.WriteLog("创建用户失败AccessToken为空 \r\n"); return(0); } return(CreateUser(FromUserName, AccessToken, cinfo.AppId, cinfo.AppSecret, lng, lat, SourceType, SourceID)); }
private void bind() { if (base.e_usertype != Common.enumUserType.host && base.e_usertype != Common.enumUserType.admin) { Response.Write("<script>alert('你没有编辑此分站信息的权限');history.go(-1);</script>"); Response.End(); } wx_configInfo pinfo = wx_configBLL.getInfo(); if (pinfo != null) { txbAppId.Text = pinfo.AppId; txbMchId.Text = pinfo.MchId; txbAppKey.Text = pinfo.AppKey; txbAppSecret.Text = pinfo.AppSecret; txbToken.Text = pinfo.Token; //string zm = DESEncrypt.Encrypt(id).ToLower(); //string jm = DESEncrypt.Decrypt(zm); //str = "companyid:" + id + " 加密后:" + zm + " 解密后:" + jm; txbwxapiurl.Text = Common.Constant.Get_Host() + "/api/weixin.ashx"; } }
/// <summary> /// 获取当前用户的微信 OpenId,如果知道用户的OpenId请不要使用该函数 /// </summary> private void GetUserOpenId() { wx_configInfo cinfo = wx_configBLL.getInfo(); if (cinfo == null) { Response.Write("<script>alert('微信参数未设置');history.go(-1);</script>"); return; } if (cinfo.AppId == null || cinfo.AppId.Trim().Length == 0) { Response.Write("<script>alert('微信参数AppId未设置');history.go(-1);</script>"); return; } if (cinfo.MchId == null || cinfo.MchId.Trim().Length == 0) { Response.Write("<script>alert('微信参数MchId未设置');history.go(-1);</script>"); return; } if (cinfo.AppKey == null || cinfo.AppKey.Trim().Length == 0) { Response.Write("<script>alert('微信参数AppKey未设置');history.go(-1);</script>"); return; } if (cinfo.AppSecret == null || cinfo.AppSecret.Trim().Length == 0) { Response.Write("<script>alert('微信参数AppSecret未设置');history.go(-1);</script>"); return; } string code = Request.QueryString["code"]; if (string.IsNullOrEmpty(code)) { //string code_url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect" // , PayConfig.AppId, PayConfig.SendUrl, State_Str); string code_url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect" , cinfo.AppId, Common.Constant.Get_Host() + PayConfig.SendUrl, State_Str); Response.Redirect(code_url); } else { //LogUtil.WriteLog(" ============ 开始 获取微信用户相关信息 ====================="); #region 获取支付用户 OpenID================ string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", cinfo.AppId, cinfo.AppSecret, code); string returnStr = HttpUtil.Send("", url); //LogUtil.WriteLog("Send 页面 returnStr 第一个:" + returnStr); var obj = JsonConvert.DeserializeObject <OpenModel>(returnStr); url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", cinfo.AppId, obj.refresh_token); returnStr = HttpUtil.Send("", url); obj = JsonConvert.DeserializeObject <OpenModel>(returnStr); //LogUtil.WriteLog("Send 页面 access_token:" + obj.access_token); //LogUtil.WriteLog("Send 页面 openid=" + obj.openid); url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", obj.access_token, obj.openid); returnStr = HttpUtil.Send("", url); //LogUtil.WriteLog(companyid, "Send 页面 returnStr:" + returnStr); //LogUtil.WriteLog(companyid, "Send 页面 openid:" + obj.openid); this.UserOpenId = obj.openid; //LogUtil.WriteLog(" ============ 结束 获取微信用户相关信息 ====================="); SendPay(); #endregion } }
public static string setReply(string FromUserName, string ToUserName, int ReplyID) { string AppId = ""; string AppSecret = ""; wx_configInfo cinfo = wx_configBLL.getInfo(); if (cinfo != null) { AppId = cinfo.AppId; AppSecret = cinfo.AppSecret; } string strhtml = string.Empty; try { wx_ReplyMesageInfo Message = wx_ReplyMesageBLL.GetModel(ReplyID); //设置欢迎语句 if (Message != null && Message.ReplyID == ReplyID) { StringBuilder strHtml = new StringBuilder(); string host = "http://" + HttpContext.Current.Request.Url.Host + (HttpContext.Current.Request.Url.Port == 80 ? "" : ":" + HttpContext.Current.Request.Url.Port); //FileUtility.WriteLog("host:" + host + "\r\n"); if (Message.RefType == 1) { strhtml = string.Format(Template.TextTemplate, FromUserName, ToUserName, Common.GetNowTime(), Message.Body); } else { //FileUtility.WriteLog("Message.RefID:" + Message.RefID + "\r\n"); IList <wx_MaterialInfo> list = wx_MaterialBLL.getlist_appmsg(Message.RefID); //设置欢迎语句 //IList<wx_MaterialInfo> list = JSONHelper.JsonToObject<IList<wx_MaterialInfo>>(strlist); if (list != null && list.Count > 0) { //FileUtility.WriteLog("list.Count:" + list.Count + "\r\n"); //1文字,2图片,3图文,4音频,5视频 switch (list[0].Type) { case 1: strhtml = string.Format(Template.TextTemplate, FromUserName, ToUserName, Common.GetNowTime(), list[0].Body); break; case 2: strhtml = string.Format(Template.ImageTemplate, FromUserName, ToUserName, Common.GetNowTime(), Media.GetMediaId(AppId, AppSecret, "image", list[0].Url)); break; case 3: foreach (wx_MaterialInfo m in list) { string url = host + "/mobile/wx/wx_appmsg.aspx?id=" + m.wx_MaterialID; if (m.Url.Trim().Length > 0) { url = m.Url; } strHtml.Append(string.Format(Template.ItemTemplate, m.Name, m.Paper, host + m.ImgUrl, url)); } strhtml = string.Format(Template.NewsTemplate, FromUserName, ToUserName, Common.GetNowTime(), list.Count, strHtml.ToString()); break; case 4: strhtml = string.Format(Template.VoiceTemplate, FromUserName, ToUserName, Common.GetNowTime(), Media.GetMediaId(AppId, AppSecret, "voice", list[0].Url)); break; case 5: strhtml = string.Format(Template.VideoTemplate, FromUserName, ToUserName, Common.GetNowTime(), Media.GetMediaId(AppId, AppSecret, "video", list[0].Url), list[0].Name, list[0].Paper); break; } } } } } catch (Exception ex) { throw ex; } //FileUtility.WriteLog("文本回复:" + strhtml + "\r\n"); return(strhtml); }
protected void Page_Load(object sender, EventArgs e) { //======================== wx_configInfo cinfo = wx_configBLL.getInfo(); if (cinfo == null) { Response.Write("<script>alert('微信参数未配置');</script>"); Response.End(); } appid = cinfo.AppId; //======================= this.BindData(); //LogUtil.WriteLog("============ 单次支付开始 ==============="); //LogUtil.WriteLog(string.Format("传递支付参数:OrderSN={0}、Body={1}、TotalFee={2}、Attach={3}、UserOpenId={4}", this.OrderSN, this.Body, this.TotalFee, this.Attach, this.UserOpenId)); #region 支付操作============================ #region 基本参数=========================== //时间戳 TimeStamp = TenpayUtil.getTimestamp(); //随机字符串 NonceStr = TenpayUtil.getNoncestr(); //创建支付应答对象 var packageReqHandler = new RequestHandler(Context); //初始化 packageReqHandler.init(); //设置package订单参数 具体参数列表请参考官方pdf文档,请勿随意设置 packageReqHandler.setParameter("body", this.Body); //商品信息 127字符 //packageReqHandler.setParameter("appid", PayConfig.AppId); packageReqHandler.setParameter("appid", cinfo.AppId); packageReqHandler.setParameter("mch_id", cinfo.MchId); packageReqHandler.setParameter("nonce_str", NonceStr.ToLower()); packageReqHandler.setParameter("notify_url", domain + PayConfig.NotifyUrl); packageReqHandler.setParameter("openid", this.UserOpenId); packageReqHandler.setParameter("out_trade_no", this.OrderSN); //商家订单号 packageReqHandler.setParameter("spbill_create_ip", Page.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.setParameter("total_fee", this.TotalFee); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.setParameter("trade_type", "JSAPI"); if (!string.IsNullOrEmpty(this.Attach)) { packageReqHandler.setParameter("attach", this.Attach);//自定义参数 127字符 } #endregion #region sign=============================== Sign = packageReqHandler.CreateMd5Sign("key", cinfo.AppKey); //LogUtil.WriteLog("WeiPay 页面 sign:" + Sign); #endregion #region 获取package包====================== packageReqHandler.setParameter("sign", Sign); string data = packageReqHandler.parseXML(); //LogUtil.WriteLog("WeiPay 页面 package(XML):" + data); string prepayXml = HttpUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder"); //LogUtil.WriteLog("WeiPay 页面 package(Back_XML):" + prepayXml); //获取预支付ID var xdoc = new XmlDocument(); xdoc.LoadXml(prepayXml); XmlNode xn = xdoc.SelectSingleNode("xml"); XmlNodeList xnl = xn.ChildNodes; if (xnl.Count > 7) { PrepayId = xnl[7].InnerText; Package = string.Format("prepay_id={0}", PrepayId); //LogUtil.WriteLog("WeiPay 页面 package:" + Package); } #endregion #region 设置支付参数 输出页面 该部分参数请勿随意修改 ============== var paySignReqHandler = new RequestHandler(Context); paySignReqHandler.setParameter("appId", cinfo.AppId); paySignReqHandler.setParameter("timeStamp", TimeStamp); paySignReqHandler.setParameter("nonceStr", NonceStr); paySignReqHandler.setParameter("package", Package); paySignReqHandler.setParameter("signType", "MD5"); PaySign = paySignReqHandler.CreateMd5Sign("key", cinfo.AppKey); //LogUtil.WriteLog("WeiPay 页面 paySign:" + PaySign); #endregion #endregion }
protected void Page_Load(object sender, EventArgs e) { wx_configInfo cinfo = BLL.wx_configBLL.getInfo(); if (cinfo == null) { Response.Write("<script>alert('微信参数未设置');history.go(-1);</script>"); return; } //创建ResponseHandler实例 ResponseHandler resHandler = new ResponseHandler(Context); //resHandler.setKey(PayConfig.AppKey); resHandler.setKey(cinfo.AppKey); //判断签名 try { string error = ""; if (resHandler.isWXsign(out error)) { #region 协议参数===================================== //--------------协议参数-------------------------------------------------------- //SUCCESS/FAIL此字段是通信标识,非交易标识,交易是否成功需要查 string return_code = resHandler.getParameter("return_code"); //返回信息,如非空,为错误原因签名失败参数格式校验错误 string return_msg = resHandler.getParameter("return_msg"); //微信分配的公众账号 ID string appid = resHandler.getParameter("appid"); //以下字段在 return_code 为 SUCCESS 的时候有返回-------------------------------- //微信支付分配的商户号 string mch_id = resHandler.getParameter("mch_id"); //微信支付分配的终端设备号 string device_info = resHandler.getParameter("device_info"); //微信分配的公众账号 ID string nonce_str = resHandler.getParameter("nonce_str"); //业务结果 SUCCESS/FAIL string result_code = resHandler.getParameter("result_code"); //错误代码 string err_code = resHandler.getParameter("err_code"); //结果信息描述 string err_code_des = resHandler.getParameter("err_code_des"); //以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回--------------- //-------------业务参数--------------------------------------------------------- //用户在商户 appid 下的唯一标识 string openid = resHandler.getParameter("openid"); //用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效 string is_subscribe = resHandler.getParameter("is_subscribe"); //JSAPI、NATIVE、MICROPAY、APP string trade_type = resHandler.getParameter("trade_type"); //银行类型,采用字符串类型的银行标识 string bank_type = resHandler.getParameter("bank_type"); //订单总金额,单位为分 string total_fee = resHandler.getParameter("total_fee"); //货币类型,符合 ISO 4217 标准的三位字母代码,默认人民币:CNY string fee_type = resHandler.getParameter("fee_type"); //微信支付订单号 string transaction_id = resHandler.getParameter("transaction_id"); //商户系统的订单号,与请求一致。 string out_trade_no = resHandler.getParameter("out_trade_no"); //商家数据包,原样返回 string attach = resHandler.getParameter("attach");//_uid + "|" + _model //支 付 完 成 时 间 , 格 式 为yyyyMMddhhmmss,如 2009 年12 月27日 9点 10分 10 秒表示为 20091227091010。时区为 GMT+8 beijing。该时间取自微信支付服务器 string time_end = resHandler.getParameter("time_end"); #endregion //string[] arrattach = attach.Split('|'); //string uid = arrattach[0]; string model = attach; //LogUtil.WriteLog(companyid, "OrderId=" + out_trade_no + " attach=" + attach + " return_code=" + return_code); //支付成功 if (!out_trade_no.Equals("") && return_code.Equals("SUCCESS") && result_code.Equals("SUCCESS")) { try { /** * 这里输入用户逻辑操作,比如更新订单的支付状态 * * **/ if (model.Equals("member_join_order")) { decimal total_fee_money = decimal.Parse(total_fee); string resultMsg = ""; BLL.member_join_orderBLL.order_payresult(out_trade_no, 1, 1, transaction_id, total_fee_money, ref resultMsg); } //LogUtil.WriteLog("============ 单次支付结束 ===============out_trade_no=" + out_trade_no + "&transaction_id=" + transaction_id); Response.Write("success"); //LogUtil.WriteLog("Notify 页面 支付成功,支付信息:商家订单号:" + out_trade_no + "、支付金额(分):" + total_fee + "、自定义参数:" + attach); return; } catch (Exception exc) { LogUtil.WriteLog("Notify 页面 异常信息:" + exc.Message + " 微信返回支付成功,支付信息:商家订单号:" + out_trade_no + "、支付金额(分):" + total_fee + "、自定义参数:" + attach + " "); } } else { if (model.Equals("member_join_order")) { string resultMsg = ""; decimal total_fee_money = decimal.Parse(total_fee); int result = BLL.member_join_orderBLL.order_payresult(out_trade_no, 1, -2, transaction_id, total_fee_money, ref resultMsg); if (result > 0) { LogUtil.WriteLog("微信支付失败更新数据库结果失败:resultMsg=" + resultMsg); } } LogUtil.WriteLog("Notify 页面 支付失败,支付信息 total_fee= " + total_fee + "、err_code_des=" + err_code_des + "、result_code=" + result_code); } } else { LogUtil.WriteLog("Notify 页面 isWXsign= false ,错误信息:" + error); } } catch (Exception ee) { LogUtil.WriteLog("Notify 页面 发送异常错误:" + ee.Message); } Response.End(); }
/// <summary> /// 自定义生成带参数的二维码 /// </summary> /// <param name="TypeID">类型ID(1:分销商)</param> /// <param name="id">相对应于类型的ID</param> /// <param name="CodeType">二维码类型:1临时二维码,2永久二维码</param> /// <returns></returns> public static string CreateQRCode(int TypeID, string id, int CodeType) { string revalue = string.Empty; string qrcodeURL = Constant.URL_QRCode(); try { string AppId = ""; string AppSecret = ""; wx_configInfo model = wx_configBLL.getInfo(); if (model != null) { AppId = model.AppId; AppSecret = model.AppSecret; } if (model != null) { //获取AccessToken string AccessToken = Context.GetAccessToken(model.AppId, model.AppSecret); string data = string.Empty; if (CodeType == 1) { data = " {\"expire_seconds\": \"1800\", \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + id + "}}}"; } else { //data = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + id + "}}}"; string scene_str = id; if (TypeID == 1)//如果是用户 { scene_str = "member_" + id; } data = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + scene_str + "\"}}}"; } string code = com.weixin.User.UserManager.CreateCodeTicket(AccessToken, data); code = Context.IsFailure(code, model.AppId, model.AppSecret); if (!IsJson(code)) { code = com.weixin.User.UserManager.CreateCodeTicket(code, data); } if (!string.IsNullOrEmpty(code)) { QRCode QRCodeModel = JSONHelper.JsonToObject <QRCode>(code); if (QRCodeModel != null && !string.IsNullOrEmpty(QRCodeModel.ticket)) { //string dirPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString(); switch (TypeID) { case 1: if (CodeType == 2) { qrcodeURL += "Forever/"; } break; } int type = 1;//展示还是下载(1下载,2展示) //绝对路径,要截取,用用户ID+产品ID来区别此产品有没有生成二维码 string QRImg = com.weixin.User.UserManager.GetCodeTicket(System.Web.HttpUtility.UrlDecode(QRCodeModel.ticket), type, System.Web.HttpContext.Current.Server.MapPath(qrcodeURL), id.ToString()); if (!string.IsNullOrEmpty(QRImg) && type == 1) { string tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录 QRImg = QRImg.Replace(tmpRootDir, "").Replace("\\", "/"); //转换成相对路径 if (QRImg.Substring(0, 1) != "/") { QRImg = "/" + QRImg; } } revalue = QRImg; } } } } catch (Exception ex) { FileUtility.WriteLog("自定义生成带参数的二维码错误:" + DateTime.Now.ToString() + " " + ex.ToString() + "\r\n"); } return(revalue); }