微信公眾號之自動回覆文字 -- PHP
首先得設定一個 可以接受 微信伺服器 發過來 的東西的 無許可權 的接收資訊的網址
怎麼設定自己去官方文件上看看
然後微信 會 發個東西來 驗證一下你 的這個網址是否正確
具體驗證操作程式碼如下
/**
* 微信接入
*/
function sss() {
//$this->responseMsg();
//如果相等,驗證成功就返回echostr 只需 一次呼叫
if ($this->checkSignature()) {
//返回echostr
$echostr = $_GET['echostr'];
if ($echostr) {
echo $echostr;
} else {
echo "Access error.";
}
}
exit;
}
//檢查標籤
function checkSignature() {
//先獲取到這三個引數
$signature = $_GET['signature'];
$nonce = $_GET['nonce'];
$timestamp = $_GET['timestamp'];
//把這三個引數存到一個數組裡面
$tmpArr = array($timestamp, $nonce, $this->token
//進行字典排序
sort($tmpArr);
//把陣列中的元素合併成字串,impode()函式是用來將一個數組合併成字串的
$tmpStr = implode($tmpArr);
//sha1加密,呼叫sha1函式
$tmpStr = sha1($tmpStr);
//判斷加密後的字串是否和signature相等
if ($tmpStr == $signature) {
return true;
}
return false;
}
那麼驗證成功後需要注意的一點是
從現在開始,這個傳送的網址就已經生效了,需要做的是
把這個驗證程式碼給去掉,去寫你的業務邏輯程式碼
接下來就好處理了,微信公眾號上 使用者 發的訊息,都會經過 微信伺服器 轉發到你寫的這個 方法來
public function responseMsg() {
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信發來的XML資料
//extract post data
if (!empty($postStr)) {
//解析post來的XML為一個物件$postObj
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //請求訊息的使用者
$toUsername = $postObj->ToUserName; //"我"的公眾號id
$keyword = trim($postObj->Content); //接受到使用者的訊息內容
$Latitude = $postObj->Latitude; //緯度
$Longitude = $postObj->Longitude; //經度
$Precision = $postObj->Precision; //地理位置精度
$Event = $postObj->Event; //事件型別
$time = time(); //時間戳
$msgtype = 'text'; //訊息型別:文字
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
/**
* 地理位置確認
*/
if ($Event == 'LOCATION') {
$useraddress = $this->upuser($fromUsername, $Longitude, $Latitude, $Precision);
// $this->sendmsg($textTpl, $fromUsername, $toUsername, $time, $msgtype, "您當前位置是:{$useraddress}");
die;
}
//簽到設定
if (strpos($keyword, "簽到") !== false ) {
$contentStr = "簽到成功。";
}
}
if (empty($ary[$keyword]) && empty($contentStr)) {
$contentStr = M("setting")->where("id = 6 and state = 1")->getField("setval");
$contentStr = $contentStr ? $contentStr : '歡迎關注乖寶寶兒童攝影。';
} else {
$contentStr = $contentStr ? $contentStr : $ary[$keyword];
}
$this->sendmsg($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
} else {
echo "";
}
}
/**
*返回訊息給 微信伺服器,注意格式。。。
*/
function sendmsg($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr) {
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
echo $resultStr;
}