【轉】C#微信公衆平臺開發者模式開啓代碼

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

 

成功後顯示下面截圖html

 

微信平臺自定義菜單代碼:api

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

 
原文地址:http://www.cnblogs.com/lhws/p/3324633.html
另外一篇文章推薦:http://www.cnblogs.com/netyoulan/archive/2013/04/28/3049111.html微信

相關文章
相關標籤/搜索