微信公众号接入(php)

原理去看微信文档,直接上代码

<?php
/**
  * wechat php test
  */
//define your token
define("TOKEN", "DKFDKL4859jkljsdfkls");
$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"];
		$postStr = file_get_contents("php://input");

      	        //extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$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($postObj->MsgType == 'image') {
                        $pic = $postObj->PicUrl;                

              		$msgType = "text";

			$cont = file_get_contents($api);
			$cont = json_decode($cont , true)['face'];


			if( count($cont) == 0 ) {
			    $str = '什么破图,不要脸了';
			} else {
			    $str = '检测出来'.count($cont)."个人,分别是\n";
			    foreach($cont as $v) {
		                $str .= '种族:' . $v['attribute']['race']['value'];
			        $str .= ',性别:' . $v['attribute']['gender']['value'];
			        $str .= ',年龄' . $v['attribute']['age']['value']."\n";
			    }
			}


                	$contentStr = $str;
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;

		}else if($postObj->MsgType == 'location') {
                        $wd = $postObj->Location_X; 
                        $jd = $postObj->Location_Y; 
			
			$word = urldecode("厕所");
			$api = "http://api.map.baidu.com/telematics/v3/local?location={$jd},{$wd}&keyWord={$word}&output=json&ak=07c8d27bbe614cfeec7383b722c6ccb4";

			$cont = file_get_contents($api);

			//echo $cont;

			$cont = json_decode($cont , true)['pointList']['0'];
			$addr = $cont['address'].$cont['type'].'离你有'.$cont['distance'].'米';



              		$msgType = "text";
                	$contentStr = $addr;
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
		} else if(!empty( $keyword ))
                {
              		$msgType = "text";
                	$contentStr = "欢迎来到布尔教育";
                	$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;
		}
	}
}

?>

猜你喜欢

转载自blog.csdn.net/taotaobaobei/article/details/81322123