1. 程式人生 > >微信公眾號開發2自動回覆

微信公眾號開發2自動回覆

這裡就囉嗦什麼了, 直接上程式碼


/**

* wechat php test

*/

//define your token

define("TOKEN","weixin");

$wechatObj=newwechatCallbackapiTest();

$wechatObj->responseMsg();

classwechatCallbackapiTest

{

public functionvalid()

{

$echoStr=$_GET["echostr"];

//valid signature , option

if($this->checkSignature()){

echo$echoStr;

exit;

}

}

public functionresponseMsg()

{

//get post data, May be due to the different environments

$postStr=$GLOBALS["HTTP_RAW_POST_DATA"];

//extract post data

if(!empty($postStr)){

$postObj=simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);

$fromUsername=$postObj->FromUserName;

$toUsername=$postObj->ToUserName;

$keyword=trim($postObj->Content);

$time=time();

$textTpl="

%s

0

";

if(!empty($keyword))

{

//這裡手動編輯自動回覆

$msgType="text";

switch($keyword){

case'1';

$contentStr="http://www.minxiny.com/";

break;

case'2':

$contentStr="您有什麼健康問題呢?請傳送關鍵詞,或者關注公眾號: hello kitty 獲取更多相關健康問題";

break;

case'3':

$contentStr="請搜尋小程式 百姓堂 允許獲取定位來使用該功能";

break;

default:

$contentStr=<<< MESG

歡迎訪問百年臻陽方,本公眾號由廣東泓然堂醫藥有限公司提供,為您的健康提供全方位保障,點選關注有驚喜.

1  訪問公司官網

2  諮詢健康問題

3  尋找附件的藥店

MESG;

break;

}

//                $msgType = "text";

//                $contentStr = "歡迎訪問百年臻陽方,本公眾號由廣東泓然堂醫藥有限公司提供,為您的健康提供全方位保障,點選關注有驚喜";

$resultStr=sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);

echo$resultStr;

}else{

echo"Input something...";

}

}else{

echo"";

exit;

}

}

private functioncheckSignature()

{

$signature=$_GET["signature"];

$timestamp=$_GET["timestamp"];

$nonce=$_GET["nonce"];

$token=TOKEN;

$tmpArr=array($token,$timestamp,$nonce);

sort($tmpArr);

$tmpStr=implode($tmpArr);

$tmpStr=sha1($tmpStr);

if($tmpStr==$signature){

return true;

}else{

return false;

}

}

}

?>