微信公众号文本消息
-
首先需要创建一个微信公众号
-
在基本配置中添加服务器配置(已启用),验证接口
-
代码
<?php
namespace App\Http\Controllers\Weixin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class IndexController extends Controller
{
public function checkSignature(Request $request)
{
if($request->method()=='GET'){
$signature = $_GET['signature'];
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
$token = 'mayuliang';
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = sha1(implode($tmpArr));
if($tmpStr == $signature && isset($_GET['echostr']) && $_GET['echostr']) {
echo $_GET['echostr'];
Log::error('success', ['message'=>'success']);
exit;
}
} else {
echo $this->reponseMsg();
}
}
public function reponseMsg()
{
$postStr = file_get_contents("php://input");
$postArr = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
Log::error('error', ['message'=>$postArr['FromUserName']]);
$FromUserName = $postArr['FromUserName']; //获取发送方帐号(OpenID)
$ToUserName = $postArr['ToUserName']; //获取接收方账号
Log::error('error',['message'=>$postArr['MsgType']]);
if (strtolower($postArr['MsgType'])=='event') {
if(strtolower($postArr['Event'])=='subscribe'){
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$content = '欢迎关注';
$type = "text";
$resultStr = sprintf($template,$FromUserName,$ToUserName, time(), $type, $content);
Log::error('error', ['message'=>$resultStr]);
return $resultStr;
}
}
}
}
遇到的坑:
- laravel框架需要处理验证,需要去 Kernel.php 中去掉 VerifyCsrfToken::class
- 接收到的ToUserName 是目标 FromUserName
- 网上很多simplexml_load_string($postStr, ‘SimpleXMLElement’, LIBXML_NOCDATA)但是我没有获取到,json_decode(json_encode(simplexml_load_string($postStr, ‘SimpleXMLElement’, LIBXML_NOCDATA)), true)