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 WeChat_MessageHandler : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string AppID = eBase.WeChatAccount.getValue("AppID");
        string Token = eBase.WeChatAccount.getValue("Token");
        string EncodingAESKey = eBase.WeChatAccount.getValue("EncodingAESKey");
        //eBase.AppendLog(AppID + "::" + Token + "::" + EncodingAESKey + "::" + Request.Url.PathAndQuery);

        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 (CheckSignature(Token, signature, timestamp, nonce))
            {
                Response.Write(echostr);
            }
            else
            {
                Response.Write("Verification passed");
            }
            Response.End();
            //WeixinServer.createMenu();
            //WeixinServer.deleteMenu();
        }
        else if (Request.HttpMethod.ToUpper() == "POST")
        {
            string xml = eBase.getPostString();
            string msgsignature = eParameters.QueryString("msg_signature"); // 微信加密签名  
            if (!string.IsNullOrEmpty(msgsignature))
            {
                WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Token, EncodingAESKey, AppID);
                string result = "";
                int ret = wxcpt.DecryptMsg(msgsignature, timestamp, nonce, xml, ref result);
                if (ret == 0)
                {
                    xml=result;
                }

            }
            Hashtable ht = eBase.ParseXml(xml);// xml请求解析
            eTable etb = new eTable("WeChatMessages");
            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("Result", xml);
            etb.Add();

            //WeixinServer.processRequest(xml);
        }
    }
    private bool CheckSignature(string token, string signature, string timestamp, string nonce)
    {
        //string[] arr = new[] { token, timestamp, nonce }.OrderBy(s => s).ToArray();
        String[] arr = new String[] { token, timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典序排序  
        Array.Sort<String>(arr);

        string tmpStr = string.Join("", arr);
        var sha1 = System.Security.Cryptography.SHA1.Create();
        byte[] hash = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(tmpStr)); // 微信使用ASCII编码生成签名
        StringBuilder sb = new StringBuilder();
        foreach (byte b in hash)
        {
            sb.Append(b.ToString("x2"));
        }
        return sb.ToString() == signature;
    }
}