亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android微信公眾號開發實例分析

發布時間:2022-10-19 11:49:09 來源:億速云 閱讀:157 作者:iii 欄目:編程語言

這篇文章主要介紹“android微信公眾號開發實例分析”,在日常操作中,相信很多人在android微信公眾號開發實例分析問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”android微信公眾號開發實例分析”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

開發前說明:
我們需要用到 StreamReader

所以需要引用:using System.IO;

現在正式講開發

上面講了一些微信給我們的規則

我們現在要用這些規則獲取我們想要的東西。

第一步:獲取那串 XML 這個是最重要的,因為沒這個XML,我們就相當于啥都沒有。(我們的信息來源就是這個XML)

這里我使用 StreamReader 來獲取 Request.Body

因為XML主要是 Request.Body 里面的

//聲明一個XML方便調用
string xml="";
//獲取我們的流
var reader = new StreamReader(Request.Body);
//把流里面的讀取出來,就是我們這串XML了。
var contentFromBody = reader.ReadToEnd();
//再保存進我們的這個字符串里,方便后期使用
xml = contentFromBody;

我們讀取XML中的信息,并將其轉成我們的微信信息對象。

這里呢。我借用了一位大佬的代碼:

專門處理微信消息的幾個類

第一個類:
MessageFromWeiXin:

using System.Collections.Generic;
namespace 命名空間(各位懂的)
{
    /// <summary>
    ///     來自微信的消息請求:基類
    /// </summary>
    public class MessageFromWeiXin
    {
        /// <summary>
        ///     開發者微信號:接收到消息的公眾號帳號
        /// </summary>
        public string ToUserName { get; set; }

        /// <summary>
        ///     發送方帳號(一個OpenID,引起這條消息的微信用戶)
        /// </summary>
        public string FromUserName { get; set; }

        /// <summary>
        ///     消息創建時間 (整型)
        /// </summary>
        public long CreateTime { get; set; }

        /// <summary>
        ///     消息id,64位整型
        /// </summary>
        public long MsgId { get; set; }

        /// <summary>
        ///     消息類型
        /// </summary>
        public MessageFromWeiXinType MsgType { get; set; }
    }

    #region 普通消息

    /// <summary>
    ///     來自微信的【文本】消息請求
    /// </summary>
    public class TextMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     文本消息內容
        /// </summary>
        public string Content { get; set; }
    }

    /// <summary>
    ///     來自微信的【圖片】消息請求
    /// </summary>
    public class ImageMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     圖片鏈接(由系統生成)
        /// </summary>
        public string PicUrl { get; set; }

        /// <summary>
        ///     圖片消息媒體id,可以調用多媒體文件下載接口拉取數據。
        /// </summary>
        public string MediaId { get; set; }
    }

    /// <summary>
    ///     來自微信的【語音】消息請求
    /// </summary>
    public class VoiceMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     語音消息媒體id,可以調用多媒體文件下載接口拉取該媒體
        /// </summary>
        public string MediaId { get; set; }

        /// <summary>
        ///     語音格式:amr
        /// </summary>
        public string Format { get; set; }

        /// <summary>
        ///     語音識別結果,UTF8編碼(需要開通此服務)
        /// </summary>
        public string Recognition { get; set; }
    }

    /// <summary>
    ///     來自微信的【文本】消息請求
    /// </summary>
    public class VideoMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     視頻消息媒體id,可以調用多媒體文件下載接口拉取數據。
        /// </summary>
        public string MediaId { get; set; }

        /// <summary>
        ///     視頻消息縮略圖的媒體id,可以調用
        /// </summary>
        public string ThumbMediaId { get; set; }
    }

    /// <summary>
    ///     來自微信的【小視頻】消息請求
    /// </summary>
    public class ShortVideoMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     視頻消息媒體id,可以調用多媒體文件下載接口拉取數據。
        /// </summary>
        public string MediaId { get; set; }

        /// <summary>
        ///     視頻消息縮略圖的媒體id,可以調用
        /// </summary>
        public string ThumbMediaId { get; set; }
    }

    /// <summary>
    ///     來自微信的【位置】消息請求
    /// </summary>
    public class LocationMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     地理位置維度【緯度】
        /// </summary>
        public float Location_X { get; set; }

        /// <summary>
        ///     地理位置經度
        /// </summary>
        public float Location_Y { get; set; }

        /// <summary>
        ///     地圖縮放大小
        /// </summary>
        public int Scale { get; set; }

        /// <summary>
        ///     地理位置信息
        /// </summary>
        public string Label { get; set; }
    }

    /// <summary>
    ///     來自微信的【位置】消息請求
    /// </summary>
    public class LinkMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     消息標題
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        ///     消息描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        ///     消息鏈接
        /// </summary>
        public string Url { get; set; }
    }

    #endregion

    #region 事件消息

    /// <summary>
    ///     基本的事件消息:關注,取消關注事件
    /// </summary>
    public class EventMessageFromWeiXin : MessageFromWeiXin
    {
        /// <summary>
        ///     事件類型
        /// </summary>
        public EventMessageFromWeiXinType Event { get; set; }
    }

    /// <summary>
    ///     用戶掃碼事件:已關注用戶事件類型為 SCAN,未關注的用戶類型為 subscribe
    /// </summary>
    public class SanEventMessageFromWeiXin : EventMessageFromWeiXin
    {
        /// <summary>
        ///     事件KEY值,是一個32位無符號整數,即創建二維碼時的二維碼scene_id,但這里作為字符串
        /// </summary>
        public string EventKey { get; set; }

        /// <summary>
        ///     二維碼的ticket,可用來換取二維碼圖片
        /// </summary>
        public string Ticket { get; set; }
    }

    /// <summary>
    ///     上報地理位置事件
    /// </summary>
    public class LocationEventMessageFromWeiXin : EventMessageFromWeiXin
    {
        /// <summary>
        ///     地理位置緯度
        /// </summary>
        public float Latitude { get; set; }

        /// <summary>
        ///     地理位置經度
        /// </summary>
        public float Longitude { get; set; }

        /// <summary>
        ///     地理位置精度
        /// </summary>
        public float Precision { get; set; }
    }

    /// <summary>
    ///     點擊菜單拉取消息事件
    /// </summary>
    public class ClickEventMessageFromWeiXin : EventMessageFromWeiXin
    {
        /// <summary>
        ///     事件KEY值,與自定義菜單接口中KEY值對應
        /// </summary>
        public string EventKey { get; set; }
    }

    /// <summary>
    ///     點擊菜單跳轉鏈接事件
    /// </summary>
    public class ViewEventMessageFromWeiXin : EventMessageFromWeiXin
    {
        /// <summary>
        ///     事件KEY值,設置的跳轉URL
        /// </summary>
        public string EventKey { get; set; }
    }

    /// <summary>
    ///     群發消息完成事件
    /// </summary>
    public class MassSendJobFinishMessageFromWeiXin : EventMessageFromWeiXin
    {
        /// <summary>
        ///     狀態
        /// </summary>
        public string Status { get; set; }

        /// <summary>
        ///     標簽粉絲數,或OpenId列表中粉絲數
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        ///     過濾(過濾是指特定地區、性別的過濾、用戶設置拒收的過濾,用戶接收已超4條的過濾)后,準備發送的粉絲數,原則上,FilterCount = SentCount + ErrorCount
        /// </summary>
        public int FilterCount { get; set; }

        /// <summary>
        ///     發送成功的粉絲數
        /// </summary>
        public int SentCount { get; set; }

        /// <summary>
        ///     發送失敗的粉絲數
        /// </summary>
        public int ErrorCount { get; set; }

        /// <summary>
        ///     原創校驗結果
        /// </summary>
        public CopyrightCheckResult CopyrightCheckResult { get; set; }
    }

    /// <summary>
    ///     原創校驗結果
    /// </summary>
    public class CopyrightCheckResult
    {
        /// <summary>
        ///     圖文個數
        /// </summary>
        public int Count { get; set; }

        /// <summary>
        ///     各個單圖文校驗結果
        /// </summary>
        public List<CopyrightCheckItem> ResultList { get; set; }

        /// <summary>
        ///     1-未被判為轉載,可以群發,2-被判為轉載,可以群發,3-被判為轉載,不能群發
        /// </summary>
        public int CheckState { get; set; }
    }

    /// <summary>
    ///     單圖文原創校驗結果
    /// </summary>
    public class CopyrightCheckItem
    {
        /// <summary>
        ///     群發文章的序號,從1開始
        /// </summary>
        public int ArticleIdx { get; set; }

        /// <summary>
        ///     用戶聲明文章的狀態
        /// </summary>
        public int UserDeclareState { get; set; }

        /// <summary>
        ///     系統校驗的狀態
        /// </summary>
        public int AuditState { get; set; }

        /// <summary>
        ///     相似原創文的url
        /// </summary>
        public string OriginalArticleUrl { get; set; }

        /// <summary>
        ///     相似原創文的類型
        /// </summary>
        public int OriginalArticleType { get; set; }

        /// <summary>
        ///     是否能轉載
        /// </summary>
        public int CanReprint { get; set; }

        /// <summary>
        ///     是否需要替換成原創文內容
        /// </summary>
        public int NeedReplaceContent { get; set; }

        /// <summary>
        ///     否需要注明轉載來源
        /// </summary>
        public int NeedShowReprintSource { get; set; }
    }

    /// <summary>
    ///     模版消息發送完成事件
    /// </summary>
    public class TEMPLATESENDJOBFINISHMessageFromWeiXin : EventMessageFromWeiXin
    {
        /// <summary>
        ///     狀態:success 成功;failed:user block 用戶拒絕;failed: system failed 非用戶拒絕
        /// </summary>
        public string Status { get; set; }
    }

    #endregion

    /// <summary>
    ///     微信服務器推送過來的消息類型
    /// </summary>
    public enum MessageFromWeiXinType
    {
        /// <summary>
        ///     未知
        /// </summary>
        unknown = 1,

        /// <summary>
        ///     文本消息
        /// </summary>
        text = 2,

        /// <summary>
        ///     圖片消息
        /// </summary>
        image = 3,

        /// <summary>
        ///     語音消息
        /// </summary>
        voice = 4,

        /// <summary>
        ///     視頻消息
        /// </summary>
        video = 5,

        /// <summary>
        ///     小視頻消息
        /// </summary>
        shortvideo = 6,

        /// <summary>
        ///     地里位置消息
        /// </summary>
        location = 7,

        /// <summary>
        ///     連接消息
        /// </summary>
        link = 8,

        /// <summary>
        ///     事件推送消息
        /// </summary>
        @event = 9
    }

    /// <summary>
    ///     微信服務器推送過來的【事件】消息的子類型
    /// </summary>
    public enum EventMessageFromWeiXinType
    {
        /// <summary>
        ///     未知
        /// </summary>
        unknown = 1,

        /// <summary>
        ///     訂閱事件;未關注用戶掃碼關注也是這個類型,但數據結構與SCAN類型相同,此時相當于兩個類型的合并
        /// </summary>
        subscribe = 2,

        /// <summary>
        ///     取消訂閱事件
        /// </summary>
        unsubscribe = 3,

        /// <summary>
        ///     掃描帶參數二維碼事件
        /// </summary>
        SCAN = 4,

        /// <summary>
        ///     上報地理位置事件
        /// </summary>
        LOCATION = 5,

        /// <summary>
        ///     點擊自定義菜單拉取消息事件
        /// </summary>
        CLICK = 6,

        /// <summary>
        ///     點擊自定義菜單跳轉鏈接事件
        /// </summary>
        VIEW = 7,

        /// <summary>
        ///     群發消息發送結束事件
        /// </summary>
        MASSSENDJOBFINISH = 8,

        /// <summary>
        ///     模板消息發送結束事件
        /// </summary>
        TEMPLATESENDJOBFINISH = 9
    }
}

第二個類:

ResponseClient:

using System.Xml;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;

namespace 命名空間(各位懂的)
{
    /// <summary>
    ///     XML消息識別
    /// </summary>
    public static class ResponseClient
    {
        /// <summary>
        ///     判斷消息類型
        /// </summary>
        public static MessageFromWeiXinType GetMsgType(string msg)
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(msg);

            if (TryGetFirstTagText(ref xmlDocument, "MsgType", out var txt) &&
                Enum.TryParse(txt, out MessageFromWeiXinType Type)) return Type;
            return MessageFromWeiXinType.unknown;
        }

        /// <summary>
        ///     XML轉消息對象
        /// </summary>
        public static MessageFromWeiXin XmlToMessageFromWeiXin(string xml)
        {
            xml = xml.Replace("< !", "<!").Replace("] ]","]]");
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            var txt = string.Empty;
            var @int = 0;

            if (TryGetFirstTagText(ref xmlDocument, "MsgType", out txt) &&
                Enum.TryParse(txt, out MessageFromWeiXinType messageType))
            {
                MessageFromWeiXin msg = null;
                switch (messageType)
                {
                    case MessageFromWeiXinType.text: //文本消息
                        msg = new TextMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.text,
                            Content = TryGetFirstTagText(ref xmlDocument, "Content", out txt) ? txt : ""
                        };
                        break;
                    case MessageFromWeiXinType.image: //圖片消息
                        msg = new ImageMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.image,
                            MediaId = TryGetFirstTagText(ref xmlDocument, "MediaId", out txt) ? txt : "",
                            PicUrl = TryGetFirstTagText(ref xmlDocument, "PicUrl", out txt) ? txt : ""
                        };
                        break;
                    case MessageFromWeiXinType.voice: //語音消息
                        msg = new VoiceMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.voice,
                            MediaId = TryGetFirstTagText(ref xmlDocument, "MediaId", out txt) ? txt : "",
                            Recognition = TryGetFirstTagText(ref xmlDocument, "Recognition", out txt) ? txt : "",
                            Format = TryGetFirstTagText(ref xmlDocument, "Format", out txt) ? txt : ""
                        };
                        break;
                    case MessageFromWeiXinType.video: //視頻消息
                        msg = new VideoMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.video,
                            MediaId = TryGetFirstTagText(ref xmlDocument, "MediaId", out txt) ? txt : "",
                            ThumbMediaId = TryGetFirstTagText(ref xmlDocument, "ThumbMediaId", out txt) ? txt : ""
                        };
                        break;
                    case MessageFromWeiXinType.shortvideo: //小視頻消息
                        msg = new ShortVideoMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.shortvideo,
                            MediaId = TryGetFirstTagText(ref xmlDocument, "MediaId", out txt) ? txt : "",
                            ThumbMediaId = TryGetFirstTagText(ref xmlDocument, "ThumbMediaId", out txt) ? txt : ""
                        };
                        break;
                    case MessageFromWeiXinType.link: //鏈接消息
                        msg = new LinkMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.link,
                            Description = TryGetFirstTagText(ref xmlDocument, "Description", out txt) ? txt : "",
                            Title = TryGetFirstTagText(ref xmlDocument, "Title", out txt) ? txt : "",
                            Url = TryGetFirstTagText(ref xmlDocument, "Url", out txt) ? txt : ""
                        };
                        break;
                    case MessageFromWeiXinType.location: //位置消息
                        msg = new LocationMessageFromWeiXin
                        {
                            MsgType = MessageFromWeiXinType.location,
                            Label = TryGetFirstTagText(ref xmlDocument, "Label", out txt) ? txt : "",
                            Location_X =
                                TryGetFirstTagText(ref xmlDocument, "Location_X", out txt) ? Convert.ToSingle(txt) : 0,
                            Location_Y =
                                TryGetFirstTagText(ref xmlDocument, "Location_Y", out txt) ? Convert.ToSingle(txt) : 0,
                            Scale = TryGetFirstTagText(ref xmlDocument, "Scale", out txt) ? Convert.ToInt32(txt) : 0
                        };
                        break;
                    case MessageFromWeiXinType.@event: //事件消息
                        if (TryGetFirstTagText(ref xmlDocument, "Event", out txt))
                        {
                            var Event = Enum.TryParse(txt, out EventMessageFromWeiXinType eventMessageFromWeiXinType)
                                ? eventMessageFromWeiXinType
                                : EventMessageFromWeiXinType.unknown;
                            switch (Event)
                            {
                                case EventMessageFromWeiXinType.subscribe: //關注事件
                                    msg = new EventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.subscribe
                                    };
                                    break;
                                case EventMessageFromWeiXinType.unsubscribe: //取消關注事件
                                    msg = new EventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.unsubscribe
                                    };
                                    break;
                                case EventMessageFromWeiXinType.SCAN: //掃碼
                                    msg = new SanEventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.SCAN,
                                        EventKey = TryGetFirstTagText(ref xmlDocument, "EventKey", out txt) ? txt : "",
                                        Ticket = TryGetFirstTagText(ref xmlDocument, "Ticket", out txt) ? txt : ""
                                    };
                                    break;
                                case EventMessageFromWeiXinType.CLICK: //點擊自定義菜單等待消息響應
                                    msg = new ClickEventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.CLICK,
                                        EventKey = TryGetFirstTagText(ref xmlDocument, "EventKey", out txt) ? txt : ""
                                    };
                                    break;
                                case EventMessageFromWeiXinType.VIEW: //點擊自定義菜單跳轉到頁面
                                    msg = new ViewEventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.VIEW,
                                        EventKey = TryGetFirstTagText(ref xmlDocument, "EventKey", out txt) ? txt : ""
                                    };
                                    break;
                                case EventMessageFromWeiXinType.LOCATION: //授權取得位置事件
                                    msg = new LocationEventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.LOCATION,
                                        Latitude = TryGetFirstTagText(ref xmlDocument, "Latitude", out txt)
                                            ? Convert.ToSingle(txt)
                                            : 0,
                                        Longitude = TryGetFirstTagText(ref xmlDocument, "Longitude", out txt)
                                            ? Convert.ToSingle(txt)
                                            : 0,
                                        Precision = TryGetFirstTagText(ref xmlDocument, "Precision", out txt)
                                            ? Convert.ToSingle(txt)
                                            : 0
                                    };
                                    break;
                                case EventMessageFromWeiXinType.MASSSENDJOBFINISH: //群發消息發送完成事件
                                    var items = xmlDocument.GetElementsByTagName("item");
                                    var itemsList = new List<CopyrightCheckItem>();
                                    foreach (XmlNode i in items)
                                    {
                                        var item = new CopyrightCheckItem();
                                        foreach (XmlNode j in i.ChildNodes)
                                            switch (j.Name)
                                            {
                                                case "ArticleIdx":
                                                    item.ArticleIdx = int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                                case "UserDeclareState":
                                                    item.UserDeclareState =
                                                        int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                                case "AuditState":
                                                    item.AuditState = int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                                case "OriginalArticleUrl":
                                                    item.OriginalArticleUrl = j.InnerText;
                                                    break;
                                                case "OriginalArticleType":
                                                    item.OriginalArticleType =
                                                        int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                                case "CanReprint":
                                                    item.CanReprint = int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                                case "NeedReplaceContent":
                                                    item.NeedReplaceContent =
                                                        int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                                case "NeedShowReprintSource":
                                                    item.NeedShowReprintSource =
                                                        int.TryParse(j.InnerText, out @int) ? @int : 0;
                                                    break;
                                            }
                                    }

                                    msg = new MassSendJobFinishMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.MASSSENDJOBFINISH,
                                        Status = TryGetFirstTagText(ref xmlDocument, "Status", out txt) ? txt : "",
                                        TotalCount =
                                            TryGetFirstTagText(ref xmlDocument, "TotalCount", out txt)
                                                ? Convert.ToInt32(txt)
                                                : 0,
                                        FilterCount =
                                            TryGetFirstTagText(ref xmlDocument, "FilterCount", out txt)
                                                ? Convert.ToInt32(txt)
                                                : 0,
                                        SentCount = TryGetFirstTagText(ref xmlDocument, "SentCount", out txt)
                                            ? Convert.ToInt32(txt)
                                            : 0,
                                        ErrorCount =
                                            TryGetFirstTagText(ref xmlDocument, "ErrorCount", out txt)
                                                ? Convert.ToInt32(txt)
                                                : 0,
                                        CopyrightCheckResult = new CopyrightCheckResult
                                        {
                                            Count = TryGetFirstTagText(ref xmlDocument, "Count", out txt)
                                                ? Convert.ToInt32(txt)
                                                : 0,
                                            CheckState =
                                                TryGetFirstTagText(ref xmlDocument, "CheckState", out txt)
                                                    ? Convert.ToInt32(txt)
                                                    : 0,
                                            ResultList = itemsList
                                        }
                                    };
                                    break;
                                case EventMessageFromWeiXinType.TEMPLATESENDJOBFINISH: //模版消息發送完成事件
                                    msg = new TEMPLATESENDJOBFINISHMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.TEMPLATESENDJOBFINISH,
                                        Status = TryGetFirstTagText(ref xmlDocument, "", out txt) ? txt : ""
                                    };
                                    break;
                                default: //其他事件
                                    msg = new EventMessageFromWeiXin
                                    {
                                        MsgType = MessageFromWeiXinType.@event,
                                        Event = EventMessageFromWeiXinType.unknown
                                    };
                                    break;
                            }
                        }

                        break;
                    default: //未知消息
                        msg = new MessageFromWeiXin {MsgType = MessageFromWeiXinType.unknown};
                        break;
                }

                if (msg.MsgType != MessageFromWeiXinType.unknown)
                {
                    if (TryGetFirstTagText(ref xmlDocument, "CreateTime", out txt))
                        msg.CreateTime = Convert.ToInt32(txt);
                    if (TryGetFirstTagText(ref xmlDocument, "FromUserName", out txt)) msg.FromUserName = txt;
                    if (TryGetFirstTagText(ref xmlDocument, "MsgId", out txt)) msg.MsgId = Convert.ToInt64(txt);
                    if (TryGetFirstTagText(ref xmlDocument, "ToUserName", out txt)) msg.ToUserName = txt;
                    return msg;
                }
            }

            return null;
        }

        /// <summary>
        ///     嘗試取得XML中第一個指定標簽的文本
        /// </summary>
        /// <param name="xml">xml文檔對象</param>
        /// <param name="tag">指定的標簽名</param>
        /// <param name="txt">取得的文本</param>
        /// <returns>是否成功取得</returns>
        public static bool TryGetFirstTagText(ref XmlDocument xml, string tag, out string txt)
        {
            txt = string.Empty;
            var Node = xml.GetElementsByTagName(tag);
            if (Node.Count > 0)
            {
                txt = Node[0].InnerText;
                if (!string.IsNullOrWhiteSpace(txt)) return true;
            }

            return false;
        }

        /// <summary>
        ///     驗證微信接口
        /// </summary>
        /// <param name="echostr"></param>
        /// <param name="nonce"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool VerificationSignature(string echostr, string nonce, string signature, string timestamp,
            string token)
        {
            string[] StrArray = {token, timestamp, nonce};
            Array.Sort(StrArray);
            var ArrayString = new StringBuilder();
            for (var i = 0; i < StrArray.Length; i++) ArrayString.Append(StrArray[i]);
            var strHash = GetSha1Hash(ArrayString.ToString());
            return signature == strHash;
        }

        /// <summary>
        ///     哈希1
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetSha1Hash(string input)
        {
            var inputBytes = Encoding.Default.GetBytes(input);

            SHA1 sha = new SHA1CryptoServiceProvider();

            var result = sha.ComputeHash(inputBytes);

            var sBuilder = new StringBuilder();

            for (var i = 0; i < result.Length; i++) sBuilder.Append(result[i].ToString("x2"));

            return sBuilder.ToString();
        }

        /// <summary>
        ///     時間轉時間戳
        /// </summary>
        public static long ConvertDateTimeToInt(DateTime dateTime)
        {
            var startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var t = (dateTime.Ticks - startTime.Ticks) / 10000; //除10000調整為13位      
            return t;
        }
    }
}

有了這兩個類,我們的東西就好開展了,如果大家有發現報錯的話,是因為string擴展類的問題。需要的留下郵箱,這個東西太長了。不好發,不過大家應該都看的懂,自己寫一套也好。

使用上面第二個類中的,這個方法,進行轉換 : XmlToMessageFromWeiXin

得到我們 msg 對象

我們這個對象里面有msgtype,這個type枚舉呢,就對應了各個事件。

我們寫個switch就能將他們分開了。不同事件進入不同分支處理。

/// <summary>
///     接收來自微信的消息
/// </summary>
[HttpPost]
[Route("api/WeChat")]
public string Post(string xml)
{
    System.Console.WriteLine("進入消息處理");
    var reader = new StreamReader(Request.Body);
    var contentFromBody = reader.ReadToEnd();
    System.Console.WriteLine($"xml:{contentFromBody}");
    xml = contentFromBody;

    try
    {
        var msg = ResponseClient.XmlToMessageFromWeiXin(xml);
        var Response = "";
        switch (msg.MsgType)
        {
            case MessageFromWeiXinType.text:
                var textMsg = (TextMessageFromWeiXin)msg;
                Response = "<xml> <ToUserName><![CDATA[" + textMsg.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + textMsg.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您說“" +
                               textMsg.Content + "”,小女子暫時還不明白,等小女子日后博學之時再來答復您。]]></Content> </xml>";
                break;
            case MessageFromWeiXinType.image:
                var imgMsg = (ImageMessageFromWeiXin)msg;
                System.Console.WriteLine($"圖片地址:{imgMsg.PicUrl}");
                Response = "<xml> <ToUserName><![CDATA[" + imgMsg.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + imgMsg.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您發了一張 圖片,小女子已經幫您保存起來了]]></Content> </xml>";
                break;
            case MessageFromWeiXinType.voice:
                var voiceMsg = (VoiceMessageFromWeiXin)msg;
                //如果有開通語音識別的功能,我們可以使用這個字段:Recognition
                System.Console.WriteLine($"音頻轉文字:{voiceMsg.Recognition}");
                //我們下載這串語音的話就要使用這個字段:MediaId,根據這個字段加上微信提供的多媒體下載接口 ,下載 我們的音頻文件。記得及時下載喲
                System.Console.WriteLine($"音頻下載地址:{voiceMsg.MediaId}");
                Response = "<xml> <ToUserName><![CDATA[" + voiceMsg.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + voiceMsg.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您發了一串 語音,小女子已經幫您保存起來了]]></Content> </xml>";
                break;
            case MessageFromWeiXinType.shortvideo:
                var shortvideo = (ShortVideoMessageFromWeiXin)msg;
                //我們下載這串語音的話就要使用這個字段:MediaId,根據這個字段加上微信提供的多媒體下載接口 ,下載 我們的視頻文件。記得及時下載喲
                System.Console.WriteLine($"小視頻下載地址:{shortvideo.MediaId}");
                Response = "<xml> <ToUserName><![CDATA[" + shortvideo.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + shortvideo.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您發了一個小視頻,小女子已經幫您保存起來了]]></Content> </xml>";
                break;
            case MessageFromWeiXinType.video:
                var video = (VideoMessageFromWeiXin)msg;
                //我們下載這串語音的話就要使用這個字段:MediaId,根據這個字段加上微信提供的多媒體下載接口 ,下載 我們的視頻文件。記得及時下載喲
                System.Console.WriteLine($"視頻下載地址:{video.MediaId}");
                Response = "<xml> <ToUserName><![CDATA[" + video.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + video.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您發了一個視頻,小女子已經幫您保存起來了]]></Content> </xml>";
                break;
            case MessageFromWeiXinType.location:
                var location = (LocationMessageFromWeiXin)msg;
                //我們的地址呢,主要有 地理位置緯度 Location_X ; 地理位置經度  Location_Y ; 地圖縮放大小 Scale; 地理位置信息 Label 
                System.Console.WriteLine($"緯度:{location.Location_X}\n經度:{location.Location_Y}\n地圖縮放大小:{location.Scale}\n地理位置信息:{location.Label}\n");
                Response = "<xml> <ToUserName><![CDATA[" + location.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + location.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您發了一個 位置信息,小女子已經幫您記錄下來了]]></Content> </xml>";
                break;
            case MessageFromWeiXinType.link:
                var link = (LinkMessageFromWeiXin)msg;
                //我們的鏈接呢,主要有 消息標題 Title  ;消息描述 Description ;消息鏈接 Url
                System.Console.WriteLine($"消息標題:{link.Title}\n消息描述:{link.Description}\n消息鏈接:{link.Url}\n");
                Response = "<xml> <ToUserName><![CDATA[" + link.FromUserName +
                               "]]></ToUserName> <FromUserName><![CDATA[" + link.ToUserName +
                               "]]></FromUserName> <CreateTime>" +
                               ResponseClient.ConvertDateTimeToInt(DateTime.Now) +
                               "</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[您發了一個 鏈接:標題:" + link.Title + " , 地址: " + link.Url + " ,小女子已經幫您記錄下來了]]></Content> </xml>";
                break;
        }
        return Response;
        // return "success";
    }
    catch (Exception ex)
    {
        return "error";
    }
}

到此,關于“android微信公眾號開發實例分析”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

旬邑县| 全州县| 周宁县| 金坛市| 武功县| 华坪县| 石门县| 页游| 库车县| 贺州市| 达拉特旗| 崇左市| 家居| 治县。| 和平县| 航空| 高平市| 邹平县| 明溪县| 武冈市| 监利县| 南安市| 南岸区| 社旗县| 富锦市| 榆树市| 平谷区| 黑水县| 城口县| 宿迁市| 凉山| 碌曲县| 延长县| 垦利县| 定远县| 阜新市| 凉城县| 黄龙县| 鄂伦春自治旗| 应用必备| 涡阳县|