using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;
namespace Weixin
{
/// <summary>
/// 只适用于微信回调模式的请求
/// </summary>
public class WXCallBackService : IWXCallBack, IQYWXHandler
{
/// <summary>
/// 当你开启应用的回调模式时,企业号会要求你填写应用的URL、Token、EncodingAESKey三个参数。
/// URL是企业应用接收企业号推送请求的访问协议和地址,支持http或https协议。
/// Token可由企业任意填写,用于生成签名。
/// EncodingAESKey用于消息体的加密,是AES密钥的Base64编码。
/// </summary>
#region 自定义参数
private string sToken { get { return System.Configuration.ConfigurationManager.AppSettings["Token"]; } }
private string sCorpID {get {return System.Configuration.ConfigurationManager.AppSettings["CorpID"];}}
private string sEncodingAESKey {get{return System.Configuration.ConfigurationManager.AppSettings["EncodingAESKey"];}}
#endregion
#region 私有属性
private HttpRequest Request;
private string Response = string.Empty;
public string wxResponse
{
get{return this.Response;}
}
private Tencent.WXBizMsgCrypt wxcpt { get; set; }
#endregion
#region 构造函数
/// <summary>
/// 构造函数 赋予初始值
/// </summary>
/// <param name="wxRequest">微信的回调模式的请求</param>
public WXCallBackService(HttpRequest wxRequest)
{
this.Request = wxRequest;
Utils.LogHelper.Instance.Start(); //日志记录,记录请求的地址、以及解密的参数与返回的解密的密文
Utils.LogHelper.Instance.WriteLog(this.Request.Url);
#region 从web.config中获取微信企业号参数,并初始化微信加解密对象
Utils.LogHelper.Instance.WriteLog("Token:" + this.sToken, Utils.LogType.Notice);
Utils.LogHelper.Instance.WriteLog("EncodingAESKey:" + this.sEncodingAESKey, Utils.LogType.Notice);
Utils.LogHelper.Instance.WriteLog("CorpID:" + this.sCorpID, Utils.LogType.Notice);
this.wxcpt = new Tencent.WXBizMsgCrypt(this.sToken, this.sEncodingAESKey, this.sCorpID);
#endregion
if (wxRequest.HttpMethod.ToLower() == "get")
{
/*
* 微信请求方式为get时,表示需要验证唯一标识的服务器,我们需要按照微信的消息加解密的方法去解密,返回明文
* 也可以使用EchoStr参数是否设置,区分
*/
this.Response = CheckSignature();
}
else
{
/*
* 当微信请求方式为post时.表示微信用户给公众号发送了消息
*/
string postString = string.Empty;
using (Stream stream = this.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = System.Text.Encoding.UTF8.GetString(postBytes);
}
if (!string.IsNullOrEmpty(postString))
{
this.Response = responseMsg(postString);
}
}
}
#endregion
#region 微信回调模式的接口方法
/// <summary>
/// 验证微信Token的函数,一般新建一个企业应用只需验证一次
/// </summary>
/// <returns>echostr的明文字符串</returns>
public string CheckSignature()
{
/*
------------验证回调URL------