/// <summary> /// 微信开放平台拉取用户信息(需scope为 snsapi_userinfo) /// </summary> /// <param name="access_token">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param> /// <param name="openid">用户的唯一标识</param> /// <returns></returns> public static WeChatUserInfo GetWeChatUserInfo(string access_token, string openid) { WeChatUserInfo uinfo = new WeChatUserInfo(); string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid); string jsonResult = HttpUtils.Ins.GET(url); ClassLoger.Info("WeChatAPIHelper.GetWeChatUserInfo", url, jsonResult); if (!jsonResult.IsNull()) { if (jsonResult.Contains("errcode")) { ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", url); ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", jsonResult); } else { Dictionary <string, object> resultDic = JsonHelper.DeserializeObject(jsonResult); uinfo.city = resultDic["city"].TryToString(); uinfo.country = resultDic["country"].TryToString(); uinfo.headimgurl = resultDic["headimgurl"].TryToString(); uinfo.nickname = resultDic["nickname"].TryToString(); uinfo.openid = resultDic["openid"].TryToString(); uinfo.privilege = resultDic["privilege"].TryToString(); uinfo.province = resultDic["province"].TryToString(); uinfo.sex = resultDic["sex"].TryToInt(0); if (resultDic.ContainsKey("unionid")) { uinfo.unionid = resultDic["unionid"].TryToString(); } } } return(uinfo); }
public static List <WeChatTags> GetAllGroup() { List <WeChatTags> grouplist = new List <WeChatTags>(); try { string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/get?access_token={0}", access_token); string json = HttpUtils.Ins.GET(url); if (json.Contains("errcode")) { ClassLoger.Fail("WeChatTagsAPI.GetAllGroup", json); return(null); } Dictionary <string, object> dic = JsonHelper.DeserializeObject(json); List <Dictionary <string, object> > groups = dic["tags"] as List <Dictionary <string, object> >; foreach (var group in groups) { WeChatTags info = new WeChatTags(); info.count = group["count"].TryToInt(0); info.id = group["id"].TryToInt(0); info.name = group["name"].TryToString(); grouplist.Add(info); } } catch (Exception ex) { ClassLoger.Error("WeChatGroupAPI.GetAllGroup", ex); } return(grouplist); }
/// <summary> /// 获取微信公共号的Access_token /// </summary> /// <returns></returns> public static string GetWeChatAccess_token() { string access_token = string.Empty; string key = getaccess_tokenKey(); if (RedisBase.ContainsKey(key)) { access_token = RedisBase.Item_Get <string>(key); } else { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", SystemSet.Serviceappid, SystemSet.Serviceappsecret); string resultJson = HttpUtils.Ins.GET(url); if (!resultJson.IsNull()) { if (resultJson.Contains("errcode")) { //WeChatErrorResult errorResult = JsonHelper.DeserializeObject<WeChatErrorResult>(resultJson); ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token", url); ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token", resultJson); } else { Dictionary <string, object> resDic = JsonHelper.DeserializeObject(resultJson); access_token = resDic["access_token"].TryToString(); int expires_in = resDic["expires_in"].TryToInt(100); RedisBase.Item_Set <string>(key, access_token); RedisBase.ExpireEntryAt(key, DateTime.Now.AddSeconds(expires_in)); } } } return(access_token); }
/// <summary> /// 获取网页用户授权 /// </summary> /// <param name="code"></param> /// <returns></returns> public static Access_tokenResult GetWeChatAccess_token(string code) { string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", SystemSet.Appid, SystemSet.Appsecret, code); Access_tokenResult result = new Access_tokenResult(); string resultJson = HttpUtils.Ins.GET(url); if (!resultJson.IsNull()) { if (resultJson.Contains("errcode")) { //WeChatErrorResult errorResult = JsonHelper.DeserializeObject<WeChatErrorResult>(resultJson); ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token(" + code + ")", url); ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token(" + code + ")", resultJson); } else { Dictionary <string, object> resDic = JsonHelper.DeserializeObject(resultJson); result.access_token = resDic["access_token"].TryToString(); result.expires_in = resDic["expires_in"].TryToInt(100); result.openid = resDic["openid"].TryToString(); result.refresh_token = resDic["refresh_token"].TryToString(); result.scope = resDic["scope"].TryToString(); } } return(result); }
/// <summary> /// 获取模板ID /// </summary> /// <param name="template_id_short">模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式</param> /// <returns></returns> public static string GetTemplateID(string template_id_short) { string templateID = string.Empty; try { string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={0}", access_token); string json = "{\"template_id_short\":\"" + template_id_short + "\"}"; string resultJson = HttpUtils.Ins.POST(url, json); Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson); if (reslut["errcode"].TryToInt(0) == 0) { templateID = reslut["template_id"].TryToString(); } else { ClassLoger.Fail("WeChatTemplateAPI.GetTemplateID", resultJson); } } catch (Exception ex) { ClassLoger.Error("WeChatTemplateAPI.GetTemplateID", ex); } return(templateID); }
public override void OnActionExecuting(ActionExecutingContext context) { if (!context.HttpContext.Session.Keys.Contains("user")) { ClassLoger.Fail("UserLoginFilter", "session过期"); context.Result = new RedirectResult("/Account/Index"); return; } base.OnActionExecuting(context); }
/// <summary> /// 根据用户OpenID获取用户所在的分组 /// </summary> /// <param name="openID"></param> /// <returns></returns> public static int GetUserGroupID(string openID) { string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/getid?access_token={0}", access_token); string json = "{\"openid\":\"" + openID + "\"}"; string resultJson = HttpUtils.Ins.POST(url, json); if (resultJson.Contains("errcode")) { ClassLoger.Fail("WeChatGroupAPI.GetUserGroupID", json); return(0); } Dictionary <string, object> result = JsonHelper.DeserializeObject(resultJson); return(result["groupid"].TryToInt(0)); }
/// <summary> /// 把用户移动到指定分组 /// </summary> /// <param name="openID">用户openid</param> /// <param name="groupid">分组ID</param> /// <returns></returns> public static bool UpdateUserGroup(string openID, int groupid) { string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token={0}", access_token); string json = "{\"openid\":\"" + openID + "\",\"to_groupid\":" + groupid + "}"; string resultJson = HttpUtils.Ins.POST(url, json); Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson); if (reslut["errcode"].TryToInt(0) == 0) { return(true); } else { ClassLoger.Fail("WeChatGroupAPI.UpdateUserGroup", resultJson); } return(false); }
/// <summary> /// 创建基础自定义菜单 /// </summary> /// <returns></returns> public static bool CreateBaseMenu() { string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}", access_token); string json = SystemSet.BaseMenu; string resultJson = HttpUtils.Ins.POST(url, json); Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson); if (reslut["errcode"].TryToInt(0) == 0) { return(true); } else { ClassLoger.Fail("WeChatMenuAPI.CreateBaseMenu", resultJson); } return(false); }
/// <summary> /// 设置用户备注名称 /// </summary> /// <param name="openID"></param> /// <param name="name"></param> /// <returns></returns> public static bool SetWeChatUserName(string openID, string name) { string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token={0}", access_token); string json = "{\"openid\":\"" + openID + "\",\"remark\":\"" + name + "\"}"; string resultJson = HttpUtils.Ins.POST(url, json); Dictionary <string, object> result = JsonHelper.DeserializeObject(resultJson); if (result["errcode"].TryToInt(0) == 0) { return(true); } else { ClassLoger.Fail("WeChatUserInfoAPI.SetWeChatUserName", resultJson); } return(false); }
/// <summary> /// 刷新access_token(如果需要) /// 由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新, /// refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效的后,需要用户重新授权。 /// </summary> /// <param name="refresh_token">通过access_token获取到的refresh_token参数</param> /// <returns></returns> public static Access_tokenResult Refresh_token(string refresh_token) { Access_tokenResult result = new Access_tokenResult(); string url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", SystemSet.Appid, refresh_token); string resultJson = HttpUtils.Ins.GET(url); if (!resultJson.IsNull()) { if (resultJson.Contains("errcode")) { //WeChatErrorResult errorResult = JsonHelper.DeserializeObject<WeChatErrorResult>(resultJson); ClassLoger.Fail("WeChatAPIHelper.refresh_token(" + refresh_token + ")", url); ClassLoger.Fail("WeChatAPIHelper.refresh_token(" + refresh_token + ")", resultJson); } else { result = JsonHelper.DeserializeObject <Access_tokenResult>(resultJson); } } return(result); }
/// <summary> /// 创建微信用户分组 /// </summary> /// <param name="groupName"></param> /// <returns></returns> public static WeChatGroup CreateGroup(string groupName) { try { string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/create?access_token={0}", SystemSet.Token); string postJson = "{\"group\":{\"name\":\"" + groupName + "\"}}"; string resultJson = HttpUtils.Ins.POST(url, postJson); if (resultJson.Contains("errcode")) { ClassLoger.Fail("WeChatGroupAPI.CreateGroup", resultJson); return(null); } Dictionary <string, object> dic = JsonHelper.DeserializeObject(resultJson); Dictionary <string, object> groupdic = dic["group"] as Dictionary <string, object>; WeChatGroup group = new WeChatGroup(); group.id = groupdic["id"].TryToInt(0); group.name = groupdic["name"].TryToString(); return(group); } catch (Exception ex) { ClassLoger.Error("WeChatGroupAPI.CreateGroup", ex); } return(null); }
public ActionResult WithdrawalsOrder() { int total_fee = Request["total_fee"].TryToInt(0); if (total_fee <= 0) { return(RedirectToAction("WithdrawalsFailed", new { msg = "提现金额不能小于0" })); } //PsychtestBuyLogBll pbuylogbll = new PsychtestBuyLogBll(); UserWithdrawalsLogBll wilbll = new UserWithdrawalsLogBll(); //decimal PbuyAmt = pbuylogbll.GetMoneyByUserid(User.ID); decimal PbuyAmt = 100;//用户总金额 decimal withAmt = wilbll.GetWithdrawalsAMT(User.ID); if (total_fee > (PbuyAmt - withAmt)) { return(RedirectToAction("WithdrawalsFailed", new { msg = "余额不足" })); } WithdrawalsOrderBll wobll = new WithdrawalsOrderBll(); string OnlineOrder = wobll.GetOnlineOrder(); WeChatUserBll wuserbll = new WeChatUserBll(); WeChatUser wuser = wuserbll.GetWeChatUserByUnionID(User.Openid); A: WxPayData pdata = new WxPayData(); pdata.SetValue("partner_trade_no", OnlineOrder); pdata.SetValue("openid", wuser.ServiceOpenID); pdata.SetValue("check_name", "NO_CHECK"); pdata.SetValue("amount", total_fee * 100); pdata.SetValue("desc", "提现"); pdata.SetValue("spbill_create_ip", "192.168.0.1"); WxPayData result = WxPayApi.transfers(pdata); WithdrawalsOrder wo = new Model.WithdrawalsOrder(); wo.CreateTime = DateTime.Now; wo.OnlineOrder = OnlineOrder; wo.openid = User.Openid; wo.total_fee = total_fee * 100; wo.UserID = User.ID; wo.wsdesc = "提现"; if (result.GetValue("return_code").TryToString() != "SUCCESS") { ClassLoger.Fail("UserCoreController.WithdrawalsOrder用户提现失败", result.GetValue("return_msg").TryToString(), result.GetValue("err_code").TryToString()); // 系统繁忙,请稍后再试错误。使用原单号以及原请求参数重试,否则可能造成重复支付等资金风险 if (result.GetValue("err_code").TryToString() == "SYSTEMERROR") { goto A; } wo.result_code = result.GetValue("result_code").TryToString(); wo.return_code = result.GetValue("return_code").TryToString(); wobll.AddWithdrawalsOrder(wo); return(RedirectToAction("WithdrawalsFailed", new { msg = "提现失败" })); } wo.payment_no = result.GetValue("payment_no").TryToString(); wo.result_code = result.GetValue("result_code").TryToString(); wo.return_code = result.GetValue("return_code").TryToString(); wobll.AddWithdrawalsOrder(wo); UserWithdrawalsLog uwlog = new UserWithdrawalsLog(); uwlog.AMT = total_fee; uwlog.CreateTime = DateTime.Now; uwlog.UserID = User.ID; wilbll.AddUserWithdrawalsLog(uwlog); return(RedirectToAction("WithdrawalsSuccess")); }
/// <summary> /// 开始发送 /// </summary> public static void StartSendEmail(int sendEmailTaskId) { if (sendEmailTaskId <= 0) { ClassLoger.Fail("SendEmailHelper.StartSendEmail", "邮件发送任务Id小于0不能发送任务"); return; } Task.Run(() => { ClassLoger.Info("SendEmailHelper.StartSendEmail", "开始发送邮件"); SendEmailLogBll sendEmailLogBll = new SendEmailLogBll(); EmailTemplateBll emailTemplateBll = new EmailTemplateBll(); try { EmailResourcesBll emailResourcesBll = new EmailResourcesBll(); List <EmailResources> emailResourceses = emailResourcesBll.GetLists(); if (emailResourceses == null || emailResourceses.Count == 0) { ClassLoger.Fail("SendEmailHelper.StartSendEmail", "邮件资源为空不能发邮件"); } int pageIndex = 0; int pageSize = 60; A: pageIndex++; var tup = sendEmailLogBll.GetNoSendByTaskId(sendEmailTaskId, pageIndex, pageSize); if (tup.Item1 != null && tup.Item1.Count > 0) { foreach (var sendEmailLog in tup.Item1) { Random r = new Random(); int i = r.Next(0, emailResourceses.Count - 1); var emailResourcese = emailResourceses[i]; var template = emailTemplateBll.GetByIds(sendEmailLog.EmailTempId); string url = $"http://open.lsc.com:8080/Account/OpenEmailCallBack?logid=" + sendEmailLog.Id; string imag = $"<img src=\"{url}\" style=\"width: 1px; height: 1px;\" />"; string emailCount = template.EmailContent + "<br/>" + imag;//邮箱内容 EmailHelper emailHelper = new EmailHelper(emailResourcese.SenderServerIp, sendEmailLog.Email, emailResourcese.Email, template.Title, emailCount, emailResourcese.UserName, emailResourcese.Password, emailResourcese.Port, false, false); try { emailHelper.Send(); sendEmailLog.IsSendOk = true; } catch (Exception e) { sendEmailLog.IsSendOk = false; } sendEmailLog.IsSend = true; sendEmailLogBll.Update(sendEmailLog); Thread.Sleep(1000 * 60 * 3); } goto A; } } catch (Exception e) { ClassLoger.Error("SendEmailHelper.SendEmail", e); } }); }
public void Index() { try { WxPayData notifyData = GetNotifyData(Request, Response); ClassLoger.Info("WeChartPayCallBack.Index", notifyData.ToJson()); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); ClassLoger.Fail("WeChartPayCallBackController.Index:支付结果中微信订单号不存在", notifyData.ToXml()); Response.Write(res.ToXml()); Response.End(); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); ClassLoger.Fail(this.GetType().ToString(), "Order query failure : " + res.ToXml()); Response.Write(res.ToXml()); Response.End(); }//查询订单成功 else { ThreadPool.QueueUserWorkItem(new WaitCallback(p => { string out_trade_no = notifyData.GetValue("out_trade_no").ToString(); PayOrderBll porderBll = new PayOrderBll(); PayOrder porder = porderBll.GetByOnlineOrder(out_trade_no); string mqttmsg = string.Empty; if (notifyData.GetValue("result_code").ToString() == "SUCCESS") { porder.PayState = Model.EnumModel.PayStateEnum.Paid; mqttmsg = MqttAgreement.GetPsychtestWeChartPayState(out_trade_no, true); } else { porder.PayState = Model.EnumModel.PayStateEnum.Fail; if (notifyData.IsSet("err_code_des")) { porder.PayStateMsg = notifyData.GetValue("err_code_des").TryToString(); } mqttmsg = MqttAgreement.GetPsychtestWeChartPayState(out_trade_no, false); } porderBll.UpdatePayOrder(porder); MqttPublishClient.Ins.PublishOneUser(porder.ID, mqttmsg); }), null); WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); ClassLoger.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); Response.Write(res.ToXml()); Response.End(); } } catch (Exception ex) { ClassLoger.Error("WeChartPayCallBackController.Index", ex); } }