微信机器人,关注回复,天气

如有问题,请联系qq  1184139881


wxs.php

<?php
/**
 * wechat php test
 */


//define your token
define("TOKEN", "weixin");


//file_put_contents("7.txt",$_GET["echostr"]."--echostr--".$_GET["signature"]."--sign--".$_GET["timestamp"]."--timestamp--".$_GET["nonce"]."--nonce--");


$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);
            $RX_TYPE = trim($postObj->MsgType);
            $str = $postObj->Content;
            file_put_contents('a.txt',$str);




            switch($RX_TYPE)
            {
                case "voice":
                    $resultStr = $this->receiveVoice($postObj);
                    break;
                case "location":
                    $resultStr = $this->receiveLocation($postObj);
                    break;
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }


    public function handleText($postObj)
    {
        $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";
            $str_trans = mb_substr($keyword,0,2,"UTF-8");
            $str_valid = mb_substr($keyword,0,-2,"UTF-8");


            if($str_trans == '翻译' && !empty($str_valid)) {


                $word = mb_substr($keyword, 2, 202, "UTF-8");
                //调用有道词典
                $contentStr = $this->youdaoDic($word);
                //调用百度词典
//                $contentStr = $this->baiduDic($word)."【百度】";


            }elseif ($keyword == "你好") {
                $contentStr = "hello";
            } elseif ($keyword == "时间") {
                $contentStr = date("Y-m-d H:i:s");
            } else {
               $contentStr = $this->qingyunDic($postObj,$keyword);
            }


            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        } else {
            echo "Input something...";
        }
    }




        function handleEvent($object){
        $contentStr="";
        switch ($object->Event)
        {
            case "subscribe":
                $contentStr=array(
                    'title'=>'渲染笔墨情',
                    'content'=>'本公司成立于2017年,主要经营与互联网相关的业务...',
                    'pic'=>'http://dsf.hk137.com/images/test.jpg',
                    'url'=>'http://m.cnblogs.com/?u=txw1958'
                );
                break;
            case "CLICK":
                switch($object->EventKey)
                {
                    case "company_intro":
                        $contentStr=array(
                            'title'=>'公司简介',
                            'content'=>'本公司成立于2017年,主要经营与互联网相关的业务...',
                            'pic'=>'http://1158410.sqnet.cn/ge/images/zgf.jpg',
                            'url'=>'1158410.sqnet.cn/ge/weixin01.html'
                        );
                        break;
                    case "weather":
                        $contentStr="请输入要查询的城市名称..";
                        break;
                    case "contact":
                        $contentStr="联系人:公司老总 ,CEO  X先生;联系电话:......";
                        break;
                    default :
                        break;
                }
                break;
            default :
                $resultStr = "Unknow Event: ".$object->Event;
                break;
        }


         if(is_array($contentStr)){
            $resultStr = $this->responseNews($object, $contentStr);
        }else{
            $resultStr = $this->responseText($object,$contentStr);
        }
        return $resultStr;
    }


    //关注  简介回复
    function responseNews($object,$arr,$flag=0){
        $newsTplHead = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>1</ArticleCount>
                <Articles>";
        $newsTplBody = "<item>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                <PicUrl><![CDATA[%s]]></PicUrl>
                <Url><![CDATA[%s]]></Url>
                </item>";
        $newsTplFoot = "</Articles>
                <FuncFlag>0</FuncFlag>
                </xml>";
        $resultStr = sprintf($newsTplHead, $object->FromUserName, $object->ToUserName, time());
        $resultStr.=sprintf($newsTplBody, $arr["title"], $arr['content'], $arr['pic'],$arr['url']);
        $resultStr.=$newsTplFoot;


        return $resultStr;


    }


    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }


    //有道翻译
    public function youdaoDic($word){


        $keyfrom = "lswx1205"; //申请APIKEY时所填表的网站名称的内容
        $apikey = "1747864206";  //从有道申请的APIKEY


       //有道翻译-xml格式
        $url_youdao = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom='.$keyfrom.'&key='.$apikey.'&type=data&doctype=xml&version=1.1&q='.$word;


        $xmlStyle = simplexml_load_file($url_youdao);


        $errorCode = $xmlStyle->errorCode;


        $paras = $xmlStyle->translation->paragraph;


        if($errorCode == 0){
            return $paras;
        }else{
            return "无法进行有效的翻译";
        }
    }


        //机器人
        public function qingyunDic($obj,$keyword){


       $url_qingyun =  'http://www.tuling123.com/openapi/api?key=9d88bcb904b24bdcb68f8ffd8634ebde&info='.$keyword;


        $jsonStyle = file_get_contents($url_qingyun);




        $result = json_decode($jsonStyle,true);


        $errorCode = $result['code'];


        $trans = '';


        if(isset($errorCode)){


            switch ($errorCode){
                case 100000:
                    $trans = $result['text'];
                    break;
                case 200000:
                    $trans = $this->tulingURL($obj,$result);
                    break;
                case 30:
                    $trans = '无法进行有效的翻译';
                    break;
                case 40:
                    $trans = '不支持的语言类型';
                    break;
                case 50:
                    $trans = '无效的key';
                    break;
                default:
                    $trans = '出现异常';
                    break;
            }
        }


        return $trans;
        }




    function tulingURL($object,$ob,$flag=0){
        $url=$ob['url'];
        $content=$ob['text'];
        $fromuser=$object->FromUserName;
        $touser=$object->ToUserName;


        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    <URL><![CDATA[%s]]></URL>
                    </xml>";
        $resultStr = sprintf($textTpl, $fromuser, $touser, time(), $content, $flag, $url);
        return $resultStr;


    }






    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }


        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];


        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );


        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


    //接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是:".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }
        return $result;
    }


    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
        <MediaId><![CDATA[%s]]></MediaId>
    </Voice>";


        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[voice]]></MsgType>
    $item_str
</xml>";


        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }






    //接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置,经度为:".$object->Location_Y.";纬度为:".$object->Location_X.";缩放级别为:".$object->Scale.";位置为:".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }
}

?>


token.php

<?php
//判断存储token文件存不存在
if ( file_exists('./token.txt') ) {
    //如果文件存在  判断文件更新时间  每个token的使用时效是7200s
    $filemTime  = filemtime('./token.txt') ;
    $nowTime = time();


    //判断文件是否过期  现在时间-文件更新时间大于7000默认过期  过期重新获取
    if ( ($nowTime - $filemTime) > 7000 ){


        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4f40e2ce105edc40';


        $token = file_get_contents( $url );
        file_put_contents( './token.txt' , $token );


    } else {
        //如果没过期  获取文件中的token
        $token = file_get_contents( './token.txt' );
    }


} else {
    //如果不存在  就获取tolen并且写入文件
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4f40e2ce105edc40&secret=a3ff7ccc90d5cdfcd450c1ffda083f8f';


    $token = file_get_contents( $url );
    file_put_contents( './token.txt' , $token );
}


echo $token;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值