微信公众平台教程之C#开发实例

首先你先去 https://mp.weixin.qq.com/  登录你的账号

微信公众平台教程之C#开发实例_第1张图片

点击左上角的高级功能


进入开发模式


首先你得成为开发者,成为开发者你要填写一个URL和TOKEN,TOKEN可以随便填写。。

因为本篇讲的是C#实例,所以新建一个defaut.aspx ,然后在PAGE_Load里填写方法,注意页面端口只能是80

腾讯给了一个PHP例子,方便给PHP开发使用,我把他给翻译成了C#

PHP例子:

valid();

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "
							
							
							%s
							
							
							0
							";             
				if(!empty( $keyword ))
                {
              		$msgType = "text";
                	$contentStr = "Welcome to wechat world!";
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }else{
                	echo "Input something...";
                }

        }else {
        	echo "";
        	exit;
        }
    }
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>

上面这个例子就是验证一下你填写的URL是不是存在,腾讯会给你填写的URL POST过来一个叫echostr的随机数,然后你页面如果返回写入echostr就证明你此页面存在。

你URL就能通过了

下面是C#

private const string TOKEN = "你页面填写的TOKEN";
protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                string echoStr = HttpContext.Current.Request["echostr"];
                if (echoStr != "")
                {
                    if (checkSignature())
                    {
                        HttpContext.Current.Response.ContentType = "text/plain";
                        HttpContext.Current.Response.Write(echoStr);
                    }
                }
            }
            catch (Exception ex)
            {
                string wrongText = string.Empty;
                wrongText = ex.Message;
                File.WriteAllText(Server.MapPath("~/") + @"\test.txt", wrongText);

            }
            finally
            {
                HttpContext.Current.Response.End();
            }
        }
#region 检测Signature
        private bool checkSignature()
        {
            string signature = HttpContext.Current.Request["signature"];
            string timestamp = HttpContext.Current.Request["timestamp"];
            string nonce = HttpContext.Current.Request["nonce"];
            List tmpArr = new List();
            tmpArr.Add(TOKEN);
            tmpArr.Add(timestamp);
            tmpArr.Add(nonce);
            tmpArr.Sort();
            string a = string.Join("", tmpArr);
            SHA1 hash = SHA1CryptoServiceProvider.Create();
            byte[] plainTextBytes = Encoding.ASCII.GetBytes(a);
            byte[] hashBytes = hash.ComputeHash(plainTextBytes);
            string localChecksum = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            if (signature == localChecksum)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

上面的代码,如果你的URL已经通过的话,就可以把Page_Load里的代码注释掉了,他只在你填写URL时使用到,一旦你的URL通过的话,上面的代码就没用了


再次你就成功成为开发者了。。

现在你如果给你的微信服务号发送消息的话,就给你填写的URL POST数据了

各种方法文档在http://mp.weixin.qq.com/wiki/index.php?title=%E9%A6%96%E9%A1%B5

因为上面的PAGE_LOAD里的代码已经注释没用了,现在PAGE_LOAD里的数据就是要获取腾讯POST过来的数据了

 protected void Page_Load(object sender, EventArgs e){
            XmlNode RequestXML = null; 
            string Content = "";
            int index = 0;
            try
            {
                byte[] data = Request.BinaryRead(Request.TotalBytes);//获取腾讯传过来的数据,他POST过来的是一个XML
                String xmlData = Encoding.UTF8.GetString(data);//转换成STRING
                XmlDocument requestXml = Converter.StringToXmlDocument(xmlData);//把String转成XML,这个大家百度搜一下方法,我就不发了
                XmlNode rootNode = requestXml.SelectSingleNode("xml");//获取根节点
                XmlNode FromUserNameNode = rootNode.SelectSingleNode("FromUserName");
                XmlNode ToUserNameNode = rootNode.SelectSingleNode("ToUserName");
                XmlNode ContentNode = rootNode.SelectSingleNode("Content");
                XmlNode MsgIdNode = rootNode.SelectSingleNode("MsgId");
                string ToUserName = ToUserNameNode == null ? "" : ToUserNameNode.InnerText;
                string FromUserName = FromUserNameNode == null ? "" : FromUserNameNode.InnerText;
                Content = ContentNode == null ? "" : ContentNode.InnerText;
                string MsgId = MsgIdNode == null ? "" : MsgIdNode.InnerText;
                long ticks = DateTime.Now.Ticks;
                string time = ticks.ToString();
                DateTime dt = new DateTime(ticks);
                string AddToDBxml = string.Format(@"
							{0}
							{1}
							{2}
							text
							{3}
                            0
							", ToUserName, FromUserName, time, Content);//上面的XML是用户发送消息后,你获取到的,你可以根据用户发过来的内容做判断,比如上面的Content如果是1,就代表用户发过来的是1,你就可以返回对应的内容了,下面是你要返给用户的XML
             string xml = string.Format(@"
							{0}
							{1}
							{2}
							text
							{3}
                            0
							", FromUserName, ToUserName, time, ResponseContentNode.InnerText);
                //把数据重新返回给客户端
                try
                {
                    HttpContext.Current.Response.ContentType = "text/xml";
                    HttpContext.Current.Response.Write(xml);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                }
                catch
                {

                }


好了,自动回复的实例就是这些了。。下面是自定义菜单的实现代码


      private string GetToken()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID + "&secret=" + AppSecret + "";//你成为开发者后会有一个appID和appSecret
            string response = HttpGet(url);
            JavaScriptSerializer json = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
            ToJson list = json.Deserialize(response);    //将json数据转化为对象类型并赋值给list
            access_token = list.access_token;      //获取JSON里access_token值
            return access_token;
        }
        #region Get
        /// 
        /// HTTP GET方式请求数据.
        /// 
        /// URL.
        /// 
        public string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }

            return responseStr;
        }
        #endregion
        #region POST
        /// 
        /// HTTP POST方式请求数据
        /// 
        /// URL.
        /// POST的数据
        /// 
        public string HttpPost(string url, string param)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    File.WriteAllText(Server.MapPath("~/") + @"\test.txt", responseStr);
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;
        }
        #endregion
        #region 中转对象
        public struct ToJson
        {
            public string access_token { get; set; }  //属性的名字,必须与json格式字符串中的"key"值一样。
            public string expires { get; set; }
        }
        #endregion
//比如我要调用自定义菜单 

  
 string CreateMenu = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
 jsonstr.Append("{\"button\":[{").Append("\"type\":\"").Append("click").Append("\",\"name\":\"").Append("test").Append("\",\"key\":").Append("\"V1001_TODAY_MUSIC\"").Append("},{").Append("\"type\":\"").Append("click").Append("\",\"name\":\"").Append("moman").Append("\",\"key\":").Append("\"V1001_TODAY_MUSIC\"").Append("},").Append("{\"name\":\"").Append("菜单").Append("\",\"sub_button\":[").Append("{\"type\":\"").Append("view").Append("\",\"name\":\"").Append("搜索").Append("\",\"url\":\"").Append("http://www.soso.com\"}]").Append("}]").Append("},");
                    string jsonStr = jsonstr.ToString();
                    if (jsonStr.LastIndexOf(',') > 0)
                        jsonStr = jsonStr.Substring(0, jsonStr.LastIndexOf(','));
                    jsonStr = jsonStr.Replace(@"\", "/");
                    string url = CreateMenu + GetToken();
                    string returnData = HttpPost(url, jsonStr); //returnData 返回的是 {"errcode":0,"errmsg":"ok"} 此时,你取消服务号关注,在添加关注,菜单就生成了

你可能感兴趣的:(C#)