關於微信接入第三方域名進行業務開發的相關說明已在另外一篇做了說明,這裏不做贅述,接入步驟請移步
https://blog.csdn.net/qq_43638176/article/details/88915436
本篇示範微信交互過程中的幾個基礎事件,主要判斷標準參數爲$postObj->MsgType,分別介紹當用戶對公衆號上傳一個圖片,回覆一個文本以及關注事件的幾個推送,其他諸如音樂回覆將在下一篇做總結。
可以查看官方文檔:
接受普通消息:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453
被動回覆:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140543
具體代碼實現:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
header("Content-type: text/html; charset=utf-8");
define("TOKEN","token");//定義識別碼 需要跟微信公衆平臺上保持一致
class Blog extends Controller
{
public function index(){
$this->valid();
}
//微信驗證
public function valid(){
$echoStr = $_GET["echostr"];
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 );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
public function responseMsg(){
$poststr = file_get_contents('php://input');
//如果推送消息 或者推送事件存在,進行處理
if(!empty($poststr)){
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($poststr, 'SimpleXMLElement', LIBXML_NOCDATA);
$msgType = $postObj->MsgType;
//判斷事件類型,進行對應事件類型處理
switch ($msgType) {
//當回覆公衆號時
case 'text':
$resultStr = $this->handleText($postObj);
break;
case 'image':
$resultStr = $this->handleImage($postObj);
break;
case 'voice':
$resultStr = $this->handleVoice($postObj);
break;
case 'video':
$resultStr = $this->handleVideo($postObj);
break;
case 'shortvideo':
$resultStr = $this->handleShortVideo($postObj);
break;
case 'location':
$resultStr = $this->handleLocation($postObj);
break;
case 'link':
$resultStr = $this->handleLink($postObj);
break;
case 'event':
$resultStr = $this->handleEvent($postObj);
break;
default:
$resultStr = "Unknow msg type: ".$msgType;
break;
}
return $resultStr;
}
}
//
//回覆消息
public function handleText($postObj)
{
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->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(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}
}