WeiXinSDK微信公開帳號接口
WeiXinSDK 是微信公開帳號接口。
比如給一個(gè)物流公司的公眾賬號發(fā)個(gè)運(yùn)單號,
對方自動回復(fù)你這個(gè)運(yùn)單號的物流詳細(xì),感覺挺酷!為了說明方便,先給出申請好的公眾賬號信息:
下圖為表示上面查看物流詳細(xì)的消息流程(虛線的編號表示流程的順序):
微信會向你的URL發(fā)送兩大類消息:
一是用戶的一般消息,如上面用戶發(fā)的運(yùn)單號;
二是用戶的行為(即文檔中說的事件) ,如用戶關(guān)注了你的公眾賬號、掃描了公眾賬號的二維碼、點(diǎn)擊了你自定義的菜單等。
你的URL就可以根據(jù)收到的消息類型和內(nèi)容做出回應(yīng)以實(shí)現(xiàn)強(qiáng)大的業(yè)務(wù)服務(wù),如上面返回的物流詳細(xì)。消息全部是以XML格式傳遞,而SDK做的就是把XML轉(zhuǎn)換成.NET對象,以方便你編寫業(yè)務(wù)邏輯。消息的框架類圖表示為(點(diǎn)擊查看包括子類的全圖):
首先有個(gè)消息基類,然后是收到的消息(RecEventBaseMsg)和回復(fù)的消息(ReplyBaseMsg),上面說了,收到的消息分兩大類,即一般消息(RecBaseMsg)和事件消息(EventBaseMsg),收到的消息類型用枚舉表示可以是:
其他的類型不說,而當(dāng)MsgType為Event時(shí),消息便是EventBaseMsg的子類了,所有EventBaseMsg的子類的MsgType都是Event,所以EventBaseMsg類型又有個(gè)EventType來區(qū)分不同的事件,如果你看過接口文檔,你應(yīng)該知道,它的事件類型對我們判斷到底是哪個(gè)事件不太友好,掃描二維碼事件分了用戶已關(guān)注和未關(guān)注兩種情況,已關(guān)注時(shí)EvenType是scan,未關(guān)注時(shí)EventType是subscribe,而用戶關(guān)注事件的EventType也是subscribe,所以SDK里又加了個(gè)MyEventType:
相關(guān)代碼:
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 = "謝謝關(guān)注!" };
});
}
public bool IsReusable
{
get
{
return false;
}
}
}