一、c#微信公众号开发----基本设置
参考微信官方文档
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
开发→基本配置
公众号开发信息
注:1.记录好开发者密码,会在程序中验证过程中使用到。
2.通过appid和appsecret调用access_token时,至有在ip白名单的ip才能成功调用。
服务器配置
若此处开启服务器配置,设置的自动回复和自定义菜单将全部失效。必须在程序中重写相关方法。
点击修改配置,token为随意填写的参数
我是用的是一般处理程序编写的微信接口token验证,参数参考官方文档。代码如下:
开发者通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
public void ProcessRequest(HttpContext context){
//验证token
string postString = string.Empty;
string token ="aabbcc"; //验证token,随意填写
if(string.IsNullEmpty(token)){
return ;
}
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["sianature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
if(CheckSignature(token,signature,timestamp,nonce)){
if(!string.IsNullOrEmpty(echiString)){
HttpContext.Current.Response.Write(echoString);
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// 验证微信签名
/// </summary>
/// <param name="token">token</param>
/// <param name="signature">签名</param>
/// <param name="timestamp">时间戳</param>
/// <param name="nonce">随机数</param>
/// <returns></returns>
public static bool CheckSignature(string token,
string signature, string timestamp, string nonce)
{
string[] ArrTmp = { token, timestamp, nonce };
//字典排序
Array.Sort(ArrTmp);
//拼接
string tmpStr = string.Join("", ArrTmp);
//sha1验证
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
//tmpStr = Membership.CreateUser(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower(); if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
将编写的代码路径,填写到url里,前面填写的“aabbcc”,此时token里填写的也必须为“aabbcc”。
token必须保持一致,若不一致会弹出提示。
二、获取timestamp/nonce/signature
timestamp时间戳
public static string timestamp(){
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
nonce随机数
public static string getNoncestr(){
Random random = new Random();
return Md5Util.GetMD5(random.Next(1000).ToString(),”GBK”).ToLower().Replace(“s”,”S”);
}
signature随机数
public static string Signature(string token, string timestamp, string nonce){
string[] ArrTmp = { token, timestamp, nonce };
//字典排序
Array.Sort(ArrTmp);
//拼接
string tmpStr = string.Join("", ArrTmp);
//sha1验证
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
return tmpStr;
}