WeiXinSDK微信公开帐号接口

联合创作 · 2023-09-28 17:59

WeiXinSDK 是微信公开帐号接口。

比如给一个物流公司的公众账号发个运单号,

对方自动回复你这个运单号的物流详细,感觉挺酷!为了说明方便,先给出申请好的公众账号信息:

下图为表示上面查看物流详细的消息流程(虚线的编号表示流程的顺序):

 

微信会向你的URL发送两大类消息:

一是用户的一般消息,如上面用户发的运单号;

二是用户的行为(即文档中说的事件)  ,如用户关注了你的公众账号、扫描了公众账号的二维码、点击了你自定义的菜单等。

 你的URL就可以根据收到的消息类型和内容做出回应以实现强大的业务服务,如上面返回的物流详细。消息全部是以XML格式传递,而SDK做的就是把XML转换成.NET对象,以方便你编写业务逻辑。消息的框架类图表示为(点击查看包括子类的全图):

 首先有个消息基类,然后是收到的消息(RecEventBaseMsg)和回复的消息(ReplyBaseMsg),上面说了,收到的消息分两大类,即一般消息(RecBaseMsg)和事件消息(EventBaseMsg),收到的消息类型用枚举表示可以是:

其他的类型不说,而当MsgType为Event时,消息便是EventBaseMsg的子类了,所有EventBaseMsg的子类的MsgType都是Event,所以EventBaseMsg类型又有个EventType来区分不同的事件,如果你看过接口文档,你应该知道,它的事件类型对我们判断到底是哪个事件不太友好,扫描二维码事件分了用户已关注和未关注两种情况,已关注时EvenType是scan,未关注时EventType是subscribe,而用户关注事件的EventType也是subscribe,所以SDK里又加了个MyEventType:


 

相关代码:

 

public class WeiXinUrl : IHttpHandler
{
    static string token = "token";
    static string AppId = "AppId";
    static string AppSecret = "AppSecret";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        var signature = context.Request["signature"] ?? string.Empty;
        var timestamp = context.Request["timestamp"] ?? string.Empty;
        var nonce = context.Request["nonce"] ?? string.Empty;
        //var echostr = context.Request.QueryString["echostr"] ?? string.Empty;
        if (WeiXin.CheckSignature(signature, timestamp, nonce, token))
        {
            //context.Response.Write(echostr);
            var replyMsg = WeiXin.ReplyMsg().GetXML();
            context.Response.Write(replyMsg);
        }
        else
        {
            context.Response.Write("fuck you");
        }

    }

    static WeiXinUrl()
    {
        WeiXin.ConfigGlobalCredential(AppId, AppSecret);
        WeiXin.RegisterMsgHandler<RecTextMsg>(msg =>
        {
            return new ReplyTextMsg { Content = "你说:" + msg.Content };
        });

        WeiXin.RegisterEventHandler<EventAttendMsg>(msg =>
        {
            return new ReplyTextMsg { Content = "谢谢关注!" };
        });
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
浏览 11
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报