.NET之微信消息模板推送

前端之家收集整理的这篇文章主要介绍了.NET之微信消息模板推送前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言:  

  最近在项目中使用到了微信消息模板推送的功能,也就是将对应的消息推送到对应的用户微信上去,前提是你必须要有一个微信公众号并且是付费了的才会有这个功能,还有就是要推送的用户必须是的关注了你的微信公众号的。

  这个流程是这样的首先用户关注你的微信公众号,让后获取到对应用户的oppenid,然后就可以通过对应的用户oppenid选折对应的消息模板把消息推送给用户

实现:

添加功能插件

  

找到模板消息:

  

选折对应的消息模板:

  

参数说明:

@H_403_139@
参数 是否必填 说明
touser 接收者openid
template_id 模板ID
url 模板跳转链接(海外帐号没有跳转能力)
miniprogram 小程序所需数据,不需跳小程序可不用传该数据
appid 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系,暂不支持小游戏)
pagepath 所需跳转小程序的具体页面路径,支持带参数,(示例index?foo=bar),要求该小程序已发布,暂不支持小游戏
data 模板数据
color 模板内容字体颜色,不填默认为黑色

代码实现:

  1. using System;
  2. System.IO;
  3. System.Net;
  4. System.Text;
  5. Newtonsoft.Json;
  6. namespace JJHL.Service
  7. {
  8. /// <summary>
  9. /// 微信消息推送
  10. </summary>
  11. public class WxChatPrompt
  12. {
  13. public WxChatPrompt()
  14. {
  15. }
  16. private static WxChatPrompt _objPrompt;
  17. WxChatPrompt _
  18. {
  19. get => _objPrompt ?? new WxChatPrompt();
  20. set => _objPrompt = value;
  21. }
  22. <summary>
  23. 消息推送
  24. </summary>
  25. <param name="Access_token">网页授权凭证,通过微信接口获取</param>
  26. <param name="Openid">要推送的用户oppenid<returns></returns>
  27. string MsgPush(string Access_token,string Openid)
  28. {
  29. string templateId = "";//模板编号
  30. string firstContent= 内容
  31. string keyword1 = 自定义内容
  32. string keyword2 = string keyword3 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //时间
  33. string remark = 备注
  34.  
  35. string contentmsg = {\"touser\":\"" + Openid + \",\"template_id\":\"" + templateId + " + firstContent + " + keyword1 + " + keyword2 + " + keyword3 + " +remark + ";
  36. string result = WeChatPushNotice(Access_token,contentmsg);
  37. return result;
  38. }
  39. 微信消息推送
  40. <param name="accessToken">微信access_token<param name="contentMsg">推送内容string WeChatPushNotice(string accessToken,1)"> contentMsg)
  41. {
  42. string promat = ""需要提交的数据
  43. byte[] bs = Encoding.UTF8.GetBytes(contentMsg);
  44. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken + );
  45. req.Method = POST;
  46. req.ContentType = application/x-www-form-urlencoded;
  47. req.ContentLength = bs.Length;
  48. using (Stream reqStream = req.GetRequestStream())
  49. {
  50. reqStream.Write(bs,0,bs.Length);
  51. }
  52. HttpWebResponse respon = (HttpWebResponse)req.GetResponse();
  53. Stream stream = respon.GetResponseStream();
  54. using (StreamReader reader = StreamReader(stream,Encoding.UTF8))
  55. {
  56. promat = reader.ReadToEnd();
  57. }
  58. ReturnMsg y = JsonConvert.DeserializeObject<ReturnMsg>(promat);
  59. promat = y.errmsg;
  60. promat;
  61. }
  62. 自定义模型
  63. </summary>
  64. ReturnMsg
  65. {
  66. string errcode { get; set; }
  67. string errmsg { string msgid { ; }
  68. }
  69. }
  70. }

 在调用模板消息接口后,会返回JSON数据包。正常时的返回JSON数据包示例:

  1. {
  2. errcode":errmsgokmsgid200228332
  3. }

 

猜你在找的微信公众号相关文章