Facebook Messenger Bot - PHP cURL消息

时间:2016-05-27 22:36:53

标签: php json facebook curl

过去几天我一直在摆弄Facebook Messenger平台并遇到了一个问题。 PHP一直是主要语言。

成功地,我已经能够通过纯文本将几个API实现到系统中。 (见下图)

enter image description here

这就是系统的样子:

$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$answer = "I don't understand that. Is that another language? Type 'hi' to get started.";

if($message == "hi") {
    $answer = "Yo!";
}

如果您不熟悉,所有这些都来自Facebook Messenger Getting Started

我现在尝试做的是将图像通过cURL传递给JSON。这是我不熟悉的事情,但找到了两个很好的资源来帮助我完成这项任务。 POSTing JSON Data With PHP cURLCreate nested list from Multidimensional Array

结果如下:

if($message == "test") {
$data = array("message" => array("attachement" => array('"type" => "image"'),"payload" => array('"url" => "http://example.com"')));                                                                    
$data_string = json_encode($data);                                                                                   

$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token=TOKEN_GOES_HERE');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                               
$answer = curl_exec($ch);
}

以下是我收到的回复: enter image description here

我确信,cURL没有正确地获取参数。虽然,我对cuRL的了解有限,但另有说法。我的问题是,我怎么能做到这一点呢?我希望能够使用PHP将图像通过JSON传递给messenger。

1 个答案:

答案 0 :(得分:1)

我认为你的帖子请求工作正常,但是由于错误,你没有传递整个json数据。

以下是图片通用邮件的外观,您将收件人放在数据中的哪个位置?

{
  "recipient":{
    "id":"USER_ID"
  },
  "message":{
    "attachment":{
      "type":"image",
      "payload":{
        "url":"https://petersapparel.com/img/shirt.png"
      }
    }
  }
}

参考:https://developers.facebook.com/docs/messenger-platform/send-api-reference#guidelines