我尝试做微信API集成。通过将文件放在公共文件夹中,它可以工作。这是我的代码
<?php
traceHttp();
define('TOKEN', 'xxxxx');
$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);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
public function responseMsg(){
//get post data, May be due to the different environments
$postStr = file_get_contents('php://input');
//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);
switch($postObj->MsgType){
case "event":
$this->_doEvent($postObj);
break;
case "text":
$this->_doText($postObj);
break;
case "image":
$this->_doImage($postObj);
break;
case "voice":
$this->_doVoice($postObj);
break;
case "music":
$this->_doMusic($postObj);
break;
case "location":
$this->_doLocation($postObj);
break;
default:
break;
}
}
现在我想在控制器中创建所有这些函数。但我得到file_get_contents('php://input')
的空值.我什至尝试使用$request->getContent()
和$request->all()
并且都返回空值。
任何人都可以告诉我问题出在哪里?我一整天都坚持这个问题,我真的很感激任何帮助。谢谢
下面是我的 laravel 控制器代码:
public function authenticate(Request $request) {
$token = 'xxxxxx';
define("TOKEN", $token);
if(isset($_GET['echostr'])) {
$this->valid();
} else {
$content = $request->all();
}
}
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);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if($tmpStr == $signature){
return true;
} else {
return false;
}
}
为了验证,微信 API 将使用 GET 请求,但发送消息将使用 POST 请求。
由于我的路由.php路由只是 Route::get,所以我的$request->getContent()
返回为空。
所以而不是Route::get('/wechat-api', 'WController@verify');
我改为Route::any('/wechat-api', 'WController@verify');
进行更改后,$request->getContent()
终于不再为空了。