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.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using WxPayAPI;
namespace dccdc.Controllers
{
public class InfectionWXController : Controller
{
[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.InfectionToken, Common.Global.InfectionEncodingAESKey, Common.Global.InfectionAppId);
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 = ExecText(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;
string scene = root["EventKey"] == null ? "" : root["EventKey"].InnerText.Replace("qrscene_", "");
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.InfectionAppId);
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("Appsecret:" + Global.InfectionAppsecret);
InfectionOpenUserModel ou = getopenuser(openid);
ou.remark = scene;
ou.recommendold = RecommendNumber();
//推荐码已存在
while (new BLL.InfectionOpenUserInfoBll().JudgementCode(ou.recommendold) == "True")
{
ou.recommendold = RecommendNumber();
}
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info("openuser:" + Newtonsoft.Json.JsonConvert.SerializeObject(ou));
try
{
new BLL.InfectionOpenUserBll().updateOpenUserInfection(ou);
}
catch (Exception ex)
{
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(ex.Message);
}
var data = new
{
touser = openid,
template_id = "x8mjZxVpKoOg8TiYVevRcDjKxBYjFqAHi7PRIetidp8",
url = "http://oa.dcqcdc.com/dccdc/Infection/personInfoEntering",
data = new
{
first = new { value = "您好,为了更好与您交流,请完善您的个人信息", color = "#173177" },
keyword1 = new { value = "个人信息", color = "#173177" },
keyword2 = new { value = "德城健康e路", color = "#173177" },
//keyword3 = new { value = model.ADate.ToString("yyyy-MM-dd"), color = "#173177" },
remark = new { value = "点击完善个人信息。", color = "#173177" },
}
};
WebClient wc = new WebClient();
wc.UploadData("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + Common.Global.getAccessTokenInfection.access_token, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(data)));
var comm = new BLL.Common();
string xiaoxi = @"
1-
";
//string xiaoxi = @"";
msg = CreateNews(openid, "news", xiaoxi);
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":
new BLL.InfectionOpenUserBll().updateRemarkInfection(openid, scene);
break;
}
}
}
return msg;
}
private string ExecText(XmlDocument doc)
{
string msg = string.Empty;
XmlNode root = doc.FirstChild;
var element = root["FromUserName"];
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(element);
if (element != null)
{
string openid = element.InnerText;
msg = CreateKF(openid, "transfer_customer_service");
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType).Info(msg);
}
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.InfectionToken, 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 获取微信信息
///
/// 读取微信用户信息
///
///
///
private InfectionOpenUserModel getopenuser(string openid)
{
var accessToken = Common.Global.getAccessTokenInfection;
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(token);
if (string.IsNullOrEmpty(ou.openid))
{
error err = Newtonsoft.Json.JsonConvert.DeserializeObject(token);
Exception wx = new Exception(err.errmsg + "\r\n" + err.errcode);
throw wx;
}
return ou;
}
#endregion
///
/// 生成返回消息
///
///
///
///
///
string CreateNews(string touser, string type, string xiaoxi)
{
string msg = @"" + GetNowTime() + @"" + xiaoxi + @" ";
return msg;
}
///
/// 生成返回消息
///
///
///
///
///
string CreateKF(string touser, string type)
{
string msg = @"" + GetNowTime() + @" ";
return msg;
}
///
/// 获取时间差
///
///
int GetNowTime()
{
return (int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1))).TotalSeconds;
}
///
/// 通过时间差获取时间
///
///
///
DateTime getTime(int tick)
{
return TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)).AddSeconds(tick);
}
///
/// 关注用户页面
///
///
public ActionResult OpenUserList()
{
List erpList = new ERPUserBll().GetSelectList();
List itemList = new List();
foreach (ERPUser user in erpList)
{
SelectListItem item = new SelectListItem()
{
Value = user.ID.ToString(),
Text = user.TrueName.ToString()
};
itemList.Add(item);
}
SelectList select = new SelectList(itemList, "Value", "Text");
ViewBag.OAList = select;
return View();
}
///
/// 获取关注用户列表
///
///
///
///
///
///
public JsonResult getOpenUserList(string nc, string bz, int page, int pagesize)
{
InfectionOpenUserBll bll = new InfectionOpenUserBll();
ERPUserBll ErpBll = new ERPUserBll();
int count = bll.getGZCountInfection(nc, bz);
List list = bll.getGZListInfection(nc, bz, page, pagesize);
for(int i = 0; i < list.Count; i++)
{
string trueName = ErpBll.GetTrueNameById(list[i].oa_id);
list[i].oa_trueName = trueName;
}
return Json(new { Total = count, Rows = list });
}
///
/// 备注关注用户
///
///
///
///
public JsonResult remark(string openid, string bz)
{
try
{
var bll = new InfectionOpenUserBll();
var c = bll.remarkGZInfection(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.getAccessTokenInfection.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(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 });
}
}
///
/// 备注关注用户
///
///
///
///
public JsonResult userState(string id, string type ,string oaId)
{
try
{
var bll = new InfectionOpenUserBll();
if (string.IsNullOrEmpty(oaId))
{
oaId = "0";
}
int i = bll.updateAdminById(id, type, oaId);
if (i>0)
{
return Json(new { State = 1, Message = "修改成功!" });
}
else
{
return Json(new { State = 0, Message = "修改失败!" });
}
}
catch (Exception ex)
{
return Json(new { State = 0, Message = ex.Message });
}
}
//添加用户信息页面
public ActionResult addOpenUserInfoQuery(string id)
{
InfectionOpenUserInfoModel model = new InfectionOpenUserInfoModel();
if (id != null && id != "") {
model.user_id = int.Parse(id);
}
ViewBag.user_id = model.user_id;
ViewBag.src = model.license;
List list = new InfectionOpenCrowdBll().GetOpenDataList();
List itemList = new List();
foreach (InfectionOpenCrowdModel crowd in list)
{
SelectListItem item = new SelectListItem()
{
Value = crowd.id.ToString(),
Text = crowd.name.ToString()
};
itemList.Add(item);
}
SelectList select = new SelectList(itemList, "Value", "Text");
ViewBag.crowdList = select;
return View(model);
}
//保存用户信息
[HttpPost]
public string addOpenUserInfoQuerySave(InfectionOpenUserInfoModel model)
{
InfectionOpenUserInfoBll bll = new InfectionOpenUserInfoBll();
if (Request.Files.Count == 0)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 0, Message = "没有要处理的文件" });
}
else
{
try
{
string path = string.Empty;
string address = string.Empty;
path = Server.MapPath("~/photo/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string specificDate = DateTime.Now.ToString("yyyyMMdd").ToString();
path += specificDate + "/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
address = DateTime.Now.ToString("HHmmss") + "-" + Guid.NewGuid().ToString() + ".jpg";
path += address;
Request.Files[0].SaveAs(path);
address = "/photo/" + specificDate + "/" + address;
model.license = address;
DateTime date = new DateTime();
date = DateTime.Now;
model.create_time = date.ToString("yyyy-MM-dd hh:mm:ss");
bll.Add(model);
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 1, Message = "保存成功!" });
}
catch (Exception ex)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { State = 0, Message = ex.Message });
}
}
//DateTime date = new DateTime();
//date = DateTime.Now;
//model.create_time = date.ToString("yyyy-MM-dd hh:mm:ss");
//return Json(bll.Add(model));
}
#region 菜单维护
///
/// 微信菜单管理
///
///
public ActionResult Menu()
{
return View();
}
///
/// 微信菜单类型
///
///
[HttpPost]
public JsonResult getCDLX()
{
return Json(
new[]
{
new { id="zu",name="菜单组" },
new { id="click",name="点击推事件" },
new { id="view",name="跳转URL" }
}
);
}
///
/// 获取菜单列表
///
///
[HttpPost]
public string getMeun()
{
// string sql = "select * from menu";
var dt = new BLL.InfectionMenuBll().getMenuInfection();
return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}
///
/// 获取上级菜单
///
///
[HttpPost]
public string getSJCD()
{
var dt = new BLL.InfectionMenuBll().getSJCDInfection();
var dr = new Models.InfectionMenuModel
{
id = 0,
name = "顶级菜单"
};
dt.Insert(0, dr);
return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}
///
/// 删除菜单
///
/// 菜单ID
///
[HttpPost]
public JsonResult delCD(int id)
{
return Json(new BLL.InfectionMenuBll().delCdInfection(id));
}
///
/// 保存菜单
///
/// 菜单实体
///
[HttpPost]
public JsonResult saveCD(Models.InfectionMenuModel m)
{
return Json(new BLL.InfectionMenuBll().saveCDInfection(m));
}
#endregion
#region 发送菜单
///
/// 提交微信菜单
///
///
[HttpPost]
public string CreateWXMenu()
{
List