C#微信公众平台开发者模式开启代码

摘要:
使用系统;使用System.IO;使用System.Text;使用System.Web.Security;名称空间HPZJ。网状物系统。excel{publicpartialclasshpd_api_weixin:System.Web.UI.Page{conststringToken=“token”;//您的tokenprotectedvoidPage

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();
            }
        }
    }
}

成功后显示下面截图

C#微信公众平台开发者模式开启代码第1张

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

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 += "{ ";
        weixin1 += ""button":[ ";
        weixin1 += "{ ";
        weixin1 += ""type":"click", ";
        weixin1 += ""name":"公司简介", ";
        weixin1 += ""key":"jianjie" ";
        weixin1 += "}, ";
        weixin1 += "{ ";
        weixin1 += ""type":"click", ";
        weixin1 += ""name":"在线订房", ";
        weixin1 += ""key":"order" ";
        weixin1 += "}, ";
        weixin1 += "{ ";
        weixin1 += ""name":"我的菜单", ";
        weixin1 += ""sub_button":[ ";
        weixin1 += "{ ";
        weixin1 += ""type":"click", ";
        weixin1 += ""name":"子菜单1", ";
        weixin1 += ""key":"zcd1" ";
        weixin1 += "}, ";
        weixin1 += "{ ";
        weixin1 += ""type":"view", ";
        weixin1 += ""name":"子菜单2", ";
        weixin1 += ""key":"zcd2" ";
        weixin1 += "}] ";
        weixin1 += "}] ";
        weixin1 += "} ";
        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#微信公众平台开发者模式开启代码》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇eclipse版本信息及操作系统六、Spring Cloud 之旅 -- Feign 更优雅的REST客户端介绍 使用 及 自定义注解器和处理请求下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

将json文件转换成insert语句的sql文件

引入是要的maven依赖: 1 <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> 2 <dependency> 3 <groupId>com.google.code.gson</groupId> 4 &l...

在.net中实现压缩多个文件为.zip文件 【转】

这段时间一直在做一个网站,其中遇到了一个问题,就是在服务器端压缩多个服务器端的文件,然后在供客户下载。说白了就是用户上传了多个文件,然后别的用户可以点击批量下载这些文件。我要做的就是实现把这些文件压缩之后供用户下载。        我首先想到的是.Net提供的GZipStream类,翻了一下书才发现GZipStream没有提供加压多个文件的方法,需要自己定...

Java接口自动化框架增加钉钉机器人配置,自动发送测试结果

1.utils目录下新建DingDingUtil类 package utils; import com.alibaba.fastjson.JSONObject;import org.apache.http.client.methods.CloseableHttpResponse;import restclient.RestClient; import ja...

Quartz.Net系列(五):Quartz五大构件Job之JobBuilder解析

 所有方法图: 1.Create,OfType  在JobBuilder中有五种方法执行Action: var job1 = JobBuilder.Create().OfType<FirstJob>().Build(); var job2 = JobBuilder.Create<Firs...

Dubbo学习笔记12:使用Dubbo中需要注意的一些事情

指定方法异步调用 前面我们讲解了通过设置ReferenceConfig的setAsync()方法来让整个接口里的所有方法变为异步调用,那么如何指定某些方法为异步调用呢?下面讲解下如何正确地设置默写方法为异步调用。 假如你只需要设置接口里的方法sayHello为异步调用,那么可以使用下面方式: final List<MethodConfig> a...

java与json互相转换(解决日期问题)

JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。本文主要讲解下java和JSON之间的转换,特别是解决互相转换遇到日期问题的情况。 一、需要相关的jar包: json-lib-xxx.jar ezmorph-xxx.jar c...