.Net实现微信公众平台开发接口(一) 之 “微信开发配置”

   我们只要通过微信官方认证,成为开发者,才能实现微信提供的各种接口,否则即使调用了接口,微信也不会实现推送,功能也无法通过开发模式真正得到实现,所以需要正确配置微信信息,通过微信官方认证,成为开发者才可以进行下一步的接口开放。

一、客户端需要配置的信息

      客户端配置微信信息的时候大概需要参数有:

序号 参数 说明
1  URL 验证开发者身份的url
2 token 用于校验
3 wechat_name 微信号
4 appid 调用微信接口的凭证
5 appsecret 调用微信接口的凭证密钥
6 wechat_originalid 微信原始id
7 wechat_type 微信类型(服务号,订阅号,企业号)
8 wechat_key 为了安全起见,在url后面加的标示参数

     这些信息都要保存到客户端中,所以我们创建数据库表字段的时候按照上面的参数即可,如下

CREATE TABLE [dbo].[w_wechat](
    [wechat_id] [int] IDENTITY(1,1) NOT NULL,
    [wechat_name] [varchar](250) NULL,
    [wechat_key] [varchar](250) NULL,
    [wechat_url] [varchar](250) NULL,
    [wechat_token] [varchar](250) NULL,
    [wechat_appid] [varchar](250) NULL,
    [wechat_appsecret] [varchar](250) NULL,
    [wechat_originalid] [varchar](250) NULL,
    [wechat_addtime] [datetime] NULL,
    [wechat_isdel] [int] NULL,
    [wechat_stutas] [int] NULL,
    [user_id] [int] NULL,
    [wechat_type] [int] NULL,
 CONSTRAINT [PK_w_wechat] PRIMARY KEY CLUSTERED 
(
    [wechat_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
View Code

    至于如何保存,这里就不在多说,通过三层和mvc都可以,这里只要页面的代码贴出来大家看看

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using weixin.Model;
using weixin.DAL;

namespace weixinWeb.web.admin.wechat
{
    public partial class bindapi : weixinWeb.web.admin.cs.adminbase
    {
        w_wechat_dal wechatdal = new w_wechat_dal();

        protected w_wechat_model wechatmodel = new w_wechat_model();
        protected DataTable dtweixin = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            dtweixin = wechatdal.GetList(" user_id =" + user_id).Tables[0];
            //打开页面就获取并保存url和token信息 
            if (dtweixin.Rows.Count <= 0)
            {
                string weixin_key = Guid.NewGuid().ToString();
                string weixin_url = "http://" + Request.Url.Authority + "/web/wechat/api/wechatapi.aspx?key=" + weixin_key;//url
                wechatmodel.wechat_token = GetRandom();//token用来验证每次的接口访问
                wechatmodel.wechat_url = weixin_url;
                wechatmodel.wechat_key = weixin_key;
                wechatmodel.wechat_addtime = DateTime.Now;
                wechatmodel.user_id = int.Parse(user_id);
                wechatdal.Add(wechatmodel);
            }
            else
            {
                wechatmodel = wechatdal.GetModel(int.Parse(dtweixin.Rows[0]["wechat_id"].ToString()));
            }
            switch (Request.Form["action"])
            {
                case "bindapi":
                    api();
                    break;
            }
        }
        /// <summary>
        /// 修改和保存微信配置信息
        /// </summary>
        private void api()
        {
            dtweixin = wechatdal.GetList(" user_id =" + user_id).Tables[0];
            if (dtweixin.Rows.Count > 0)
            {
                wechatmodel = wechatdal.GetModel(int.Parse(dtweixin.Rows[0]["WeChat_ID"].ToString()));
                wechatmodel.wechat_name = Request.Form["weixin_name"].Trim().ToString();//微信名称
                wechatmodel.wechat_appid = Request.Form["appid"].Trim().ToString();//凭证
                wechatmodel.wechat_appsecret = Request.Form["appsecret"].Trim().ToString();//凭证钥匙
                wechatmodel.wechat_originalid = Request.Form["originalid"].Trim().ToString();//微信原始id
                wechatmodel.wechat_type = int.Parse(Request.Form["is_show"].Trim().ToString());//公众号类型(服务号,订阅号)
                wechatdal.Update(wechatmodel);
                Response.Write("{"errno":"0","tip":"设置成功!","url":"bindapi.aspx","error":""}");
            }
            Response.End();
        }
        #region 获取10位随即数(字符串类型)
        /// <summary>
        /// 获取10位随即数(字符串类型)
        /// </summary>
        /// <returns></returns>
        private string GetRandom()
        {
            Random ran = new Random();
            int RandomValue = ran.Next(999999999) + 1000000000;
            return RandomValue.ToString();
        }
        #endregion 获取10位随即数(字符串类型)

    }
}
View Code

    其中这里要说的是

string weixin_key = Guid.NewGuid().ToString();
string weixin_url = "http://" + Request.Url.Authority + "/web/wechat/api/wechatapi.aspx?key=" + weixin_key;//url
wechatmodel.wechat_token = GetRandom();//token用来验证每次的接口访问

url的地址wechatapi.aspx主要是用来验证微信信息的,下面会重点说说这个页面

token是随机生成的一个说,主要在官网输入的和客户端一致就可以,token可以随意获取。

二、微信url和token验证基本原理和流程

      微信是如何验证url和token的呢,假如填写的url和token信息为

URL: http://demo.xxx.com/web/wechat/api/wechatapi.aspx?key=d26bd9ae-5a4f-45d6-bb91-c434e3a7087a
ToKen:1369750827 

首先、开发者提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:

参数描述
signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp 时间戳
nonce 随机数
echostr 随机字符串

其次、客户端接受到这四个参数后,需要进行验证处理:

加密/校验流程如下:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
 也就是通过客户端的token,和微信服务器发送过来的timestamp,nonce进行字典排序,组成字符串并通过sha1加密,然后和微信服务器发送过来的signature进行比较,如果一样,则验证通过,并返回接收的echostr,

验证通过后,正确返回echostr,则表示接入成功,成为开发者,否则需要检查配置信息。

三、客户端验证处理

      首先,开发端接收微信服务器发送的参数,并按照验证流程进行验证signature是否一致,代码如下

    wechatapi.aspx

        /// <summary>
        /// 验证微信签名
        /// </summary>
        /// <returns></returns>
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
        private bool CheckSignature()
        {
            string WeChat_Token = "";
            string WeChat_Key = Request.QueryString["key"];

            DataTable dtWeChat = wechatdal.GetList("wechat_key='" + WeChat_Key + "'").Tables[0];

            if (dtWeChat.Rows.Count > 0)
            {
                WeChat_Token = dtWeChat.Rows[0]["wechat_token"].ToString();
            }
            //从微信服务器接收传递过来的数据
            string signature = Request.QueryString["signature"]; //微信加密签名
            string timestamp = Request.QueryString["timestamp"];//时间戳
            string nonce = Request.QueryString["nonce"];//随机数
            string[] ArrTmp = { WeChat_Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);//将三个字符串组成一个字符串
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");//进行sha1加密
            tmpStr = tmpStr.ToLower();
            //加过密的字符串与微信发送的signature进行比较,一样则通过微信验证,否则失败。
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion 验证微信API接口
View Code

     若验证通过,正确返回echostr

        /// <summary>
        /// 验证微信API接口
        /// </summary>
        private void CheckWeChat()
        {
            string echoStr = Request.QueryString["echoStr"];

            if (CheckSignature())
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    Response.Write(echoStr);
                    Response.End();
                }
            }
        }
View Code

     最后,微信访问页面的时候就要对其进行处理验证,所以事件要放到页面加载的地方

   protected void Page_Load(object sender, EventArgs e)
        {
          
                //微信通过get请求验证api接口
                CheckWeChat();
            
        }

这样就基本完成了微信公众平台的配置和验证,成为开发者,下一步就是获取access_token,实现各个接口了。

      

原文地址:https://www.cnblogs.com/shuang121/p/4000139.html