PHP WeChat server-side code

<?php
//Introduce the package provided by WeChat to find the dependency library
include_once "wxBizMsgCrypt.php";
  
//your own token, appid and password assigned to you
define("TOKEN", "yourtoken");
define("APPID", "wxb21b4b3b11111111");
define("APPSECRET", "se8c89e213c8efab31d53fc98s6d2222");

$wechatObj = new wechatCallbackapiTest();

//authentication server
if(isset($_GET["openid"])){
	
	//check token
	$access_token = $wechatObj->getToken();
    $wechatObj->responseMsg();

}else if (isset($_GET["echostr"])){
	//Server token verification
    $wechatObj->valid();
}else{
	echo "empty";
}


class wechatCallbackapiTest  
{  
    public function valid()  
    {  
        $echoStr = $_GET["echostr"];
  
        //valid signature , option  
        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);  
        $tmpStr = implode( $tmpArr );  
        $tmpStr = sha1( $tmpStr );  
        
        if( $tmpStr == $signature ){  
            return true;  
        }else{  
            return false;  
        }  
    }

    public function responseMsg()
    {

		$postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
		//$fp = fopen("./post_data.txt", "w+");
		//fwrite($fp, $postStr);
		//fclose($fp);

		$postObj = simplexml_load_string($postStr,'SimpleXMLElement', LIBXML_NOCDATA);
        $RX_TYPE = trim($postObj->MsgType);

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

	//text message
    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";
            $contentStr = "Hello^_^";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }else{
            echo "Input something...";
        }
    }

    public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
			//Follow the event
            case "subscribe":
                $contentStr = "Thank you for your attention to [I love money]"."\n"."WeChat: happysoul0";
                break;
            default :
                $contentStr = "Unknow Event: ".$object->Event;
                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }
    
	// output return information
    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;
    }

	
	//Get the token and write it locally
	function getToken(){
		//Write the local file name, although this is not safe, it can be debugged like this for the time being
		$fileName = "./happysoul_access_token.json";

		$ appid = APPID;
		$appsecret=APPSECRET;
		if(!is_file($fileName)){
			$f = fopen($fileName, "w");
			fclose($f);
		}
		$file = file_get_contents($fileName,true);
		$result = json_decode($file,true);
		if (time() > $result['expires']){
			$data = array();
			$data['access_token'] = $this->getNewToken($appid,$appsecret);
			$data['expires']=time()+7000;
			$jsonStr =  json_encode($data);
			$fp = fopen($fileName, "w");
			fwrite($fp, $jsonStr);
			fclose($fp);
			return $data['access_token'];
		}else{
			return $result['access_token'];
		}
	}
	function getNewToken($appid,$appsecret){
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
		$access_token_Arr =  $this->https_request($url);
		return $access_token_Arr['access_token'];
	}
	function https_request ($url){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			$out = curl_exec($ch);
			curl_close($ch);
			return  json_decode($out,true);
	}

}  
  
?>


The attachment is the package provided by WeChat, including java php c++ ​​c# python


public platform-development-basic configuration (server configuration) Remember to verify the server and then enable it. People who
follow you can send messages to your official account before they can be sent to your server.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326236392&siteId=291194637