php-微信公众号与新浪sae接口代码

2021-11-27 85 0

定义TOKEN,开发启用时用到;
定义一个wechatCallbackapiTest()的类;
验证消息确实来自微信服务器;
接受原始的xml数据包;
封装你想发送的xml数据返回给用户;

<?php
define("TOKEN", "kantm");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
    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, SORT_STRING);//将token、timestamp、nonce三个参数进行字典序排序
        $tmpStr = implode( $tmpArr );//将数组转换成字符串
        $tmpStr = sha1( $tmpStr );//sha1加密
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

	//具体功能实现

    public function responseMsg()
    {
        //接受post过来的原始数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            //数据载入对象中
            //对象名为SimpleXMLElement
            $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($keyword)
            {
                $msgType = "text";
                $contentStr = date("Y-m-d H:i:s",time());
                //封装xml并返回给用户
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }
        }else{
            echo "";
            exit;
        }
    }
}
?>

相关文章

Linux-如何升级php的版本
WordPress-更换链接格式之后报404错误
Linux-使用Remi源安装最新版PHP
PHP-WordPress连接数据库失败问题
php-网络安全实验室脚本关快速口算题
php-从网页中提取关键字

发布评论