php - 微信公众号开发者自动回复设置没反应

查看:224
本文介绍了php - 微信公众号开发者自动回复设置没反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在新浪sea平台设置了微信公众号应用,设置关注自动回复功能,接口设置成功,,代码写好,url也修改代码的页面,但是测试后没反应。
<?php

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
$wechatObj->responseMsg();
class wechatCallbackapiTest
{

    public function valid()
{
    $echoStr = $_GET["echostr"];

    //valid signature , option
    if($this->checkSignature()){
            echo $echoStr;
            exit;
    }
}

public function responseMsg()
{
            //get post data, May be due to the different environments
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

    //extract post data
            if (!empty($postStr)){
            
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content); 
            $time = time();
            $textTpl = "<xml>
                                                    <ToUserName><![CDATA[%s]]></ToUserName>
                                                    <FromUserName><![CDATA[%s]]></FromUserName>
                                                    <CreateTime>%s</CreateTime>
                                                    <MsgType><![CDATA[%s]]></MsgType>
                                                    <Content><![CDATA[%s]]></Content>
                                                    <FuncFlag>0</FuncFlag>
                                                    </xml>";             
                            if(!empty( $keyword ))
            {
                    $msgType = "text";
                    $contentStr = "Welcome to wechat world!";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
            }else{
                    echo "Input something...";
            }

    }else {
            echo "";
            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;
            }
    }

}

?>

解决方案

valid方式是用来检测所发消息是否来自微信服务器的,它会输出内容到页面中来,所以会打乱你要回复的XML包
只调用responseMsg方法即可

这篇关于php - 微信公众号开发者自动回复设置没反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆