完善微信公众号对接基础功能

This commit is contained in:
2020-02-20 16:31:10 +08:00
parent f28c84f3bb
commit acf28e8b6f
10 changed files with 1874 additions and 110 deletions
+44 -105
View File
@@ -8,6 +8,12 @@ using COMCMS.Web.Common;
using Senparc.Weixin.MP;
using NewLife.Log;
using COMCMS.Common;
using Senparc.CO2NET.HttpUtility;
using System.Threading;
using COMCMS.API.Weixin.CustomMessageHandler;
using Senparc.Weixin;
using Senparc.NeuChar.MessageHandlers;
using Senparc.Weixin.MP.MvcExtension;
namespace COMCMS.Web.Controllers
{
@@ -15,122 +21,55 @@ namespace COMCMS.Web.Controllers
{
[HttpGet]
[ActionName("Index")]
public ActionResult Get(PostModel postModel, string echostr, int id = 0)
public Task<ActionResult> Get(string signature, string timestamp, string nonce, string echostr)
{
string token = cfg.Token;
if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token))
{
return Content(echostr); //返回随机字符串则表示验证通过
}
else
{
return Content("failed:" + postModel.Signature + ","
+ Senparc.Weixin.MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, token) + "。" +
"如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
}
return Task.Factory.StartNew(() =>
{
if (CheckSignature.Check(signature, timestamp, nonce, token))
{
return echostr; //返回随机字符串则表示验证通过
}
else
{
return "failed:" + signature + "," + Senparc.Weixin.MP.CheckSignature.GetSignature(timestamp, nonce, token) + "。" +
"如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。";
}
}).ContinueWith<ActionResult>(task => Content(task.Result));
}
//#region 处理微信接口 消息,事件等
///// <summary>
///// 用户发送消息后,微信平台自动Post一个请求到这里,并等待响应XML。
///// PS:此方法为简化方法,效果与OldPost一致。
///// v0.8之后的版本可以结合Senparc.Weixin.MP.MvcExtension扩展包,使用WeixinResult,见MiniPost方法。
///// </summary>
//[HttpPost]
//[ActionName("Index")]
//public ActionResult Post(PostModel postModel)
//{
// string token = cfg.Token;
// string appid = cfg.AppId;
// string EncodingAESKey = cfg.EncodingAESKey;
// if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token))
// {
// return Content("参数错误!");
// }
// #region 打包 PostModel 信息
// postModel.Token = token;//根据自己后台的设置保持一致
// postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致
// postModel.AppId = appid;//根据自己后台的设置保持一致
// #endregion
// //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
// var maxRecordCount = 10;
#region 处理微信接口 消息,事件等
[HttpPost]
[ActionName("Index")]
public async Task<IActionResult> Post(PostModel postModel)
{
string token = cfg.Token;
if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token))
{
return Content("参数错误!");
}
var cancellationToken = new CancellationToken();//给异步方法使用
var messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, 10);
#region 设置消息去重
// //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
// var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);
/* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
* 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能
// #region 设置消息去重
messageHandler.DefaultMessageHandlerAsyncEvent = DefaultMessageHandlerAsyncEvent.SelfSynicMethod;
// /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
// * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
// messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能
#endregion
await messageHandler.ExecuteAsync(cancellationToken); //执行微信处理过程(关键)
// #endregion
// try
// {
// #region 记录 Request 日志
string content = messageHandler.TextResponseMessage.Replace("\r\n", "\n");
// var logPath = Server.MapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd")));
// if (!Directory.Exists(logPath))
// {
// Directory.CreateDirectory(logPath);
// }
return Content(content, "text/xml");
//return new FixWeixinBugWeixinResult(messageHandler);
// //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
// messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", Utils.GetRandomChar(20),
// messageHandler.RequestMessage.FromUserName,
// messageHandler.RequestMessage.MsgType)));
// if (messageHandler.UsingEcryptMessage)
// {
// messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", Utils.GetRandomChar(20),
// messageHandler.RequestMessage.FromUserName,
// messageHandler.RequestMessage.MsgType)));
// }
}
#endregion
// #endregion
// //执行微信处理过程
// messageHandler.Execute();
// #region 记录 Response 日志
// //测试时可开启,帮助跟踪数据
// //if (messageHandler.ResponseDocument == null)
// //{
// // throw new Exception(messageHandler.RequestDocument.ToString());
// //}
// if (messageHandler.ResponseDocument != null)
// {
// messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", Utils.GetRandomChar(20),
// messageHandler.ResponseMessage.ToUserName,
// messageHandler.ResponseMessage.MsgType)));
// }
// if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null)
// {
// //记录加密后的响应信息
// messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", Utils.GetRandomChar(20),
// messageHandler.ResponseMessage.ToUserName,
// messageHandler.ResponseMessage.MsgType)));
// }
// #endregion
// //return Content(messageHandler.ResponseDocument.ToString());//v0.7-
// //return new WeixinResult(messageHandler);//v0.8+
// return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
// }
// catch (Exception ex)
// {
// #region 异常处理
// XTrace.WriteLine("MessageHandler错误:{0}", ex.Message);
// return Content("");
// #endregion
// }
//}
//#endregion
}
}