本文主要是介绍【黄啊码】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信息里消息类型为eventif($postObj->Event == 'subscribe'){ //如果是订阅事件$contentStrq = $content = '欢迎关注';$resultStrq = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStrq);echo $resultStrq;exit();//一定要加!!!!不加程序运转正常就是不回复消息}}}} }}
这篇关于【黄啊码】php实现关注公众号自动回复消息(网上教程有大坑,慎用)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!