C# .Net 小程序消息推送配置+详细代码
首先在微信公众平台登录小程序账号
第一步登陆
登录后,在首页-功能-订阅信息,打开后如未进行配置,需要进行后台配置。
第二步:填写服务器配置
登录微信公众平台官网后,在公众平台官网的开发-基本设置页面,勾选协议成为开发者,点击“修改配置”按钮,填写服务器地址(URL)、Token和EncodingAESKey,其中URL是开发者用来接收微信消息和事件的接口URL。Token可由开发者可以任意填写,用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)。EncodingAESKey由开发者手动填写或随机生成,将用作消息体加解密密钥。
同时,开发者可选择消息加解密方式:明文模式、兼容模式和安全模式。模式的选择与服务器配置在提交后都会立即生效,请开发者谨慎填写及选择。加解密方式的默认状态为明文模式,选择兼容模式和安全模式需要提前配置好相关加解密代码。
第三步:验证消息的确来自微信服务器
开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
检验signature的C#示例代码(本人自己写):
public void ProcessRequest(HttpContext context){HttpRequest request = context.Request;HttpResponse response = context.Response;Dictionary<string, string> dictionary = new Dictionary<string, string>();dictionary.Add("timestamp", request["timestamp"]);dictionary.Add("nonce", request["nonce"]);dictionary.Add("Token", "自己设置的token");dictionary = dictionary.Where(a => !string.IsNullOrEmpty(a.Value)).OrderBy(b => b.Value).ToDictionary(c => c.Key, c => c.Value);//进行排序StringBuilder builder = new StringBuilder();foreach (var v in dictionary){builder.Append(v.Value);}string echostr = request["echostr"];//验证成功返回微信请求的随机字符串if(request["signature"]== SHA1(builder.ToString()).ToLower()){response.Write(echostr);log.Info("验证成功,返回=" + echostr);}else{response.Write(false);log.Info("验证失败");}response.End();}/// <summary>/// SHA1 加密/// </summary>/// <param name="content">需要加密字符串</param>public string SHA1(string content){return SHA1(content, Encoding.UTF8);}/// <summary>/// SHA1 加密/// </summary>/// <param name="content">需要加密字符串</param>/// <param name="encode">指定加密编码</param>public string SHA1(string content, Encoding encode){try{SHA1 sha1 = new SHA1CryptoServiceProvider();byte[] bytes_in = encode.GetBytes(content);byte[] bytes_out = puteHash(bytes_in);sha1.Dispose();string result = BitConverter.ToString(bytes_out);result = result.Replace("-", "");return result;}catch (Exception ex){log.Info("SHA1加密出错:" + ex.Message);return "";}}
成功返回微信服务器后,即可申请模板-点击选用-选择所需内容点击提交(如下图)。
接入配置结束,具体请看官方文档–小程序开发接入文档
C#接口代码
第一步,获取token
//token实体类public class AccessToken{public string access_token {get; set; }public int expires_in {get; set; }}//获取微信tokenprivate string Exe_Access_token(){string appid = "小程序的appid";string secret = "小程序的秘钥";HttpResponse Response = HttpContext.Current.Response;JavaScriptSerializer serializer = new JavaScriptSerializer();string access_token = string.Empty;AccessToken accesstoken = (AccessToken)serializer.Deserialize(HttpPostRequest("https://api./cgi-bin/token", "grant_type=client_credential&appid=" + appid + "&secret=" + secret), typeof(AccessToken));//请求微信服务器HttpCookie cookie_access_token_create = new HttpCookie("access_token", HttpUtility.UrlEncode(accesstoken.access_token));//创建Cookiecookie_access_token_create.Expires = DateTime.Now.AddSeconds(accesstoken.expires_in);Response.AppendCookie(cookie_access_token_create);access_token = accesstoken.access_token;return access_token;}//post请求方法public static string HttpPostRequest(string path, string parameter){string result = string.Empty;try{byte[] b = Encoding.UTF8.GetBytes(parameter);HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";request.ContentLength = b.Length;using (Stream s = request.GetRequestStream()){s.Write(b, 0, b.Length);}using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){using (StreamReader sr = new StreamReader(response.GetResponseStream())){result = sr.ReadToEnd().Trim();}}}catch{result = string.Empty;}return result;}
第二步,请求发送
private void WxNotification(HttpRequest request){string openid = request["openid"];//此处openid是用户的openidstring http = HttpPostRequest("https://api./cgi-bin/message/subscribe/send?access_token=" + Exe_Access_token(),"{\"touser\":\"" + openid + "\"," +"\"template_id\":\"pr8jhwtQ\"," + //template_id就是申请的模板ID"\"data\":" +"{\"character_string1\":{\"value\":\"Dy09261714\"}," + //分别对应申请的模板详细内容"\"phrase2\":{\"value\":\"打包中\"}," +"\"date3\":{\"value\":\"" + DateTime.Now.ToString() + "\"}" +"}}");log.Info(http);}
模板内容如下图所示
最后一步-小程序代码
页面代码
<view><button bindtap="testbutton">确认下单</button></view>
Js代码
testbutton:function(){wx.requestSubscribeMessage({tmplIds: ['4pr8jhwtQ'],//申请的模板idsuccess (res) {//reject 用户取消 accept 用户同意if(res.rZPwDiPjoS7yaY3QlWFENS8lirpPaMbFFE4pr8jhwtQ=="accept"){wx.request({url: '',//上面服务器配置的域名data:{openid:openid//用户的openid},header: {'Content-Type': "application/x-www-form-urlencoded",},method: "POST",success:function(req){}})}}})}
最后调试结果如下:
小程序订阅消息官方文档