C#微信公众号学习

主要分为两部分:

1、创建C#的项目,并发布,

2、微信填写发布的地址进行开发者验证。

一、

VS环境为VS2017,创建项目时,自带的一些东西发布会导致各种错误,无奈,创建了空项目aspx窗体,如下图:

创建后,项目很干净,新建一个窗体,我这里创建的是Default.aspx,

前端示例:

后端示例:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WeiXinDemo
{
    public partial class Default : System.Web.UI.Page
    {
        //自己的token,需要和服务器地址配置中保持一致
        // const string Token = "weixin";
        //从配置文件获取Token
        string Token = ConfigurationManager.AppSettings["WeixinToken"];
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            Valid();
        }

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

        /// <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.Equals(signature))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

 WebConfig中添加 一行代码如下:

此时将项目进行发布,部署到服务器(端口号一般为80,此处端口号限制请看微信公众平台文档)

二、

打开微信测试账号申请地址:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

填写项目部署的URL及Token值点击提交即可,

原文地址:https://www.cnblogs.com/Violety/p/9776368.html