using System;
using System.IO;
using System.Text;
using System.Web.Security;

namespace HPZJ.Web.sys.excel
{
    public partial class hpd_api_weixin : System.Web.UI.Page
    {
        const string Token = "token";  //你的token
        protected void Page_Load(object sender, EventArgs e)
        {
            string postStr = "";

Valid();
            if (Request.HttpMethod.ToLower() == "post")
            {
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                postStr = Encoding.UTF8.GetString(b);
                if (!string.IsNullOrEmpty(postStr))
                {
                    ResponseMsg(postStr);
                }
                //WriteLog("postStr:" + postStr);
            }
        }

/// <summary>
        /// 验证微信签名
        /// </summary>
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
        /// <returns></returns>
        private bool CheckSignature()
        {
            string signature = Request.QueryString["signature"].ToString();
            string timestamp = Request.QueryString["timestamp"].ToString();
            string nonce = Request.QueryString["nonce"].ToString();
            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

private void Valid()
        {
            string echoStr = Request.QueryString["echoStr"].ToString();
            if (CheckSignature())
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    Response.Write(echoStr);
                    Response.End();
                }
            }
        }

/// <summary>
        /// 返回信息结果(微信信息返回)
        /// </summary>
        /// <param name="weixinXML"></param>
        private void ResponseMsg(string weixinXML)
        {
            //回复消息的部分:你的代码写在这里

}

/// <summary>
        /// unix时间转换为datetime
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        private DateTime UnixTimeToTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

/// <summary>
        /// datetime转换为unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

/// <summary>
        /// 写日志(用于跟踪)
        /// </summary>
        private void WriteLog(string strMemo)
        {
            string filename = Server.MapPath("/logs/log.txt");
            if (!Directory.Exists(Server.MapPath("//logs//")))
                Directory.CreateDirectory("//logs//");
            StreamWriter sr = null;
            try
            {
                if (!File.Exists(filename))
                {
                    sr = File.CreateText(filename);
                }
                else
                {
                    sr = File.AppendText(filename);
                }
                sr.WriteLine(strMemo);
            }
            catch
            {
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }
    }
}

成功后显示下面截图

微信平台自定义菜单代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Net;

public partial class wx_weixin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
//        首先根据微信的接口说明 获取你的 access_token 值

//然后 利用提供的文件直接上传运行,根据显示的返回 参考判断是否正确,如果返回的是 {"errcode":0,"errmsg":"ok"} 则成功。
//保证能用,有问题可以咨询

//所有的 key 和name 都是可以自己定义,结合公众平台文档,根据自己需要调整

string weixin1 = "";
        weixin1 += "{\n";
        weixin1 += "\"button\":[\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"公司简介\",\n";
        weixin1 += "\"key\":\"jianjie\"\n";
        weixin1 += "},\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"在线订房\",\n";
        weixin1 += "\"key\":\"order\"\n";
        weixin1 += "},\n";
        weixin1 += "{\n";
        weixin1 += "\"name\":\"我的菜单\",\n";
        weixin1 += "\"sub_button\":[\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"子菜单1\",\n";
        weixin1 += "\"key\":\"zcd1\"\n";
        weixin1 += "},\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"view\",\n";
        weixin1 += "\"name\":\"子菜单2\",\n";
        weixin1 += "\"key\":\"zcd2\"\n";
        weixin1 += "}]\n";
        weixin1 += "}]\n";
        weixin1 += "}\n";
        string i = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=改成你自己的access_token", weixin1);
        Response.Write(i);
    }
    public string GetPage(string posturl, string postData)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            // 设置参数
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            Response.Write(err);
            return string.Empty;
        }
    }
}

C#微信公众平台开发者模式开启代码的更多相关文章

  1. 【转】C#微信公众平台开发者模式开启代码

    using System; using System.IO; using System.Text; using System.Web.Security; namespace HPZJ.Web.sys. ...

  2. MVC下c#对接微信公众平台开发者模式

    在ashx文件中进行HttpContext的处理: using System; using System.Collections.Generic; using System.Linq; using S ...

  3. php 开启微信公众号开发者模式

    php 开启微信公众号开发者模式<pre><?php/** * wechat php test */header('Content-type:text');//define your ...

  4. java版微信公众平台自定义菜单创建代码实现

    微信公众平台自定义菜单创建代码实现—java版 搞了两天的自定义菜单,终于搞定了,现在分享下心得,以便后来者少走弯路...... 好了,先看先微信官方的API 官方写的很详细,但是我看完后很茫然,不知 ...

  5. 使用 Laravel 框架:成为微信公众平台开发者

    转: http://ninghao.net/blog/1441 作者:王皓发布于:2014-05-30 13:16更新于:2014-05-31 12:05 我们可以使用Laravel 框架为微信公众平 ...

  6. tp6微信公众号开发者模式token认证

      微信公众号开发完整教程(一) PHP7.0版本,TP5.0框架 技术标签: 微信公众号开发         因为工作的需要,这一两年对微信公众号和小程序,项目制作的比较多.所以我才打算写一篇全面的 ...

  7. 微信公众平台开发者中心服务器配置Token验证失败问题

    微信发展如火如荼,没有哪家的企业营销能避开微信不谈的,那像我们这种给客户实施项目的多多少少会涉及微信端的开发,本文只要给从未做过微信开发的人做一些简单的演示,行家里手们可以呵呵一下该干嘛干嘛去了. 微 ...

  8. 微信公众平台自定义菜单创建代码实现—java版

    搞了两天的自定义菜单,终于搞定了,现在分享下心得,以便后来者少走弯路...... 好了,先看先微信官方的API 官方写的很详细,但是我看完后很茫然,不知道你们什么感觉.  我知道是post一个带参数的 ...

  9. tp6微信公众号开发者模式自定义菜单

    1,参考上篇博客,获取access_token https://www.cnblogs.com/xiaoyantongxue/p/15803334.html 2:控制器写以下代码 /* * 获取普通a ...

随机推荐

  1. Vector和Stack源码分析/List集合的总结

    序言 这篇文章算是在这list接口下的集合的最后一篇了,前面ArrayList.LinkedList都已经讲解完了,剩下就Vector和Vector的子类Stack啦.继续努力.一步一个脚印, --W ...

  2. SDWebImage清除图片缓存

    背景: 使用 SDWebImage 库,由于内存中一直缓存着加载的图片,而导致内存过高(我们无法手动管理内存),弹出内存警告而导致程序很卡或者直接crash掉. 我的解决方法: 在AppDelegat ...

  3. c#将list集合转换为datatable的简单办法

    public static class ExtensionMethods        {        /// <summary>        /// 将List转换成DataTabl ...

  4. 再谈collections模块defaultdict()和namedtuple()

    defaultdict()和namedtuple()是collections模块里面2个很实用的扩展类型.一个继承自dict系统内置类型,一个继承自tuple系统内置类型.在扩展的同时都添加了额外的很 ...

  5. 用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片

    用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片 ticons的用法可以百度 这里记录下具体的编译方法 在安装了ticons和ImageMagickDisp ...

  6. 自制jquery可编辑的下拉框

    昨天看到QQ登录的时候,可以选择以前登录过的账户,这个东西也可以在网站登录的时候用到,所以我就想做一个这样的插件:在网上查了很多,没有找到合适自己的,所以决定自动制作一个. 原理就是一个textbox ...

  7. kqueue用法简介

    1.什么是kqueue和IO复用 kueue是在UNIX上比较高效的IO复用技术. 所谓的IO复用,就是同时等待多个文件描述符就绪,以系统调用的形式提供.如果所有文件描述符都没有就绪的话,该系统调用阻 ...

  8. Windows Azure Virtual Machine (31) 迁移Azure虚拟机

    <Windows Azure Platform 系列文章目录> 为什么要写这篇Blog? 之前遇到过很多客户提问: (1)我之前创建的虚拟机,没有加入虚拟网络.现在需要重新加入虚拟机网络, ...

  9. java并发编程实践学习(2)--对象的组合

    先验条件(Precondition):某些方法包含基于状态的先验条件.例如,不能从空队列中移除一个元素,在删除元素前队列必须处于非空状态.基于状态的先验条件的操作成为依赖状态操作. 在单线程中,如果某 ...

  10. java线程(2)--同步和锁

    参考转载:http://rainyear.iteye.com/blog/1734311 http://turandot.iteye.com/blog/1704027 http://www.cnblog ...