PHP Messenger中的Facebook Messenger bot,我做错了什么?

时间:2016-12-29 21:01:49

标签: php facebook api messenger

更新:我重写了这个脚本4次,我理解了这个机制,但遗憾的是我不明白缺少什么..错误代码是一样的..

<?php
// parameters
$hubVerifyToken = 'XXXXXX';
$accessToken = "xxxxxxxxxxxxxx";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$answer = "I don't understand. Ask me 'hi'.";
if($messageText == "hi") {
  $answer = "Hello";
}
$response = [
  'recipient' => [ 'id' => $senderId ],
  'message' => [ 'text' => $answer ]
];
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);
//based on http://stackoverflow.com/questions/36803518

但是如果我打开API的页面,我会收到以下错误消息:

{
 "error": {
 "message": "(#100) The parameter user_id is required",
 "type": "OAuthException",
 "code": 100,
 "fbtrace_id": "G8FOo08+EsE"
 }
}

如果缺少user_id,我在哪里以及如何写入?我应该使用user_id什么? PHP代码不再可以使用了吗?我应该使用例如this site而不是PHP?

1 个答案:

答案 0 :(得分:-1)

试试这个......

$response = [
  'recipient' => [ 'user_id' => $senderId ],
  'message' => [ 'text' => $answer ]
];