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