@page
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Mvc
@using System.Collections.Generic;
@using System.Data;
@using System.Data.SqlClient;
@using ZoomLa.BLL;
@using ZoomLa.BLL.API;
@using ZoomLa.Common;
@using ZoomLa.Model;
@using ZoomLa.Safe;
@using ZoomLa.SQLDAL;
@using ZoomLa.SQLDAL.SQL;
@using Newtonsoft.Json;
@using Newtonsoft.Json.Linq;
@using ZoomLa.AppCode.Verify;
@using System.Threading.Tasks;
@using System.Linq;
@using System.IO;
@using ZoomLa.Components;
@using ZoomLa.BLL.Plat;
@using ZoomLa.Model.Plat;
@using Microsoft.AspNetCore.Http;
@model PageModel
@functions{
public class PageModel : Page_Base
{
public string action { get { return GetParam("action"); } }
public override int Mid { get { return DataConvert.CLng(GetParam("id")); } }
public string result = "";
B_WX_User wxuserBll = new B_WX_User();
B_WX_ReplyMsg rpBll = new B_WX_ReplyMsg();
B_WX_APPID appBll = new B_WX_APPID();
WxAPI api = null;
string baseUrl = SiteConfig.SiteInfo.SiteUrl;
//-----------------用于debug
string errmsg = "";
string requesdata = "";
M_APIResult retMod = new M_APIResult(M_APIResult.Failed);
public IActionResult OnGet()
{
return ActionDeal();
}
public IActionResult OnPost()
{
return ActionDeal();
}
//============================================================================================================
private IActionResult ActionDeal()
{
string echoString = Request.GetParam("echoStr");
string signature = Request.GetParam("signature");
string timestamp = Request.GetParam("timestamp");
string nonce = Request.GetParam("nonce");
if (Request.Method == "GET") { Auth(); return Content(result); }
try
{
requesdata = GetXml();
//requesdata = " 1434081760 6159334259197323209 ";
if (string.IsNullOrEmpty(requesdata)) { return Content(result); }
M_WxTextMsg reqMod = new M_WxTextMsg(requesdata);
//多公众号情况下开启,获取需要返回的公众号
M_WX_APPID appmod = appBll.GetAppByWxNo(reqMod.ToUserName);
if (appmod == null) { api = WxAPI.Code_Get("公众号"); } else { api = WxAPI.Code_Get(appmod); }
errmsg += "动作:" + reqMod.MsgType;
switch (reqMod.MsgType)
{
case "event"://事件--关注处理,后期扩展单击等
{
//M_WxImgMsg msgMod = JsonConvert.DeserializeObject(appmod.WelStr);
M_WxImgMsg msgMod = new M_WxImgMsg();
msgMod.ToUserName = reqMod.FromUserName;
msgMod.FromUserName = reqMod.ToUserName;
WxEventHandler(reqMod);//系统事件处理
//登录检测,可按需取消或修改位置
M_UserInfo mu = UserBindCheck(reqMod);
//if (mu.IsNull)
//{
// msgMod.Articles.Add(new M_WXImgItem()
// {
// Title = "请先关联用户",
// Description = "你尚未关联用户,点击登录关联用户",
// Url = baseUrl + "/User/Login?WXOpenID=" + reqMod.FromUserName
// });
// RepToClient(msgMod.ToXML());
//}
WxMenuBtnHandler(reqMod, msgMod, mu);
}
break;
case "text"://接收文本消息
{
string xml = UserTextDeal(reqMod);
RepToClient(xml);
}
break;
}
}
catch (Exception ex) { ZLLog.L("微信报错," + errmsg + ",数据:" + requesdata + ",原因:" + ex.Message); }
return Content(result);
}
private void RepToClient(string xml)
{
//自返回,用于避免线程中断报错
//Response.Clear();
//Response.Write(xml);
//Response.Flush();
//Response.End();
result = xml;
}
//检测用户是否关联用户,未关联用户则直接返回,否则返回用户信息
//帐户在所有公众号通用
private M_UserInfo UserBindCheck(M_WxTextMsg reqMod)
{
B_User_Token tokenBll = new B_User_Token();
M_User_Token tokenMod = tokenBll.SelByOpenID(reqMod.FromUserName, "WX");
M_UserInfo mu = new M_UserInfo(true);
if (tokenMod == null)
{
}
else { mu = buser.SelReturnModel(tokenMod.uid); }
return mu;
}
///
/// 系统事件,如订阅等处理
///
private void WxEventHandler(M_WxTextMsg reqMod)
{
M_WX_User userMod = null;
errmsg += ",事件:" + reqMod.Event;
switch (reqMod.Event.ToLower())
{
case "subscribe":
#region 关注事件
//写入用户信息
userMod = api.GetWxUserModel(reqMod.FromUserName);
userMod.AppId = api.AppId.ID;
M_WX_User umod = wxuserBll.SelForOpenid(reqMod.FromUserName);
if (umod != null) { userMod.ID = umod.ID; wxuserBll.UpdateByID(userMod); }
else { wxuserBll.Insert(userMod); }
//显示欢迎语
if (!string.IsNullOrEmpty(api.AppId.WelStr))
{
M_WxImgMsg msgmod = JsonConvert.DeserializeObject(api.AppId.WelStr);
msgmod.ToUserName = reqMod.FromUserName;
msgmod.FromUserName = reqMod.ToUserName;
if (string.IsNullOrEmpty(msgmod.Articles[0].PicUrl)) //如未设置图片则以纯文本格式发送,纯文本支持内置超链接
{
M_WxTextMsg textMod = ImageToText(msgmod);
RepToClient(textMod.ToXML());
}
else
{
RepToClient(msgmod.ToXML());
}
}
else
{
M_WxTextMsg msgMod = new M_WxTextMsg();
msgMod.ToUserName = reqMod.FromUserName;
msgMod.FromUserName = reqMod.ToUserName;
msgMod.Content = "欢迎关注[" + SiteConfig.SiteInfo.SiteName + "]";
RepToClient(msgMod.ToXML());
}
//关注时发送多条信息
//System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SendMsg), reqMod);
#endregion
break;
case "unsubscribe":
//wxuserBll.DelByOpenid(reqMod.FromUserName);
{
//取消关注只移除粉丝
//userMod = wxuserBll.SelForOpenid(reqMod.FromUserName);
//if (userMod != null)
//{
// wxuserBll.Del(userMod.ID);
//}
}
break;
case "location"://用户进入公众号(包含定位信息)
{
}
break;
case "scan"://带参数的二维码扫描进入(关注事件在上方处理)
{
//二维码所带的参数
string scenceStr = reqMod.EventKey;
}
break;
default:
break;
}
}
//private void SendMsg(Object info)
//{
// try
// {
// M_WxTextMsg reqMod = (M_WxTextMsg)info;
// System.Threading.Thread.Sleep(1000);//延迟1秒,避免先于欢迎消息
// M_WX_APPID appmod = new B_WX_APPID().GetAppByWxNo(reqMod.ToUserName);
// if (appmod == null) { throw new Exception("目标公众号[" + reqMod.ToUserName + "]不存在"); }
// WxAPI.Code_Get(appmod).SendMsg(reqMod.FromUserName, "test");
// }
// catch (Exception ex) { ZLLog.L("微信多信息出错,原因:" + ex.Message); }
//}
///
/// 自定义单击事件处理,按需扩展
///
private void WxMenuBtnHandler(M_WxTextMsg reqMod, M_WxImgMsg msgMod, M_UserInfo mu)
{
//switch (reqMod.Event)
//{
// case "CLICK":
// break;
//}
//
//
//1450326669
//
//
//
//
switch (reqMod.EventKey)
{
case "menu_0_btn_0"://项目进度
{
msgMod.Articles.Add(new M_WXImgItem()
{
Title = mu.UserName + "[项目进度]的信息1",
Description = "点击访问[项目进度]信息",
//PicUrl=baseUrl+"/Template/Ke/style/images/login1.png",
Url = baseUrl + "/User/Default"
});
RepToClient(msgMod.ToXML());
}
break;
case "menu_0_btn_1":
{
M_WxTextMsg textMod = new M_WxTextMsg()
{
MsgType = "text",
CreateTime = reqMod.CreateTime,
Content = "点击访问[发布项目]信息",
FromUserName = msgMod.FromUserName,
ToUserName = msgMod.ToUserName
};
RepToClient(textMod.ToXML());
}
break;
}
}
//用户文件信息处理
private string UserTextDeal(M_WxTextMsg reqMod)
{
//if (reqMod.Content.Equals("母亲节"))
//{
// string r = ZoomLa.BLL.APIHelper.GetWebResult("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + api.AccessToken, "POST", "{\"touser\":\"" + reqMod.FromUserName + "\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"P4zZGc5Q0p_fiAB2BuQABssIUSDxdJOVIqftgiHxKsk\"}}");
// System.Threading.Thread.Sleep(1000); //不能延长太久,否则会重发,发送推荐使用图片或纯文本
//}
M_WX_ReplyMsg rpMod = rpBll.SelByFileAndDef(appBll.GetAppByWxNo(reqMod.ToUserName).ID, reqMod.Content);
M_WxImgMsg msgMod = new M_WxImgMsg();
msgMod.ToUserName = reqMod.FromUserName;
msgMod.FromUserName = reqMod.ToUserName;
//如果未匹配到则直接返回
string result = "";
if (rpMod == null)
{
msgMod.Articles.Add(new M_WXImgItem() { Title = "未找到相关联的操作" });
result = msgMod.ToXML();
}
else//如果匹配到
{
M_WXImgItem item = JsonConvert.DeserializeObject(rpMod.Content);
msgMod.Articles.Add(item);
switch (rpMod.MsgType)
{
case "0":
M_WxTextMsg textMod = ImageToText(msgMod);
result = textMod.ToXML();
break;
case "1":
result = msgMod.ToXML();
break;
case "5":
result = ""
+ ""
+ ""
+ "12345678"
+ ""
+ ""
+ ""
+ "";
break;
}
if (rpMod.fiter.Equals("关键词"))
{
//M_WxImgMsg myMsg = new M_WxImgMsg();
//msgMod.ToUserName = reqMod.FromUserName;
//msgMod.FromUserName = reqMod.ToUserName;
//M_WX_ReplyMsg imgMod = rpBll.SelReturnModel(1);
//M_WXImgItem myItem = JsonConvert.DeserializeObject(rpMod.Content);
//myMsg.Articles.Add(myItem);
//api.SendImgMsg(myMsg);
ZoomLa.BLL.APIHelper.GetWebResult("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + api.AccessToken, "POST", "{\"touser\":\"" + reqMod.FromUserName + "\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"P4zZGc5Q0p_fiAB2BuQABkS9XdXmADDdjB-w5l8FPYY\"}}");
}
}
return result;
}
//用于处理微信初次验证
private void Auth()
{
string echoString = Request.GetParam("echoStr");
string signature = Request.GetParam("signature");
string timestamp = Request.GetParam("timestamp");
string nonce = Request.GetParam("nonce");
RepToClient(echoString);
//string token = "demo";
//if (CheckSignature(token, signature, timestamp, nonce))
//{
// if (!string.IsNullOrEmpty(echoString))
// {
// HttpContext.Current.Response.Write(echoString);
// HttpContext.Current.Response.End();
// }
//}
}
//------------------Tools
private string GetXml()
{
var buffer = new MemoryStream();
Request.Body.CopyTo(buffer);
byte[] inputdata = new byte[buffer.Length];
buffer.Read(inputdata, 0, inputdata.Length);
return System.Text.Encoding.UTF8.GetString(inputdata);
}
// 验证微信签名
private bool CheckSignature(string token, string signature, string timestamp, string nonce)
{
string[] ArrTmp = { token, timestamp, nonce };
Array.Sort(ArrTmp);
string tmpStr = string.Join("", ArrTmp);
//tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = EncryptHelper.SHA1(tmpStr).ToLower();// tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
//图文消息转文本(存储时以图片消息为准)
//文本的优点在于,可以内置超链接
private M_WxTextMsg ImageToText(M_WxImgMsg msgmod)
{
M_WxTextMsg textMod = new M_WxTextMsg();
textMod.ToUserName = msgmod.ToUserName;
textMod.FromUserName = msgmod.FromUserName;
textMod.Content = msgmod.Articles[0].Description;
textMod.CreateTime = DateTime.Now.Millisecond;
textMod.MsgType = "text";
return textMod;
}
}
}
@{
Layout = null;
}