【黄啊码】php实现关注公众号自动回复消息(网上教程有大坑,慎用)
·
废话不多说,直接上代码
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();//一定要加!!!!不加程序运转正常就是不回复消息 } } } } }}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)