嗨,我对 PHP 和 Messenger Bots 中的编码非常陌生。
我想知道如何访问向我的聊天机器人发送消息的人的姓名。
嗨,我对 PHP 和 Messenger Bots 中的编码非常陌生。
我想知道如何访问向我的聊天机器人发送消息的人的姓名。
用户配置文件 API可能会对您有所帮助。
使用event.sender.id
从 messenger bot 服务器 (/webhook) 收到的数据,并按照以下请求进行操作
curl -X GET "https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=<PAGE_ACCESS_TOKEN>"
那么你可以在下面得到返回的 json
{
"first_name": "Peter",
"last_name": "Chang",
"profile_pic": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p200x200/13055603_10105219398495383_8237637584159975445_n.jpg?oh=1d241d4b6d4dac50eaf9bb73288ea192&oe=57AF5C03&__gda__=1470213755_ab17c8c8e3a0a447fed3f272fa2179ce",
"locale": "en_US",
"timezone": -7,
"gender": "male"
}
您可以使用以下 PHP 片段来获取用户名
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name&access_token=<PAGE_ACCESS_TOKEN>');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo 'Hi ' . $obj['first_name'] . ' ' . $obj['last_name']
@Rajesh 对冲
您的代码有一个小错误:
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name&access_token=<PAGE_ACCESS_TOKEN>');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result); // *** here
echo 'Hi ' . $obj['first_name'] . ' ' . $obj['last_name']
$obj = json_decode($result, **true**);
$result
需要先转换为关联数组,然后才能像这样访问它:$obj['first_name']
有关详细信息,请参阅http://php.net/manual/en/function.json-decode.php。