Thinkphp5实现公众号关键词回复消息

ThinkPHP5中实现微信公众号的关键词回复消息,你需要完成以下几个步骤:

1. 配置微信公众号

首先,确保你已经在微信公众平台上注册并配置好了公众号,并且获取了相应的AppIDAppSecret

2. 验证服务器地址的有效性

微信服务器会发送一个GET请求到你配置的服务器地址,你需要验证这个请求以确认服务器地址的有效性。

在你的控制器中添加一个方法来处理这个验证请求:

namespace app\index\controller;

use think\Controller;
use think\Request;

class Wechat extends Controller
{
    public function verify(Request $request)
    {
        $signature = $request->get('signature');
        $timestamp = $request->get('timestamp');
        $nonce = $request->get('nonce');
        $echostr = $request->get('echostr');

        $token = 'your_token'; // 你在微信公众平台设置的Token

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            echo $echostr;
        } else {
            echo '';
        }
    }
}

3. 处理用户消息

当用户发送消息到公众号时,微信服务器会发送一个POST请求到你配置的服务器地址。你需要解析这个请求并回复相应的消息。

在你的控制器中添加一个方法来处理这个POST请求:

public function handleMessage(Request $request)
{
    $postXml = file_get_contents("php://input");
    $postObj = simplexml_load_string($postXml, 'SimpleXMLElement', LIBXML_NOCDATA);

    if ($postObj->MsgType == 'text') {
        $keyword = trim($postObj->Content);
        $reply = '';

        // 根据关键词回复消息
        switch ($keyword) {
            case 'hello':
                $reply = '你好!';
                break;
            case 'help':
                $reply = '需要帮助吗?';
                break;
            default:
                $reply = '对不起,我暂时无法理解你的意图。';
                break;
        }

        $toUser = $postObj->FromUserName;
        $fromUser = $postObj->ToUserName;
        $time = time();
        $msgType = 'text';

        $template = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                     </xml>";

        $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $reply);
        echo $info;
    }
}

4. 配置路由

在你的route.php文件中配置路由,以便微信服务器能够访问到你的验证和处理方法:

use think\Route;

Route::get('wechat/verify', 'Wechat/verify');
Route::post('wechat/message', 'Wechat/handleMessage');

5. 配置服务器地址

在微信公众平台的开发者中心,配置服务器地址为你的域名加上上述路由,例如:http://yourdomain.com/wechat/verifyhttp://yourdomain.com/wechat/message

总结

通过以上步骤,你就可以在ThinkPHP5中实现微信公众号的关键词回复消息功能。确保你的服务器能够正确处理微信服务器的请求,并根据用户的输入返回相应的回复消息。

0 条评论

还没有人发表评论

发表评论 取消回复

记住我的信息,方便下次评论
有人回复时邮件通知我