1 首先服务器跟域名指向的80端口必须不能缺少。
2 然后在企业号后台配置里选择回调模式,选择回调模式时候需要配置域名。这时候就跟我们的代码相关了,这一次的配置,对于服务器来说,属于get的请求,我们要在服务器上面写上get请求的方法,以及返回值,如果通过,则配置成功,否则无法往下面开发。
贴上代码:#region 回调模式下发送任务
public static void ProcessRequest()
{
Logger.Info(HttpContext.Current.Request.HttpMethod.ToUpper());
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
{
GetInitsetInfo();
}
else if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
{
EvenClick();
}
}
public static PipelineCountForWebchat GetTaskCountForWebchat(int PositionID, String EID)
{
var context = HttpContext.Current;
string url = string.Format("{0}Api/Pipeline/GetTaskCountForWebchat?PositionID={1}&EID={2}", ConfigurationManager.AppSettings["WebAPI"], PositionID, EID);
PipelineCountForWebchat wxMsg = ApiProxy.Call<PipelineCountForWebchat>(url, "GET", null, null);
context.Session.Timeout = 24 * 60;
return wxMsg;
}
public static void EvenClick()
{
Logger.Info("Post数据");
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string sReqMsgSig = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
string sReqTimeStamp = HttpContext.Current.Request.QueryString["timestamp"];
string sReqNonce = HttpContext.Current.Request.QueryString["nonce"];
Logger.Info("signature=" + sReqMsgSig);
Logger.Info("echoString=" + echoString);
Logger.Info("timestamp=" + sReqTimeStamp);
Logger.Info("nonce=" + sReqNonce);
//读取发过来的信息到inputXml变量中
Stream sin = HttpContext.Current.Request.InputStream;
if (sin.Length == 0)
{
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.Write("<xml>error</xml>");
return;
}
byte[] readBytes;
readBytes = new byte[sin.Length];
sin.Read(readBytes, 0, readBytes.Length);
string inputXml = Encoding.UTF8.GetString(readBytes);
Logger.Info("input xml:{0}" + inputXml);
Logger.Info("1");
//使用XMLDocument加载信息结构
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(inputXml);
Logger.Info("2");
string sMsg = ""; //解析之后的明文
Logger.Info("3");
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
Logger.Info("4");
int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, inputXml, ref sMsg);
Logger.Info(ret.ToString());
if (ret != 0)
{
Logger.Info("ERR: Decrypt fail, ret: " + ret);
return;
}
Logger.Info("解析后数据: " + sMsg);
XmlDocument _nxmlDoc = new XmlDocument();
_nxmlDoc.LoadXml(sMsg);
//把传过来的XML数据各个字段区分出来,并且填到fields这个字典变量中去
Dictionary<string, string> fields = new Dictionary<string, string>();
Logger.Info("Xml里的数据有多少个 " + _nxmlDoc.SelectSingleNode("/xml").ChildNodes.Count);
foreach (XmlNode x in _nxmlDoc.SelectSingleNode("/xml").ChildNodes)
{
Logger.Info(x.Name + "*****" + x.InnerText);
fields.Add(x.Name, x.InnerText);
}
// 发送方帐号(open_id)
String fromUserName = fields["FromUserName"];
// 公众帐号
String toUserName = fields["ToUserName"];
// 消息类型
String msgType = fields["MsgType"];
//事件类型
String Event = fields["Event"];
//消息Key
String EventKey = fields["EventKey"];
Logger.Info("用户开始登陆" + fromUserName);
McdPMTContext.GetLoginUserByEmportId(fromUserName);
String Content = "";
Logger.Info("登陆成功继续执行");
//string host = HttpContext.Current.Request.Url.Host;
//string path = HttpContext.Current.Request.Path;
//string redirect_uri = HttpUtility.UrlEncode("http://" + host + path);
string redirect_uri = "http://pmtstg02.mcd.com.cn";
switch (EventKey)
{
case "Task":
if (McdPMTContext.CurrentUser != null)
{
PipelineCountForWebchat Wxmsg = McdPMTContext.GetTaskCountForWebchat(McdPMTContext.CurrentUser.PositionID, McdPMTContext.CurrentUser.EID);
Content = @"<item>
<PicUrl><![CDATA[" + Wxmsg.TopUrl + @"]]></PicUrl>
<Url><![CDATA[" + Wxmsg.TopUrl + @"]]></Url>
</item>
<item>
<Title><![CDATA[PP待处理 (" + Wxmsg.toBePending_PP + @")]]></Title>
<Url><![CDATA[https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx42cf5e73876fe3b9&redirect_uri=http%3a%2f%2fpmtonair02.mcd.com.cn%2fWxApproveFramePage?url=Pipeline/PendingIndex&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect]]></Url>
</item>
<item>
<Title><![CDATA[PP待批复 (" + Wxmsg.toBeApproved_PP + @")]]></Title>
<Url><![CDATA[https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx42cf5e73876fe3b9&redirect_uri=http%3a%2f%2fpmtonair02.mcd.com.cn%2fWxApproveFramePage?url=Pipeline/ApprovedIndex&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect]]></Url>
</item>
<item>
<Title><![CDATA[AM待批复 (" + Wxmsg.toBeApproved_Store + @")]]></Title>
<Url><![CDATA[https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx42cf5e73876fe3b9&redirect_uri=http%3a%2f%2fpmtonair02.mcd.com.cn%2fWxApproveFramePage?url=Store/ApprovedIndex&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect]]></Url>
</item>
";
//发送消息
SendTextReplyMessage(fromUserName, toUserName, Content);
}
else
{
Content = "您的账号不在我们的服务内,请联系管理员进行设置";
SendTextReplyMessage(fromUserName, toUserName, Content);
}
// String Content = @"<item>
// <PicUrl><![CDATA[http://love.doghouse.com.tw/image/wallpaper/011102/bf1554.jpg]]></PicUrl>
// <Url><![CDATA[http://love.doghouse.com.tw/image/wallpaper/011102/bf1554.jpg]]></Url>
// </item>
// <item>
// <Title><![CDATA[待处理]]></Title>
// <Url><![CDATA[http://love.doghouse.com.tw/image/wallpaper/011102/bf1554.jpg]]></Url>
// </item>
// <item>
// <Title><![CDATA[待批复]]></Title>
// <Url><![CDATA[http://love.doghouse.com.tw/image/wallpaper/011102/bf1554.jpg]]></Url>
// </item>";
// SendTextReplyMessage(fromUserName, toUserName, Content);
break;
default:
Logger.Info("开始跳转到OnAir页面" + EventKey);
break;
}
}
/// <summary>
/// 获取基本配置信息
/// </summary>
public static void GetInitsetInfo()
{
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
string sPostData = HttpContext.Current.Request.QueryString["sPostData"];
string sMsg = HttpContext.Current.Request.QueryString["sMsg"];
Logger.Info("signature=" + signature);
Logger.Info("echoString=" + echoString);
Logger.Info("timestamp=" + timestamp);
Logger.Info("nonce=" + nonce);
Logger.Info("sPostData=" + sPostData);
Logger.Info("sMsg=" + sMsg);
Logger.Info("以下是配置信息");
Logger.Info("token=" + token);
Logger.Info("encodingAESKey=" + encodingAESKey);
Logger.Info("corpId=" + corpId);
string decryptEchoString = "";
if (CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString))
{
if (!string.IsNullOrEmpty(decryptEchoString))
{
HttpContext.Current.Response.Write(decryptEchoString);
HttpContext.Current.Response.End();
}
}
}
public static bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
{
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr);
if (result != 0)
{
Logger.Error("ERR: VerifyURL fail, ret: " + result);
return false;
}
return true;
//ret==0表示验证成功,retEchostr参数表示明文,用户需要将retEchostr作为get请求的返回参数,返回给企业号。
// HttpUtils.SetResponse(retEchostr);
}
//当前语言
public static String Language
{
get
{
return CultureInfo.CurrentCulture.Name;
}
}
#region 新的方法
//发送被动响应文本消息:
/// <summary>
/// 发送被动响应文本消息,需要先加密在发送
/// </summary>
/// <param name="fromUserName">发送方</param>
/// <param name="toUserName">接收方</param>
/// <param name="content">文本内容</param>
public static void SendTextReplyMessage(string fromUserName, string toUserName, string content)
{
DateTime newTime = Convert.ToDateTime(DateTime.Now.ToLocalTime().ToString());
long strTime = newTime.Ticks;
TextReplyMessage msg = new TextReplyMessage()
{
CreateTime = strTime,
FromUserName = fromUserName,
ToUserName = toUserName,
Content = content
};
/* LogInfo.Info("发送信息2sMsg=" + content);//也可以使用微信的接口发送消息
TextMsg data = new TextMsg(content);
data.agentid = "7";
data.safe = "0";
// data.toparty = "@all";
// data.totag = "@all";
data.touser = toUserName;
BLLMsg.SendMessage(data);*/
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
string msg_signature = HttpContext.Current.Request.QueryString["msg_signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
string encryptResponse = "";//加密后的文字
string sMsg = msg.ToXmlString();//加密前的文字
int isok = wxcpt.EncryptMsg(sMsg, timestamp, nonce, ref encryptResponse);//
Logger.Info("发送信息sMsg=" + sMsg);
if (isok == 0 && !string.IsNullOrEmpty(encryptResponse))
{
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Write(encryptResponse);//被动相应消息不需要调用微信接口
}
else
{
Logger.Info("发送信息失败isok=" + isok);
}
}
//被动响应消息实体
/// <summary>
/// 被动响应消息类
/// </summary>
public abstract class ReplyMessage
{
public string ToUserName { get; set; }
public string FromUserName { get; set; }
public long CreateTime { get; set; }
/// <summary>
/// 将对象转化为Xml消息
/// </summary>
/// <returns></returns>
public abstract string ToXmlString();
}
/// <summary>
/// 被动响应文本消息
/// </summary>
public class TextReplyMessage : ReplyMessage
{
/// <summary>
/// 回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)
/// </summary>
public string Content { get; set; }
/// <summary>
/// 将对象转化为Xml消息
/// </summary>
/// <returns></returns>
public override string ToXmlString()
{
string s = @"<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[{3}]]></MsgType>
<ArticleCount>4</ArticleCount>
<Articles>{4}</Articles>
</xml>";
s = string.Format(s,
ToUserName ?? string.Empty,
FromUserName ?? string.Empty,
CreateTime.ToString(),
"news",
Content ?? string.Empty
);
return s;
}
}
#endregion
#endregion
点击查看更多内容
5人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦