1. 程式人生 > >Laravel框架之微信機器人,關鍵字回覆

Laravel框架之微信機器人,關鍵字回覆

我們每個人都在使用微信,那訂閱號,公眾號中的機器人以及關鍵字是如何實現的呢?

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use function Couchbase\defaultDecoder;

class ApiController extends Controller{
    /*此處開始為機器人以及關鍵字回覆*/
    public function robot(){
        define("TOKEN", "mengxianglei");
        $wechatObj = new ApiController();
        if(!isset($_GET['echostr'])){
            $wechatObj->responseMsg();
        }else{
            $wechatObj->valid();
        }
    }
	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 = file_get_contents("php://input");
//		var_dump($postStr);die;
      	//extract post data
		if (!empty($postStr)){
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
				$type = trim($postObj->Event);
                $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($type == "subscribe")
				{
					$textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[news]]></MsgType>
						<ArticleCount>1</ArticleCount>
						<Articles>
						<item>
						<Title><![CDATA[第五組測試]]></Title>
						<Description><![CDATA[歡迎來到第五組測試公眾號,我們現在有如下功能:
						            1.PHP教程,如輸入:php 
						           ]]></Description>
						<PicUrl><![CDATA[http://p0.so.qhimg.com/t013971ecacef25bf25.jpg]]></PicUrl>
						<Url><![CDATA[http://www.so.com/s?q=圖片&src=se6_toolbar&ie=utf-8&_jmp=1]]></Url>
						</item>
						</Articles>
						</xml>				
						";
					$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time);
					echo $resultStr;
				}
				if(!empty( $keyword ))
                {
              		switch($keyword){//此處為自己填寫的死資料,後期可以通過調取資料庫的資訊
                        case "php":
                            $msgType = "text";
                            $contentStr = "php教程:http://m.runoob.com/php";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            echo $resultStr;
                            break;
                        case "python":
                            $msgType = "text";
                            $contentStr = "Python教程:http://m.runboo.com/python";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            echo $resultStr;
                            break;
                        case "java":
                            $msgType = "text";
                            $contentStr = "Java教程:http://m.runboo.com/java";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            echo $resultStr;
                            break;
                        default:
                            $msgType = "text";
                            $url="http://apis.haoservice.com/efficient/robot?info=$keyword&address=&key=9822f39592d64366b7e0605cd97ef196";
                            $contentStr = json_decode(file_get_contents($url),true)['result']['text'];//取出回覆的訊息
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            echo $resultStr;
                    }
                }else{
                	echo "Input something...";
                }
        }else {
        	echo "";
        	exit;
        }
    }
	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;
		}
	}
}

因為從微信接收的訊息都是POST方式接收的,所以我們在呼叫介面的時候需要在
app\Http\Middleware這個目錄下面的 VerifyCsrfToken.php檔案中加上你的路由,進行免csrf驗證