C#微信公众号开发之微信菜单相关操作及发送模板消息、群发消息(三)

目录

一、微信菜单的创建

   1、需要注意的地方

2、自定义菜单接口可实现多种类型按钮,如下:

 3、创建菜单

4.创建菜单的代码


 

一、微信菜单的创建

   1、需要注意的地方

1、自定义菜单最多包括3个一级菜单,每个一级菜单最多包含5个二级菜单。
2、一级菜单最多4个汉字,二级菜单最多7个汉字,多出来的部分将会以“...”代替。
3、创建自定义菜单后,菜单的刷新策略是,在用户进入公众号会话页或公众号profile页时,如果发现上一次拉取菜单的请求在5分钟以前,就会拉取一下菜单,如果菜单有更新,就会刷新客户端的菜单。测试时可以尝试取消关注公众账号后再次关注,则可以看到创建后的效果。

2、自定义菜单接口可实现多种类型按钮,如下:

1、click:点击推事件用户点击click类型按钮后,微信服务器会通过消息接口推送消息类型为event的结构给开发者(参考消息接口指南),并且带上按钮中开发者填写的key值,开发者可以通过自定义的key值与用户进行交互;
2、view:跳转URL用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的网页URL,可与网页授权获取用户基本信息接口结合,获得用户基本信息。
3、scancode_push:扫码推事件用户点击按钮后,微信客户端将调起扫一扫工具,完成扫码操作后显示扫描结果(如果是URL,将进入URL),且会将扫码的结果传给开发者,开发者可以下发消息。
4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框用户点击按钮后,微信客户端将调起扫一扫工具,完成扫码操作后,将扫码的结果传给开发者,同时收起扫一扫工具,然后弹出“消息接收中”提示框,随后可能会收到开发者下发的消息。
5、pic_sysphoto:弹出系统拍照发图用户点击按钮后,微信客户端将调起系统相机,完成拍照操作后,会将拍摄的相片发送给开发者,并推送事件给开发者,同时收起系统相机,随后可能会收到开发者下发的消息。
6、pic_photo_or_album:弹出拍照或者相册发图用户点击按钮后,微信客户端将弹出选择器供用户选择“拍照”或者“从手机相册选择”。用户选择后即走其他两种流程。
7、pic_weixin:弹出微信相册发图器用户点击按钮后,微信客户端将调起微信相册,完成选择操作后,将选择的相片发送给开发者的服务器,并推送事件给开发者,同时收起相册,随后可能会收到开发者下发的消息。
8、location_select:弹出地理位置选择器用户点击按钮后,微信客户端将调起地理位置选择工具,完成选择操作后,将选择的地理位置发送给开发者的服务器,同时收起位置选择工具,随后可能会收到开发者下发的消息。
9、media_id:下发消息(除文本消息)用户点击media_id类型按钮后,微信服务器会将开发者填写的永久素材id对应的素材下发给用户,永久素材类型可以是图片、音频、视频、图文消息。请注意:永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id。
10、view_limited:跳转图文消息URL用户点击view_limited类型按钮后,微信客户端将打开开发者在按钮中填写的永久素材id对应的图文消息URL,永久素材类型只支持图文消息。请注意:永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id。

 3、创建菜单

1.http请求方式:POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN  

2.post传送一下菜单的json数据----click和view的请求示例

{
     "button":[
     {    
          "type":"click",
          "name":"今日歌曲",
          "key":"V1001_TODAY_MUSIC"
      },
      {
           "name":"菜单",
           "sub_button":[
           {    
               "type":"view",
               "name":"搜索",
               "url":"http://www.soso.com/"
            },
            {
                 "type":"miniprogram",
                 "name":"wxa",
                 "url":"http://mp.weixin.qq.com",
                 "appid":"wx286b93c14bbf93aa",
                 "pagepath":"pages/lunar/index"
             },
            {
               "type":"click",
               "name":"赞一下我们",
               "key":"V1001_GOOD"
            }]
       }]
 }

这里就举一个例子,具体的可以参考官方文档https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013

4.创建菜单的代码

  这里我就简单的写了一个apsx,直接访问网站完成创建,如果想用界面操作的可以自己写一下,因为这里我就是简单的测试一下微信开发的功能,并没有以项目为目标,好了下面就贴了相关的代码,包含了很多测试:创建菜单、发送模板消息、群发文本消息(注:测试号不支持群发图文消息)、分标签发送消息及模板消息。关于代码优化就交给你们了,目前测试工作完成。

using CrystalDecisions.Shared.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class web_WeiXin_Menu : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //读取txt创建菜单

        //FileStream fs1 = new FileStream(Server.MapPath(".") + "\\menu.txt", FileMode.Open);
        //StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK"));
        //string menu = sr.ReadToEnd();
        //sr.Close();
        //fs1.Close();
      String json = "{\"button\":[{\"name\": \"扫码\","+
            "\"sub_button\": [{"+
                    "\"type\": \"scancode_waitmsg\","+
                   "\"name\": \"扫码消息\","+
                    "\"key\": \"rselfmenu_0_0\","+
                    "\"sub_button\": [ ]},{"+
                    "\"type\": \"scancode_push\","+
                    "\"name\": \"扫码结果\", "+
                    "\"key\": \"rselfmenu_0_1\","+
                    "\"sub_button\": [ ]},{"+
                    "\"type\": \"pic_sysphoto\","+
                    "\"name\": \"拍照发图\","+
                    "\"key\": \"rselfmenu_1_0\","+
                   "\"sub_button\": [ ]},{"+
                    "\"type\": \"pic_photo_or_album\","+ 
                    "\"name\": \"发图\","+
                    "\"key\": \"rselfmenu_1_1\","+
                    "\"sub_button\": [ ]}]},"
      +"{\"type\":\"click\",\"name\":\"四六级查询\",\"key\":\"V1001_TODAY_SINGER\"},{\"name\":\"菜单\",\"sub_button\":[{"	
      +"\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"},{\"type\":\"view\",\"name\":\"视频\","
      + "\"url\":\"http://v.qq.com/\"},{\"type\":\"click\",\"name\":\"赞一下我们\",\"key\":\"V1001_GOOD\"}]}]}";
      PostMessage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" +CommonApi.GetAccessToken("wxadf0f", "35e3c8aeaa8c12d2bc76c1c12570bc96")+ "", json);
      TemplateMessage mess = new TemplateMessage();
      var data = new
      {
          first=new {
          value="车铣",
           color="#173177"
          },
          remark=new {
          value="组装",
           color="#173177"
          }
      };
        //获取用户openid
     CommonApi api = new CommonApi();
    // string result=api.GetResult("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + CommonApi.GetAccessToken("wxadf0f0a", "35e3c8aeaa8c12d2bc76c1c12570bc96") + "&next_openid=");
    //string openid= api.getValue(result,"微信的nickname");
   // mess.SendTemplate(openid, "xuWr3wDclf-Sl60qxlTvhDIBalCdpFZJQ9wNfJ3NX0g", data);

        //上传素材图片
   //   string r= uploadMaterial();
   //   string thumb_media_id = CommonApi.GetJsonValue(r, "thumb_media_id");
   //    //上传图文素材
   //   string articles = "{\"articles\": [{" +
   //                   "\"thumb_media_id\":\""+thumb_media_id+"\"," +
   //                  "\"author\":\"zy\"," +
   //                   "\"title\":\"Happy Day\"," +
   //                   "\"content_source_url\":\"www.qq.com\"," +
   //                   "\"content\":\"震惊!程序名竟然这么做。。。\"," +
   //                   "\"digest\":\"digest\"," +
   //                   "\"show_cover_pic\":1," +
   //                   "\"need_open_comment\":1," +
   //                   "\"only_fans_can_comment\":1}," +
   //                   "{\"thumb_media_id\":\""+thumb_media_id+"\"," +
   //                   "\"author\":\"zy\"," +
   //                   "\"title\":\"Happy Day\"," +
   //                   "\"content_source_url\":\"www.qq.com\"," +
   //                   "\"content\":\"这篇文章是世界上最完美的一篇文章<p><a data-miniprogram-appid=\"wx123123123\" data-miniprogram-path=\"pages/index\" href=\"\">点击文字跳转小程序</a></p>\"," +
   //                   "\"digest\":\"digest\"," +
   //                   "\"show_cover_pic\":0," +
   //                  "\"need_open_comment\":1," +
   //                   "\"only_fans_can_comment\":1}]}";
   //string artres=PostMessage("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="+CommonApi.GetAccessToken("wxadf0f0c801b521fa", "35e3c8aeaa8c12d2bc76c1c12570bc96"),articles);
   //string media_id = CommonApi.GetJsonValue(artres, "media_id");
        //群发图文,测试号没有该权限。
   //string qunfaArticles= "{\"filter\":{\"is_to_all\":true,\"tag_id\":\"\"},"+
   //"\"mpnews\":{"+
   //  "\"media_id\":\""+ media_id + "\"}," +
   // "\"msgtype\":\"mpnews\","+
   // "\"send_ignore_reprint\":0}";

        //设置用户标签
     //   string tag="{\"tag\":{\"name\":\"最帅的人\"}}";
     // string tagid=PostMessage("https://api.weixin.qq.com/cgi-bin/tags/create?access_token=" + CommonApi.GetAccessToken("wxadf0f1fa", "35e3c8aeaa8c12d2bc76c1c12570bc96"), tag);
     //string id=CommonApi.GetJsonValue(tagid, "id");
        //批量给用户打标签
 //    string addTag = "{" +
 //"\"openid_list\" : [" +
 //"\"" + openid + "\"]," +
 //"\"tagid\":"+id+"}";
 //    PostMessage("https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=" + CommonApi.GetAccessToken("wxadf1b521fa", "35e3c8aeaa8c12d2bc76c1c12570bc96"), addTag);
        string  qunfaText = "{\"filter\":{\"is_to_all\":false,\"tag_id\":\""+1001+"\"}," +
"\"text\":{"+
      "\"content\":\"震惊!最帅的人才能收到这条消息哦。。。\"}," +
    "\"msgtype\":\"text\""+
"\"send_ignore_reprint\":0}";
// PostMessage("https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + CommonApi.GetAccessToken("wxadf21fa", "35e3c8aeaa8c12d2bc76c1c12570bc96"), qunfaText);
        //删除群发
//        1、只有已经发送成功的消息才能删除
//2、删除消息是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片。
//3、删除群发消息只能删除图文消息和视频消息,其他类型的消息一经发送,无法删除。
//4、如果多次群发发送的是一个图文消息,那么删除其中一次群发,就会删除掉这个图文消息也,导致所有群发都失效
//   post数据 {
//   "msg_id":30124,
//   "article_idx":2
//}
 //PostMessage("https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=" + CommonApi.GetAccessToken("wxadf521fa", "35e3c8aeaa8c12d2bc76c1c12570bc96"),"");
    }
    public string PostMessage(string posturl, string postData)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            // 设置参数
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            string err = string.Empty;
            Response.Write(content);
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }
    //上传图片素材
    /// <summary>
    /// {"type":"image","media_id":"5fp-YfxKA0FvLHsfK0wVxUOfeEE118avD2XOgj3vSPXRuBdBEFxLS-BY1eQ_1SCw","created_at":1560820683}
    /// </summary>
    /// <returns></returns>
    public static string  uploadMaterial(){
    string imgpath = HttpContext.Current.Server.MapPath("Images\\Closed.png");
    //上传临时素材,返回media_id,type:媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
    string url2 = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + CommonApi.GetAccessToken("wxadf1fa", "35e3c8aeaa8c12d2bc76c1c12570bc96") + "&type=thumb";
        //上传永久图片素材,返回图片url,用于发送文章是的图片地址
   // string url2 = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" + CommonApi.GetAccessToken("w521fa", "35e3c8aeaa8c12d2bc76c1c12570bc96");
           
      //图片转为流
            System.Drawing.Image img = new Bitmap(imgpath);
            MemoryStream stream = new MemoryStream();
            img.Save(stream, ImageFormat.Png);
            BinaryReader br = new BinaryReader(stream);
            byte[] data = stream.ToArray();
            stream.Close();



            var boundary = "fbce142e-4e8e-4bf3-826d-cc3cf506cccc";
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("User-Agent", "KnowledgeCenter");
            client.DefaultRequestHeaders.Remove("Expect");
            client.DefaultRequestHeaders.Remove("Connection");
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.DefaultRequestHeaders.ConnectionClose = true;
            var content = new MultipartFormDataContent(boundary);
            content.Headers.Remove("Content-Type");
            content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
            var contentByte = new ByteArrayContent(data);
            content.Add(contentByte);
            contentByte.Headers.Remove("Content-Disposition");
            contentByte.Headers.TryAddWithoutValidation("Content-Disposition","form-data; name=\"media\";filename=\"{userid}_2.png\"" + "");
            contentByte.Headers.Remove("Content-Type");
            contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png");
            try
            {
                var result2 = client.PostAsync(url2, content);
                if (result2.Result.StatusCode != HttpStatusCode.OK)
                    throw new Exception(result2.Result.Content.ReadAsStringAsync().Result);
                string jsonstr = result2.Result.Content.ReadAsStringAsync().Result;
                
                return jsonstr;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.InnerException.Message);
            } 

        }
    protected void Unnamed_Click(object sender, EventArgs e)
    {
    }
}

这里再简单提一点,如果想实现机器人聊天的可以注册一下图灵机器人,绑定自己的公众号,或者调用提供的消息接口实现自动聊天功能,个人认证后可以有100次/天的消息回复哦。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值