您的位置:首页 > 移动开发 > 微信开发

微信公众号开发--开发服务器接入微信服务器

2016-09-18 00:16 351 查看
1.微信公众号注册
到微信公众平台(https://mp.weixin.qq.com/)注册公众号。
公众号有“服务号”,“订阅号”,“企业号”三种类别,“服务号”主要面向企业和个人,“订阅号”主要面向组织和个人。
申请完毕后,登陆公众号,进入管理界面,公众号对应的二维码如下所示:



2.开发服务器配置



URL是开发者用来接收微信消息和事件的接口URL
Token可由开发者任意填写,用作生成签名
EncodingAESKey由开发者手动填写或随机生成,将用作消息体加解密秘钥

3.验证开发服务器地址有效性
开发者提交信息后,微信服务器将发送GET请求到开发服务器URL,GET请求有四个参数:
signature:微信加密签名
signature结合了token,timestamp,nonce三个参数
timestamp:时间戳
nonce:随机数
echostr:随机字符串

开发者通过检验signature对请求进行检验,若检验成功,接入生效,否则接入失败

加密/检验流程如下:
1)将token,timestamp,nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串雨signature对比

检验signature的C#示例代码如下:

wxapi.ashx

<%@ WebHandler Language="C#" Class="wxapi" %>

using System;
using System.Web;
using System.IO;
using System.Text;
using System.Web.Security;
public class wxapi : IHttpHandler {

public void ProcessRequest (HttpContext context) {
string postString = string.Empty;
Auth(); //微信接入的测试
}
/// <summary>
/// 成为开发者的第一步,验证并相应服务器的数据
/// </summary>
private void Auth()
{
string token = "weixin";//从配置文件获取Token
if (string.IsNullOrEmpty(token))
{

}

string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];

if (CheckSignature(token, signature, timestamp, nonce))
{
if (!string.IsNullOrEmpty(echoString))
{
HttpContext.Current.Response.Write(echoString);
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// 验证微信签名
/// </summary>
public bool CheckSignature(string token, string signature, string timestamp, string nonce)
{
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;
}
}
public bool IsReusable {
get {
return false;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: