微信物聯(lián)網(wǎng)開發(fā)原理圖:
一骇笔、微信公眾號與用戶端的交互
1.你需要的東西
- 申請到一個微信公眾號彻消,申請地址點這里竿拆,其中,訂閱號的申請門檻較低宾尚,不需要實名認(rèn)證丙笋,開放給開發(fā)者的接口權(quán)限也基本夠用。
**我自己的公眾號**
- 自定義HTTP服務(wù)器
1.本地服務(wù)器 需要申請公網(wǎng)IP和開通80端口煌贴,維護(hù)方便御板,但易受外界影響
2.云服務(wù)器 由互聯(lián)網(wǎng)公司提供,學(xué)生優(yōu)惠性價比高
3.Web服務(wù)器 例如百度的BAE和新浪的SAE崔步,使用方便稳吮,本地需要安裝Git或SVN - 開發(fā)的技術(shù)儲備
理論上來說,凡是能開發(fā)網(wǎng)站的語言都可以使用井濒,如PHP灶似、ASP、JSP(Java Serve Page)瑞你、ASP.NET酪惭、Node.JS、Python者甲、Java等春感。由于PHP在服務(wù)器端開發(fā)十分普遍,微信官網(wǎng)提供的示例程序也是用PHP作為開發(fā)語言來介紹,因此鲫懒,我選擇PHP寫代碼嫩实。
由于微信公眾平臺開發(fā)類似于網(wǎng)站開發(fā),因此窥岩,將會使用到網(wǎng)站開發(fā)的相關(guān)技術(shù)知識甲献,如HTTP協(xié)議、HTML颂翼、XML晃洒、JSON、數(shù)據(jù)庫等朦乏。
關(guān)于代碼編輯器球及,有Sublime Text,Eclipse等呻疹。我使用的是Hbuilder吃引。
2.自定義服務(wù)器上的部署
3.開發(fā)接口驗證
微信公眾平臺技術(shù)文檔
一個不錯的PHP在線執(zhí)行工具
<?php
define("TOKEN","weixin"); // 定義token
$wechatObj = new wechat_php(); // 生成類實例
$wechatObj->valid(); // 調(diào)用類的檢驗方法
// 定義一個操作微信公眾帳號的類
class wechat_php
{
// 定義公用校驗方法
public function valid()
{
$echoStr = $_GET["echostr"]; // 獲取GET請求的參數(shù)echostr
// 校驗signature
if($this->checkSignature ()) { // 調(diào)用校驗方法
echo $echoStr;
exit;
}
}
// 校驗方法
private function checkSignature ()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce); // 將三個參數(shù)保存到數(shù)組中
sort($tmpArr); // 對數(shù)組中三個數(shù)據(jù)進(jìn)行排序
$tmpStr = implode( $tmpArr ); // 將數(shù)組中三個數(shù)據(jù)組成一個字符串
$tmpStr = sha1( $tmpStr ); // 對字符串進(jìn)行SHA-1散列運算
if( $tmpStr == $signature ) { // 計算結(jié)果與$signature相等
return true; // 通過驗證
} else {
return false; // 未通過驗證
}
}
}
?>
4.開始編寫代碼進(jìn)行開發(fā)
例1:文本消息自動被動回復(fù)
<?php
$wechatObj = new wechat_php();
$wechatObj->GetTextMsg();
class wechat_php
{
public function GetTextMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr))
{
$postStr = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUesrname = $postStr->FromUserName;
$toUsername = $postStr->ToUserName;
$msgType = $postStr->MsgType;
$keyword = trim($postStr->Content);
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if (strtolower($msgType) != "text")
{
$msgType = "text";
$contentStr = "我只接收文本信息!";
}else{
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "消息內(nèi)容:" . $keyword . "\n";
$contentStr = $contentStr . "ToUserName:" . $toUsername . "\n";
$contentStr = $contentStr . "FromUserName:" . $fromUesrname;
}else{
$contentStr = "請輸入關(guān)鍵字...";
}
}
$resultStr = sprintf($textTpl, $fromUesrname, $toUsername, $time, $msgType, $contentStr);
ob_clean();
echo $resultStr;
}else{
echo "";
exit;
}
}
}
?>