微信物聯網開發原理圖:
一、微信公眾號與用戶端的交互
1.你需要的東西
- 申請到一個微信公眾號,申請地址點這里,其中,訂閱號的申請門檻較低,不需要實名認證,開放給開發者的接口權限也基本夠用。
**我自己的公眾號**
- 自定義HTTP服務器
1.本地服務器 需要申請公網IP和開通80端口,維護方便,但易受外界影響
2.云服務器 由互聯網公司提供,學生優惠性價比高
3.Web服務器 例如百度的BAE和新浪的SAE,使用方便,本地需要安裝Git或SVN - 開發的技術儲備
理論上來說,凡是能開發網站的語言都可以使用,如PHP、ASP、JSP(Java Serve Page)、ASP.NET、Node.JS、Python、Java等。由于PHP在服務器端開發十分普遍,微信官網提供的示例程序也是用PHP作為開發語言來介紹,因此,我選擇PHP寫代碼。
由于微信公眾平臺開發類似于網站開發,因此,將會使用到網站開發的相關技術知識,如HTTP協議、HTML、XML、JSON、數據庫等。
關于代碼編輯器,有Sublime Text,Eclipse等。我使用的是Hbuilder。
2.自定義服務器上的部署
3.開發接口驗證
微信公眾平臺技術文檔
一個不錯的PHP在線執行工具
<?php
define("TOKEN","weixin"); // 定義token
$wechatObj = new wechat_php(); // 生成類實例
$wechatObj->valid(); // 調用類的檢驗方法
// 定義一個操作微信公眾帳號的類
class wechat_php
{
// 定義公用校驗方法
public function valid()
{
$echoStr = $_GET["echostr"]; // 獲取GET請求的參數echostr
// 校驗signature
if($this->checkSignature ()) { // 調用校驗方法
echo $echoStr;
exit;
}
}
// 校驗方法
private function checkSignature ()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce); // 將三個參數保存到數組中
sort($tmpArr); // 對數組中三個數據進行排序
$tmpStr = implode( $tmpArr ); // 將數組中三個數據組成一個字符串
$tmpStr = sha1( $tmpStr ); // 對字符串進行SHA-1散列運算
if( $tmpStr == $signature ) { // 計算結果與$signature相等
return true; // 通過驗證
} else {
return false; // 未通過驗證
}
}
}
?>
4.開始編寫代碼進行開發
例1:文本消息自動被動回復
<?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 = "消息內容:" . $keyword . "\n";
$contentStr = $contentStr . "ToUserName:" . $toUsername . "\n";
$contentStr = $contentStr . "FromUserName:" . $fromUesrname;
}else{
$contentStr = "請輸入關鍵字...";
}
}
$resultStr = sprintf($textTpl, $fromUesrname, $toUsername, $time, $msgType, $contentStr);
ob_clean();
echo $resultStr;
}else{
echo "";
exit;
}
}
}
?>