tijian_tieying/web/dccdc/Controllers/YiMiaoWXController.cs
2025-02-20 12:14:39 +08:00

1201 lines
51 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using dccdc.BLL;
using dccdc.Common;
using dccdc.Models;
using dccdc.Models.WeiXin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace dccdc.Controllers
{
/// <summary>
/// 疫苗相关微信 --zzq 2018年5月18日 11:32:08
/// </summary>
public class YiMiaoWXController : Controller
{
public string cs()
{
var result = new ERPUserBll().Setopenid("32", "1");
return result.ToString();
}
[AllowAnonymous]
// GET: WeiXin
[HttpGet]
public string Index()
{
string echostr = Request.QueryString["echostr"];
return CheckSignature() ? echostr : "error";
}
[AllowAnonymous]
[HttpPost]
public string Index(FormCollection fc)
{
string postString;
using (Stream stream = Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
}
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(postString);
string signature = Request.QueryString["signature"];
string timestamp = Request.QueryString["timestamp"];
string nonce = Request.QueryString["nonce"];
string msg_signature = Request.QueryString["msg_signature"];
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(signature);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(timestamp);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(nonce);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg_signature);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(postString);
//if (CheckSignature())
//{
// log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("成功!");
//}
WXBizMsgCrypt wxbiz = new WXBizMsgCrypt(Common.Global.YMToken, Common.Global.YMEncodingAESKey, Common.Global.YMAppId);
string msg = postString;
int code = wxbiz.DecryptMsg(msg_signature, timestamp, nonce, postString, ref msg);
//msg = postString;
//int code = 0;
string retmsg = string.Empty;
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg);
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(msg);
XmlNode root = doc.FirstChild;
var xmlElement = root["MsgType"];
if (xmlElement != null)
{
string msgType = xmlElement.InnerText;
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msgType);
switch (msgType.ToLower())
{
case "event":
retmsg = ExecEvent(doc);
break;
case "text":
//retmsg = ExceText(doc);
break;
}
}
}
catch (Exception ex)
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(ex.Message);
}
if (string.IsNullOrEmpty(retmsg))
return retmsg;
else
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(retmsg);
int t_code = wxbiz.EncryptMsg(retmsg, timestamp, nonce, ref msg);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg);
if (t_code == 0)
return msg;
else
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(t_code.ToString());
return "";
}
}
}
private string ExecEvent(XmlDocument doc)
{
string msg = string.Empty;
XmlNode root = doc.FirstChild;
var xmlElement = root["Event"];
if (xmlElement != null)
{
var Event = xmlElement.InnerText;
var element = root["FromUserName"];
if (element != null)
{
string openid = element.InnerText;
openuser ou = getopenuser(openid);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("openuser:" + Newtonsoft.Json.JsonConvert.SerializeObject(ou));
try
{
new BLL.weixinBll().updateOpenUserYM(ou);
}
catch (Exception ex)
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(ex.Message);
}
switch (Event)
{
case "subscribe":
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("关注微信");
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("openid:" + openid);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("appid:" + Global.YMAppId);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("Appsecret:" + Global.YMAppsecret);
var comm = new BLL.Common();
string xiaoxi = @"
<ArticleCount>1</ArticleCount><Articles><item>
<Title><![CDATA[HI " + ou.nickname + @"~" + comm.getParm_Value("wxgztitleym", "欢迎关注德城区疾病预防控制中心微信公众号", "微信关注消息标题(疫苗)") + @"]]></Title>
<Description><![CDATA[" + comm.getParm_Value("wxgzjjym", "欢迎关注德城区疾病预防控制中心微信公众号,体检疫苗缴费,疫苗接种消息提醒,在线排队。", "微信关注消息简介(疫苗)") + @"]]></Description>
<PicUrl><![CDATA[" + comm.getParm_Value("wxgzpicym", "http://www.dcqcdc.com/news/UploadFiles_9967/201707/2017071008093694.jpg", "微信关注消息图片连接(疫苗)") + @"]]></PicUrl>
<Url><![CDATA[" + comm.getParm_Value("wxgzurlym", "http://www.dcqcdc.com", "微信关注消息连接") + @"]]></Url>
</item></Articles>";
msg = CreateNews(openid, "news", xiaoxi);
var EventKey = root["EventKey"];
if (EventKey != null)
{
string userid = EventKey.InnerText;
if (userid.StartsWith("qrscene_"))
{
userid = userid.Replace("qrscene_", "");
new ERPUserBll().Setopenid(userid, openid);
}
}
break;
case "unsubscribe":
// var opuunsubscribe = cont.OpenUser.Find(new[] { openid });
//ou = getopenuser(openid);
//updateOpenUser(ou);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("取消关注");
//unsubscribe(openid);
break;
case "SCAN":
var ek = root["EventKey"];
if (ek != null)
{
string userid = ek.InnerText;
new ERPUserBll().Setopenid(userid, openid);
}
break;
}
}
}
return msg;
}
#region
private bool CheckSignature()
{
string signature = Request.QueryString["signature"];
string timestamp = Request.QueryString["timestamp"];
string nonce = Request.QueryString["nonce"];
string[] arrTmp = { Common.Global.YMToken, timestamp, nonce };
//string[] arrTmp = { Token, timestamp, nonce };
Array.Sort(arrTmp);//字典排序
string tmpStr = string.Join("", arrTmp);
var sha1 = System.Security.Cryptography.SHA1.Create();
tmpStr = BitConverter.ToString(sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(tmpStr))).Replace("-", ""); //对该字符串进行sha1加密
tmpStr = tmpStr.ToLower();//对字符串中的字母部分进行小写转换,非字母字符不作处理
//WriteLog(tmpStr);//计入日志
if (tmpStr == signature)//开发者获得加密后的字符串可与signature对比标识该请求来源于微信。开发者通过检验signature对请求进行校验若确认此次GET请求来自微信服务器请原样返回echostr参数内容则接入生效否则接入失败
{
return true;
}
return false;
}
#endregion
#region
/// <summary>
/// 读取微信用户信息
/// </summary>
/// <param name="openid"></param>
/// <returns></returns>
private openuser getopenuser(string openid)
{
var accessToken = Common.Global.getAccessTokenYM;
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("accessToken:" + Newtonsoft.Json.JsonConvert.SerializeObject(accessToken));
WebClient wc = new WebClient();
var stream = wc.OpenRead("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken.access_token + "&openid=" + openid + "&lang=zh_CN");
var sr = new StreamReader(stream);
string token = sr.ReadToEnd();
sr.Close();
stream.Dispose();
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(token);
var ou = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.WeiXin.openuser>(token);
if (string.IsNullOrEmpty(ou.openid))
{
error err = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.WeiXin.error>(token);
Exception wx = new Exception(err.errmsg + "\r\n" + err.errcode);
throw wx;
}
return ou;
}
#endregion
/// <summary>
/// 生成返回消息
/// </summary>
/// <param name="touser"></param>
/// <param name="type"></param>
/// <param name="xiaoxi"></param>
/// <returns></returns>
string CreateNews(string touser, string type, string xiaoxi)
{
string msg = @"<xml><ToUserName><![CDATA[" + touser + @"]]></ToUserName><FromUserName><![CDATA[" + Common.Global.YMMyId + @"]]></FromUserName><CreateTime>" + GetNowTime() + @"</CreateTime><MsgType><![CDATA[" + type + @"]]></MsgType>" + xiaoxi + @"</xml> ";
return msg;
}
/// <summary>
/// 获取时间差
/// </summary>
/// <returns></returns>
int GetNowTime()
{
return (int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1))).TotalSeconds;
}
/// <summary>
/// 通过时间差获取时间
/// </summary>
/// <param name="tick"></param>
/// <returns></returns>
DateTime getTime(int tick)
{
return TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)).AddSeconds(tick);
}
/// <summary>
/// 关注用户页面
/// </summary>
/// <returns></returns>
public ActionResult OpenUserList()
{
return View();
}
/// <summary>
/// 获取关注用户列表
/// </summary>
/// <param name="nc"></param>
/// <param name="bz"></param>
/// <param name="page"></param>
/// <param name="pagesize"></param>
/// <returns></returns>
public JsonResult getOpenUserList(string nc, string bz, int page, int pagesize)
{
var bll = new weixinBll();
var count = bll.getGZCountYM(nc, bz);
var list = bll.getGZListYM(nc, bz, page, pagesize);
return Json(new { Total = count, Rows = list });
}
/// <summary>
/// 备注关注用户
/// </summary>
/// <param name="openid"></param>
/// <param name="bz"></param>
/// <returns></returns>
public JsonResult remark(string openid, string bz)
{
try
{
var bll = new weixinBll();
var c = bll.remarkGZYM(openid, bz);
if (c > 0)
{
/*
* {
"openid":"oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark":"pangzi"
}
*/
var data = new { openid = openid, remark = bz };
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
log4net.LogManager.GetLogger(this.GetType()).Info(Newtonsoft.Json.JsonConvert.SerializeObject(data));
var result = wc.UploadData("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + Common.Global.getAccessTokenYM.access_token, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(data)));
string jg = System.Text.Encoding.UTF8.GetString(result);
var rjg = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.WeiXin.error>(jg);
if (rjg.errmsg == "ok")
{
return Json(new { State = 1, Message = "修改成功!" });
}
else
{
return Json(new { State = 0, Message = jg });
}
}
else
{
return Json(new { State = 0, Message = "没有数据备注成功!" });
}
}
catch (Exception ex)
{
return Json(new { State = 0, Message = ex.Message });
}
}
#region
/// <summary>
/// 微信菜单管理
/// </summary>
/// <returns></returns>
public ActionResult Menu()
{
return View();
}
/// <summary>
/// 微信菜单类型
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult getCDLX()
{
return Json(
new[]
{
new { id="zu",name="菜单组" },
new { id="click",name="点击推事件" },
new { id="view",name="跳转URL" }
}
);
}
/// <summary>
/// 获取菜单列表
/// </summary>
/// <returns></returns>
[HttpPost]
public string getMeun()
{
// string sql = "select * from menu";
var dt = new BLL.weixinBll().getMenuYM();
return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}
/// <summary>
/// 获取上级菜单
/// </summary>
/// <returns></returns>
[HttpPost]
public string getSJCD()
{
var dt = new BLL.weixinBll().getSJCDYM();
var dr = new Models.WeiXin.menu
{
id = 0,
name = "顶级菜单"
};
dt.Insert(0, dr);
return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}
/// <summary>
/// 删除菜单
/// </summary>
/// <param name="id">菜单ID</param>
/// <returns></returns>
[HttpPost]
public JsonResult delCD(int id)
{
return Json(new BLL.weixinBll().delCdYM(id));
}
/// <summary>
/// 保存菜单
/// </summary>
/// <param name="m">菜单实体</param>
/// <returns></returns>
[HttpPost]
public JsonResult saveCD(Models.WeiXin.menu m)
{
return Json(new BLL.weixinBll().saveCDYM(m));
}
#endregion
#region
/// <summary>
/// 提交微信菜单
/// </summary>
/// <returns></returns>
[HttpPost]
public string CreateWXMenu()
{
List<button> btns = new List<button>();
var dt = new BLL.weixinBll().getMenuYM();
var drs = dt.Where(t => t.pid == 0);
foreach (var dr in drs)
{
var btn = new button { name = dr.name };
var zcds = dt.Where(t => t.pid == dr.id);
var enumerable = zcds as menu[] ?? zcds.ToArray();
if (enumerable.Any())
{
btn.sub_button = new List<button>();
foreach (var zdr in enumerable)
{
var zcd = new button
{
name = zdr.name,
type = zdr.cdlx
};
if (zcd.type == "click")
{
zcd.key = zdr.key;
}
else if (zcd.type == "view")
{
zcd.url = zdr.url;
}
btn.sub_button.Add(zcd);
}
}
else
{
btn.type = dr.cdlx;
if (btn.type == "click")
{
btn.key = dr.key;
}
else if (btn.type == "view")
{
btn.url = dr.url;
}
}
btns.Add(btn);
}
string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new { button = btns });
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
log4net.LogManager.GetLogger(this.GetType()).Info(postData);
var result = wc.UploadData("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + Common.Global.getAccessTokenYM.access_token, System.Text.Encoding.UTF8.GetBytes(postData));
string jg = System.Text.Encoding.UTF8.GetString(result);
return jg;
}
#endregion
#region
[AllowAnonymous]
public string getpdxx()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 0, Message = "获取关注信息失败请重新打开排队页面!" });
}
string session = Session["openuser"].ToString();
Models.PD_XX pdxx = new BLL.PaiDuiJiaoHaoBLL().getpdxx(session);
//log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(Newtonsoft.Json.JsonConvert.SerializeObject(ml));
if (pdxx == null)
return Newtonsoft.Json.JsonConvert.SerializeObject(new { Stste=0});
else
{
ViewBag.pdid = pdxx.id;
var pdxx1 = new BLL.JiezhongmianyitiaomaModelBll().getpdxx(session);
/*
ViewBag.wdhm = pdxx.hm;
ViewBag.ddrs = pdxx1.ddrs;
ViewBag.dqhm = pdxx1.dqhm;
if (pdxx1.dqhm > pdxx.hm)
{
ViewBag.btntext = "重新排队";
}
else
{
ViewBag.btntext = "取消排队";
}*/
//return View();
return Newtonsoft.Json.JsonConvert.SerializeObject(new { pdid=pdxx.id, wdhm=pdxx.hm,ddrs=pdxx1.ddrs, dqhm=pdxx1.dqhm });
}
}
[AllowAnonymous]
public ActionResult paidui()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Common.Global.YMAppId +
"&redirect_uri=" + Url.Encode(Request.Url.AbsoluteUri) +
"&response_type=code&scope=snsapi_base#wechat_redirect");
}
string openidstr = GetOAuthOpenId(code);
var openid = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthopenid>(openidstr);
Session["openuser"] = openid.openid;
HttpCookie hc = new HttpCookie("openuser");
hc.Value = openid.openid;
Response.Cookies.Add(hc);
}
string session = Session["openuser"].ToString();
JiezhongmianyitiaomaModelBll bll = new JiezhongmianyitiaomaModelBll();
var ml = bll.getListByopenid(session);
//log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().GetType()).Info(Newtonsoft.Json.JsonConvert.SerializeObject(ml));
if (ml.Count > 0)
{
Models.PD_XX pdxx= new BLL.PaiDuiJiaoHaoBLL().getpdxx(session);
//log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(Newtonsoft.Json.JsonConvert.SerializeObject(ml));
if (pdxx == null)
return RedirectToAction("quhao");
else
{
ViewBag.pdid = pdxx.id;
var pdxx1 = new BLL.JiezhongmianyitiaomaModelBll().getpdxx(session);
ViewBag.wdhm = pdxx.hm;
ViewBag.ddrs = pdxx1.ddrs;
ViewBag.dqhm = pdxx1.dqhm;
if(pdxx1.dqhm>pdxx.hm)
{
ViewBag.btntext = "重新排队";
}
else
{
ViewBag.btntext = "取消排队";
}
return View();
}
}
else
{
return View("bd");
}
}
[AllowAnonymous]
public JsonResult qxpd(string pdid)
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Json(new { State = 0, Message = "获取关注信息失败请重新打开排队页面!" });
}
return Json(new BLL.PaiDuiJiaoHaoBLL().qxpd(pdid));
//return View();
}
[AllowAnonymous]
public ActionResult quhao()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Common.Global.YMAppId +
"&redirect_uri=" + Url.Encode(Request.Url.AbsoluteUri) +
"&response_type=code&scope=snsapi_base#wechat_redirect");
}
string openidstr = GetOAuthOpenId(code);
var openid = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthopenid>(openidstr);
Session["openuser"] = openid.openid;
HttpCookie hc = new HttpCookie("openuser");
hc.Value = openid.openid;
Response.Cookies.Add(hc);
}
string session = Session["openuser"].ToString();
JiezhongmianyitiaomaModelBll bll = new JiezhongmianyitiaomaModelBll();
var ml = bll.getListByopenid(session);
if (ml.Count > 0)
{
var etlist = bll.getetlistbybdxx(session);
ViewBag.etlist = new SelectList(etlist, "id", "username");
ViewBag.pdrs = new BLL.PaiDuiJiaoHaoBLL().getPdrs();
return View();
}
else
{
return View("bd");
}
}
[AllowAnonymous]
public JsonResult savequhao(string etid)
{
PaiDuiJiaoHaoBLL bll = new PaiDuiJiaoHaoBLL();
int ietid = 0;
if(!int.TryParse(etid,out ietid))
{
return Json(new { State = 0, Message = "您的儿童信息有问题,请选择儿童。" });
}
var result = bll.JiaoHao(ietid);
if (result.State == 1)
{
IConnection connection;
ISession session;
IMessageProducer prod;
string address = System.Configuration.ConfigurationManager.AppSettings["MQAddress"];
IConnectionFactory factory = new ConnectionFactory(address);
connection = factory.CreateConnection();
connection.ClientId = Dns.GetHostName() + "_gxpdrs";
connection.Start();
//Create the Session
session = connection.CreateSession();
//Create the Producer for the topic/queue
prod = session.CreateProducer(
new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("sxpdrs"));
prod.DeliveryMode = MsgDeliveryMode.Persistent;
var imesg = prod.CreateTextMessage();
imesg.Text = result.Message.Split('|')[2];
//imesg.Properties.SetString("dept_code", ksbh);
prod.Send(imesg, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue);
prod.Close();
prod = session.CreateProducer(
new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("gxpdlb"));
prod.DeliveryMode = MsgDeliveryMode.Persistent;
imesg = prod.CreateTextMessage();
imesg.Text = "gxpdlb";
//imesg.Properties.SetString("dept_code", ksbh);
prod.Send(imesg, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue);
prod.Close();
prod = session.CreateProducer(
new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("sxpdrs"));
prod.DeliveryMode = MsgDeliveryMode.Persistent;
imesg = prod.CreateTextMessage();
imesg.Text = "";
//imesg.Properties.SetString("dept_code", ksbh);
prod.Send(imesg, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue);
prod.Close();
session.Close();
connection.Close();
return Json(new { State = 1, Message = result.Message.Split('|')[2] });
}
return Json(result);
}
[AllowAnonymous]
public ActionResult my()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Common.Global.YMAppId +
"&redirect_uri=" + Url.Encode(Request.Url.AbsoluteUri) +
"&response_type=code&scope=snsapi_base#wechat_redirect");
}
string openidstr = GetOAuthOpenId(code);
var openid = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthopenid>(openidstr);
Session["openuser"] = openid.openid;
HttpCookie hc = new HttpCookie("openuser");
hc.Value = openid.openid;
Response.Cookies.Add(hc);
}
string session = Session["openuser"].ToString();
JiezhongmianyitiaomaModelBll bll = new JiezhongmianyitiaomaModelBll();
var ml = bll.getListByopenid(session);
if (ml.Count > 0)
{
var etlist = bll.getetlistbybdxx(session);
ViewBag.etlist = new SelectList(etlist, "id", "username");
return View();
}
else
{
return View("bd");
}
}
#endregion
#region
public string GetOAuthOpenId(string code)
{
//log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("code:"+code);
//log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("YMAppId:" + Common.Global.YMAppId);
//log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("YMAppsecret:" + Common.Global.YMAppsecret);
//return "";
string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Common.Global.YMAppId + "&secret=" + Common.Global.YMAppsecret + "&code=" + code + "&grant_type=authorization_code";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream(); //获取响应的字符串流
if (stream != null)
{
StreamReader sr = new StreamReader(stream); //创建一个stream读取流
string html = sr.ReadToEnd(); //从头读到尾放到字符串html李米
sr.Close();
stream.Close();
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(html);
return html;
}
return "";
}
[AllowAnonymous]
public string getetxx(string etid)
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 0, Message = "获取关注信息失败请重新打开儿童信息绑定页面!" });
}
var m = new BLL.JiezhongmianyitiaomaModelBll().getetxx(etid, Session["openuser"].ToString());
if (m == null)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 0 });
}
else
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 1, et = m });
}
}
#endregion
#region
[AllowAnonymous]
public ActionResult bd()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Common.Global.YMAppId +
"&redirect_uri=" + Url.Encode(Request.Url.AbsoluteUri) +
"&response_type=code&scope=snsapi_base#wechat_redirect");
}
string openidstr = GetOAuthOpenId(code);
var openid = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthopenid>(openidstr);
Session["openuser"] = openid.openid;
HttpCookie hc = new HttpCookie("openuser");
hc.Value = openid.openid;
Response.Cookies.Add(hc);
}
return View();
}
[AllowAnonymous]
public JsonResult checkBd(string username, string barcode, string yetgx)
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Json(new { State = 0, Message = "获取关注信息失败请重新打开儿童信息绑定页面!" });
}
JiezhongmianyitiaomaModelBll bll = new JiezhongmianyitiaomaModelBll();
var result = bll.checkBarcode(username, barcode, yetgx, Session["openuser"].ToString());
return Json(result);
}
[AllowAnonymous]
public JsonResult jiebang(string etid)
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Json(new { State = 0, Message = "获取关注信息失败请重新打开儿童信息绑定页面!" });
}
if (!string.IsNullOrEmpty(etid))
{
return Json(new JiezhongmianyitiaomaModelBll().jb(etid, Session["openuser"].ToString()));
//return Json(new { State = 1, Message = "解除绑定失败!" });
}
else
{
return Json(new { State = 0, Message = "解除绑定失败!" });
}
}
[AllowAnonymous]
public JsonResult saveBd(JiezhongmianyitiaomaModel model)
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Json(new { State = 0, Message = "获取关注信息失败请重新打开儿童信息绑定页面!" });
}
model.openid = Session["openuser"].ToString();
var yzmbll = new BLL.DuanXinYanZhengBll();
//int iyzmid;
//int.TryParse(yzmid, out iyzmid);
if (string.IsNullOrEmpty(model.yzmid))
{
return Json(new { State = 0, Message = "手机验证码不正确!" });
}
var yzm = yzmbll.getYZMById(model.yzmid);
if (yzm == null)
{
return Json(new { State = 0, Message = "手机验证码不正确!" });
}
if (yzm.ShouJiHao != model.sjh)
{
return Json(new { State = 0, Message = "手机号码和获取验证码的手机号码不一致!" });
}
if ((DateTime.Now - yzm.sendtime).TotalMinutes > yzm.YanZhengYouXiaoQi)
{
return Json(new { State = 0, Message = "验证码已经超过有效期!" });
}
if (yzm.state != 0)
{
return Json(new { State = 0, Message = "验证码已经使用不能重复验证!" });
}
if (yzm.smscode != model.yzm)
{
return Json(new { State = 0, Message = "手机验证码不正确!" });
}
JiezhongmianyitiaomaModelBll bll = new JiezhongmianyitiaomaModelBll();
OperationResult result;
result = bll.bd(model);
if (result.State == 1)
{
yzmbll.YanZhenged(yzm);
}
return Json(result);
}
#endregion
#region
[AllowAnonymous]
public ActionResult WXTS(string id)
{
return View(new BLL.Common().GetModelBy(id));
}
#endregion
/// <summary>
/// 获取手机验证码
/// </summary>
/// <param name="Mobile">手机号</param>
/// <returns>验证码ID</returns>
[AllowAnonymous]
public JsonResult getsjyzm(string Mobile)
{
if (System.Text.RegularExpressions.Regex.IsMatch(Mobile, "^1[3|4|5|7|8]\\d{9}$"))
{
var dxyz = new BLL.DuanXinYanZhengBll();
string cookieid = Guid.NewGuid().ToString();// Request.Cookies["clientid"].Value;
var yzm = dxyz.getYanZheng(Session.SessionID, cookieid, Request.UserHostAddress, Mobile);
if (yzm.id == 0)
{
return Json(new { State = 0, Message = yzm.bz });
}
else
{
var commonbll = new BLL.Common();
string yddx = commonbll.getParm_Value("qyyddx", "false", "是否启用移动短信");
if (yddx == "false")
{
string AccessKeyID = commonbll.getParm_Value("AccessKeyID", "LTAIWq3410bmP7hi", "阿里AccessKeyID");
string AccessKeySecret = commonbll.getParm_Value("AccessKeySecret", "F953Ru3uZN2ZbS5741zvO9OvHrthNV", "阿里AccessKeySecret");
string qm = commonbll.getParm_Value("aldxqm", "三才网络", "短信签名");
string dxmb = commonbll.getParm_Value("aldxmb_ym", "SMS_135797401", "疫苗绑定短信模版");
//string smsurl = System.Configuration.ConfigurationManager.AppSettings["smsurl"];
//string yznr = "你好,欢迎你注册天瑞体检中心会员,你的验证码是:" + yzm.smscode + "。有效期10分钟。回TD退订【天瑞体检】";
//var zysms = new zyer.smsservice.SmsServiceSoapClient("SmsServiceSoap");
//var smsjg = zysms.SendEx(username, userpassword, "808", sjh, "", yznr);
//var fz = Session["FenZhan"] as Model.FenZhan;
//Common.SendMsg.Send(sjh, yznr, fz.id);
String product = "Dysmsapi";//短信API产品名称
String domain = "dysmsapi.aliyuncs.com";//短信API产品域名
String accessKeyId = AccessKeyID;//你的accessKeyId
String accessKeySecret = AccessKeySecret;//你的accessKeySecret
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
//IAcsClient client = new DefaultAcsClient(profile);
// SingleSendSmsRequest request = new SingleSendSmsRequest();
DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
try
{
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
request.PhoneNumbers = Mobile;
//必填:短信签名-可在短信控制台中找到
request.SignName = qm;
//必填:短信模板-可在短信控制台中找到
request.TemplateCode = dxmb;
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.TemplateParam = Newtonsoft.Json.JsonConvert.SerializeObject(new { code = yzm.smscode });
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//request.OutId = "21212121211";
//请求失败这里会抛ClientException异常
SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
//System.Console.WriteLine(sendSmsResponse.Message);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(sendSmsResponse.Message);
}
catch (ServerException e)
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(e.Message + e.RequestId);
//System.Console.WriteLine("Hello World!");
//return Json(new { State = 0, Message = e.Message});
}
catch (ClientException e)
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(e.Message + e.RequestId);
//return Json(new { State = 0, Message = e.Message});
}
return Json(new { State = 1, Message = yzm.id.ToString() });
}
else
{
//http://112.35.1.155:1992/sms/norsubmit
string ydhttp = commonbll.getParm_Value("ydhttp", "http://112.35.1.155:1992/sms/tmpsubmit", "移动短信地址");
var req = new Models.duanxin.msend();
req.ecName = commonbll.getParm_Value("yddxqymc", "德州市德城区疾病预防控制中心", "企业名称");
req.apId = commonbll.getParm_Value("yddxapId", "jkoa", "接口账号用户名");
req.mobiles = yzm.ShouJiHao;
req.sign = commonbll.getParm_Value("yddxsign", "d37CYmrbG", "签名编码");
//req.content = "您正在绑定宝宝的接种信息,您的验证码是!" + yzm.smscode + "!请确认提交信息准确,如有不明请咨询登记窗口";
req.templateId = "36d5cd74c4a646198e4ade08168082ec";
req.addSerial = "";
string[] parms = new string[1];
parms[0] = yzm.smscode;
req.parms = Newtonsoft.Json.JsonConvert.SerializeObject(parms);
var md5 = MD5.Create();
//secretKey
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(req.ecName + req.apId + commonbll.getParm_Value("yddxsecretKey", "a7551898", "短信接口密码") + req.templateId + req.mobiles + req.parms + req.sign));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
req.mac = sb.ToString().ToLower();
WebClient wc = new WebClient();
string upstr = Newtonsoft.Json.JsonConvert.SerializeObject(req);
upstr = upstr.Replace("parms", "params");
//new {params }
//upstr.Insert(upstr.Length-1,",")
byte[] resp = wc.UploadData(ydhttp, System.Text.Encoding.UTF8.GetBytes(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(upstr))));
var nres = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.duanxin.nrecive>(System.Text.Encoding.UTF8.GetString(resp));
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(System.Text.Encoding.UTF8.GetString(resp));
return Json(new { State = 1, Message = yzm.id.ToString() });
}
}
}
else
{
return Json(new { State = 0, Message = "请输入正确的手机号码!" });
}
}
public string mytest()
{
var m = new BLL.JiezhongmianyitiaomaModelBll().getpdxx("");
return Newtonsoft.Json.JsonConvert.SerializeObject(m);
}
#region
[AllowAnonymous]
public ActionResult jzyy()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Common.Global.YMAppId +
"&redirect_uri=" + Url.Encode(Request.Url.AbsoluteUri) +
"&response_type=code&scope=snsapi_base#wechat_redirect");
}
string openidstr = GetOAuthOpenId(code);
var openid = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthopenid>(openidstr);
Session["openuser"] = openid.openid;
HttpCookie hc = new HttpCookie("openuser");
hc.Value = openid.openid;
Response.Cookies.Add(hc);
}
return View();
}
[AllowAnonymous]
public ActionResult myjzyy()
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Common.Global.YMAppId +
"&redirect_uri=" + Url.Encode(Request.Url.AbsoluteUri) +
"&response_type=code&scope=snsapi_base#wechat_redirect");
}
string openidstr = GetOAuthOpenId(code);
var openid = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthopenid>(openidstr);
Session["openuser"] = openid.openid;
HttpCookie hc = new HttpCookie("openuser");
hc.Value = openid.openid;
Response.Cookies.Add(hc);
}
string openid2 = Session["openuser"].ToString();
var list2 = new BLL.ym_yymxBll().GetList("openid = '" + openid2 + "' order by id desc");
return View(list2);
}
[AllowAnonymous]
public string getsjd(string yyrq)
{
var list = new BLL.ym_yysjdBll().GetAllList("");
var list2 = new BLL.ym_yymxBll().GetSjd(yyrq);
StringBuilder sb = new StringBuilder();
foreach (var model in list)
{
string key = model.id.ToString();
int yjyy2 = 0;
if (list2.Count(t => t.key == key) != 0)
{
yjyy2 = Convert.ToInt32(list2.First(t => t.key == key).value);
}
if (yjyy2 < model.yyrs)
{
sb.Append("<label class=\"weui-cell weui-check__label\">");
sb.Append(model.mc + " (剩余可预约" + (model.yyrs - yjyy2) + "人) <input type=\"radio\" class=\"weui-check\" name=\"sjdid\" value=\"" + model.id + "\">");
sb.Append("<span class=\"weui-icon-checked\"></span></label>");
}
else
{
sb.Append("<label class=\"weui-cell weui-check__label\" style=\"background-color:#ccc\">" + model.mc + " - 预约人数已满</label>");
}
}
return sb.ToString();
}
[AllowAnonymous]
public JsonResult saveJzyy(ym_yymx model)
{
if (Session["openuser"] == null || Session["openuser"].ToString() == "")
{
return Json(new { State = 0, Message = "获取关注信息失败请重新打开疫苗预约页面!" });
}
if (model.yyrq.Date > Convert.ToDateTime("2020-04-30"))
{
return Json(new { State = 0, Message = "4月30号后不能预约" });
}
model.openid = Session["openuser"].ToString();
model.yysj = DateTime.Now;
ym_yymxBll bll = new ym_yymxBll();
var result = bll.save(model);
return Json(result);
}
[AllowAnonymous]
public JsonResult deletejzyy(string id)
{
ym_yymxBll bll = new ym_yymxBll();
var result = bll.delete(id);
return Json(result);
}
/// <summary>
/// 保存预约人数
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public JsonResult saveyyrs(ym_yysjd model)
{
BLL.ym_yysjdBll bll = new ym_yysjdBll();
return Json( bll.save(model));
}
public string getymyysjdwh()
{
BLL.ym_yysjdBll bll = new ym_yysjdBll();
var list = bll.GetAllList("");
return Newtonsoft.Json.JsonConvert.SerializeObject(new { Rows = list, Total = list.Count });
}
public ActionResult ymyysjdwh()
{
return View();
}
public JsonResult delyyrs(string id)
{
return Json(new ym_yysjdBll().delete(id));
}
public ActionResult YYList()
{
return View();
}
public JsonResult getYYList(int page, int pagesize, string xm, string yyrq)
{
var user = Session["loginUser"] as ERPUser;
var bll = new ym_yymxBll();
int count = bll.getyyCount(xm, yyrq);
var list = bll.getYYList(xm, yyrq,page,pagesize);
return Json(new { Total = count, Rows = list });
}
/// <summary>
/// 日期段是否可以预约
/// </summary>
/// <param name="rq"></param>
/// <param name="endtime"></param>
/// <returns></returns>
[AllowAnonymous]
public JsonResult canSelected(string rq, string endtime, string jgid, string CYFA)
{
return Json(new ym_yysjdBll().canSelected(rq, endtime), JsonRequestBehavior.AllowGet);
}
#endregion
#region
public JsonResult savetjyysjd(tj_yysjd model)
{
BLL.tj_yysjdBll bll = new tj_yysjdBll();
return Json(bll.save(model));
}
public string gettjyysjdwh()
{
BLL.tj_yysjdBll bll = new tj_yysjdBll();
var list = bll.GetAllList("");
return Newtonsoft.Json.JsonConvert.SerializeObject(new { Rows = list, Total = list.Count });
}
public ActionResult tjyysjdwh()
{
var tjjg = new DAL.weixinDal().getyyjg();
ViewData["tjjg"] = new SelectList(tjjg, "jgid", "jgmc");
return View();
}
public JsonResult deltjyysjd(string id)
{
return Json(new tj_yysjdBll().delete(id));
}
#endregion
}
}