首先在微信公眾平臺(網址:https://mp.weixin.qq.com)申請一個訂閱號,然后在開發里找到開發者工具點擊公眾平臺測試賬號,在測試賬號內進行微信開發實驗。? ? 1. 設置一個自己的有效的域名網址和TOKEN(就是暗號),TOKEN一定要與PHP代碼中的TOKEN驗證一致否則會一直配置失敗(寫有這段代碼的文件一定要傳到有效的域名網址內。與設置的網址必須相同)。? ? 下面是PHP代碼(在微信公眾平臺開發里的開發者文檔內有部分代碼) 。
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->run();
class wechatCallbackapiTest
{
public function run()
{
if ($this->checkSignature()==false) {
die('非法請求');
}
if (isset($_GET["echostr"])) {
$echostr = $_GET["echostr"];
echo $echostr;
exit();
} else {
$this->responseMsg();
}
/*$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;*/
}
}
public function responseMsg()
{
//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";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
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 );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>
2.自動回復?首先重新寫一個方法在上面那個文件夾里,再調用此方法,注意不能重名。以下代碼是給訂閱號發天氣,它會回復天氣晴朗,發放假,它會回復你“不好好奮斗瞎想啥?”回復其他則會回復"Welcome to wechat world!"public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
file_put_contents('msg.txt', $postStr,FILE_APPEND);
//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();
//$msgType = $postObj->MsgType;//消息類型
//$event = $postObj->Event;//時間類型,subscribe(訂閱)、unsubscribe(取消訂閱)
$textTpl = "
%s
0
";
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = $this->autohuifu($keyword);
//$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
public function autohuifu($keyword){
if($keyword =='天氣'){
$contentStr = "天氣晴朗";
}else if($keyword =='放假'){
$contentStr = "成天不好好奮斗瞎想啥?";
}else{
$contentStr = "Welcome to wechat world!";
}
return $contentStr;