前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >php实现自动回复消息(网上教程有大坑,慎用)

php实现自动回复消息(网上教程有大坑,慎用)

作者头像
黄啊码
发布2022-05-10 10:21:40
7240
发布2022-05-10 10:21:40
举报
文章被收录于专栏:黄啊码【CSDN同名】

废话不多说,直接上代码

代码语言:javascript
复制

define("TOKEN",  config("wx_token"));
$wechatObj = new Wxapi();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}
class Wxapi
{
/**
 * 微信公众号验证
 */
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()
{
    //$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
    $postArr  = file_get_contents('php://input');
    //2.处理消息类型,并设置回复类型和内容
    $postObj = simplexml_load_string( $postArr );
    //判断该数据包是否是订阅的事件推送
    if(strtolower( $postObj->MsgType) == 'event'){
        //如果是关注 subscribe 事件
        // 超链接里边指定data-miniprogram-path跳转小程序某个页面
        if( strtolower($postObj->Event == 'subscribe') ) {
            Log::info("有人关注");
            Log::info("1");
            //回复用户消息(纯文本格式)
            $fromUsername = $postObj->FromUserName; //请求消息的用户
            $toUsername = $postObj->ToUserName; //"我"的公众号id
            $keyword = trim($postObj->Content); //消息内容
            $time = time(); //时间戳
            $msgtype = 'text'; //消息类型:文本
            $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>";

            if(strtolower($postObj->MsgType == 'event' )){ //如果XML信息里消息类型为event
                if($postObj->Event == 'subscribe'){ //如果是订阅事件
                    $contentStrq = $content = '欢迎关注';
                    $resultStrq = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStrq);
                    echo $resultStrq;
                    exit();//一定要加!!!!不加程序运转正常就是不回复消息
                }
            }
        }
    }
}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云开发 CloudBase
云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档