我尝试进行微信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;
}
}
答案 0 :(得分:1)
结果是验证,微信api将使用GET请求,而发送msg将使用POST请求。
由于我的route.php路由仅为Route :: get,所以我的$request->getContent()
返回空。
所以不是Route::get('/wechat-api', 'WController@verify');
我更改为Route::any('/wechat-api', 'WController@verify');
进行更改后,$request->getContent()
最终不再为空。