using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.Tencent;

public partial class WXWork_MessageHandler : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string Token = eBase.WXWorkAccount.getValue("Token");
        string EncodingAESKey = eBase.WXWorkAccount.getValue("EncodingAESKey");
        string CorpID = eBase.WXWorkAccount.getValue("CorpID");
        
        string signature = eParameters.QueryString("signature");        // 微信加密签名
        string timestamp = eParameters.QueryString("timestamp");        // 时间戳
        string nonce = eParameters.QueryString("nonce");                // 随机数

        if (Request.HttpMethod.ToUpper() == "GET")
        {
            string echostr = eParameters.QueryString("echostr");        // 随机字符串
            if(!string.IsNullOrEmpty(echostr))
            {
                string result = Cryptography.AES_decrypt(echostr, EncodingAESKey, ref CorpID);
                eBase.Writeln(result);
            }
            else
            {
                Response.Write("Verification passed");
                Response.End();
            }
        }
        else if (Request.HttpMethod.ToUpper() == "POST")
        {
            string msgsignature = eParameters.QueryString("msg_signature"); // 微信加密签名
            string signxml = eBase.getPostString();
            if (signxml.Length > 10)
            {
                WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Token, EncodingAESKey, CorpID);
                string xml = "";
                int ret = wxcpt.DecryptMsg(msgsignature, timestamp, nonce, signxml, ref xml);
                if (ret == 0)
                {
                    //eBase.AppendLog(xml);
                    Hashtable ht = eBase.ParseXml(xml);// xml请求解析
                    eTable etb = new eTable("WXWorkMessages");
                    etb.Fields.Add("SiteID", eBase.getSiteID());
                    etb.Fields.Add("ToUserName", ht["ToUserName"]);
                    etb.Fields.Add("FromUserName", ht["FromUserName"]);
                    etb.Fields.Add("CreateTime", ht["CreateTime"]);
                    etb.Fields.Add("MsgType", ht["MsgType"]);
                    etb.Fields.Add("Body", ht["Content"]);
                    etb.Fields.Add("MsgId", ht["MsgId"]);
                    etb.Fields.Add("AgentID", ht["AgentID"]);
                    etb.Fields.Add("Result", xml);
                    etb.Add();
                }
            }
        }
    }
}