2017-05-08 149 views
0

我正在爲PHP編寫Facebook的機器人。我可以發送文本併發送並快速回復。但是我不可能回覆郵件。我使用ngrok進行localhost測試,但我知道這不是問題,因爲它不能在我的vps上運行2.所有其他功能都按預期工作。Facebook Messenger Chatbot - 我無法回覆回覆

我發送後回代碼:

$jsonData = '{ 
     "recipient":{ 
     "id":"'.$sender.'" 
     }, 
     "message":{ 
     "attachment":{ 
      "type":"template", 
      "payload":{ 
      "template_type":"button", 
      "text":"What do you want to do next?", 
      "buttons":[ 
       { 
       "type":"postback", 
       "title":"Start Chatting", 
       "payload":"USER_DEFINED_PAYLOAD" 
       } 
      ] 
      } 
     } 
     } 
    }'; 
    $url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token; 
$ch = curl_init($url); 

//Tell cURL that we want to send a POST request. 
curl_setopt($ch, CURLOPT_POST, 1); 
//Attach our encoded JSON string to the POST fields. 
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); 
//Set the content type to application/json 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
//Execute the request 

if(!empty($message_body['message'])){ 
    $result = curl_exec($ch); 
} 

然後,當我收到後回我得到這個從FB信使:

{ 
    "object": "page", 
    "entry": [ 
     { 
      "id": "590445400970275", 
      "time": 1494251031827, 
      "messaging": [ 
       { 
        "recipient": { 
         "id": "590445400970275" 
        }, 
        "timestamp": 1494251031827, 
        "sender": { 
         "id": "1075794782546272" 
        }, 
        "postback": { 
         "payload": "USER_DEFINED_PAYLOAD" 
        } 
       } 
      ] 
     } 
    ] 
} 

和我的代碼來分析吧:

$input = json_decode(file_get_contents('php://input'), true); 
$message_body = $input['entry'][0]['messaging'][0]; 
$sender = $message_body['sender']['id']; 
if (isset($message_body['postback'])){ 
    //Reception d'un postback 
    $postback = $message_body['postback']['payload']; 
    if ($postback == "USER_DEFINED_PAYLOAD"){ 
    // The JSON data. 
    $jsonData = '{ 
     "recipient":{ 
     "id":"'.$sender.'" 
     }, 
     "message":{ 
     "text":"messagetoreply" 
     } 
    }'; 
    } 
} 

這是由curl函數發送的消息之前。

然而使者從未收到一個答案: enter image description here

誰能幫我找出其中的問題?

非常感謝您

回答

0

有在這部分我的代碼中的錯誤:

if(!empty($message_body['message'])){ 
    $result = curl_exec($ch); 
} 

自$ MESSAGE_BODY變種是不是「消息」,但一個「回傳」,捲曲不發送回覆。