我不是 php 开发人员,但在 javascript、node.js 中实现了相同的逻辑。我想详细分享这些步骤以及 javascript 代码,希望你能弄清楚你能用它做什么来让你的生活更美好:P
正如您所说,您正在从 api 调用接收 user_ref 。这是正确的。再次阅读文档,他们提到当用户选中复选框插件时将收到 user_ref。此 user_ref 由您设置,每次页面加载时,此 user_ref 必须是唯一的,然后只有复选框插件将呈现,如果它不是唯一的插件将不会呈现。这是其背后的完整逻辑。您生成 user_ref,当用户选中复选框时,您会收到此 unqiue user_ref,使用此 user_ref 向用户发送消息(您可以根据需要多次使用 user_ref 向用户发送消息,但我建议您宁愿使用 senderId) .当您使用 user_ref 向用户发送消息时,webhook api 会给您一个包含用户的 senderId 的响应,这实际上是我们通常在我们的应用程序中使用的 psid。这是您需要保存在数据库中的内容。
现在我将把我的代码放在这里。
接收 user_ref 并向用户发送消息:
我的有效载荷:
function sendTextMessageRef(user_ref, messageText,md) {
var messageData = {
recipient: {
user_ref: user_ref
},
message: {
text: messageText,
metadata: md
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
if (messageId) {
console.log("Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("Successfully called Send API for recipient %s",
recipientId);
}
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
}
现在,在发送消息后,我会收到一个 json 格式的响应,其中将包含用户的发件人 ID:
{"sender":{"id":"xxxxxxx"},"recipient":{"id":"xxxxxWhat you are looking for is this*******"},"timestamp":1504698781373,"message":{"is_echo":true,"app_id":xxxxxxxxxxxxxxx,"metadata":"INVITATION__REPLY__qwe__2017-09-05T02xo20__xxxxxxxx__063__yes","mid":"mid.$cAAGcxxxxxxxxVxuAtJ","seq":120162,"text":":)"}}
在上面收到的 json 数据中,recipient.id 就是您要查找的内容。
在这里为了让您了解我在聊天机器人中所做的是第一个用户选择复选框插件,我在我的服务器上收到呼叫,如果检查它是否包含 user_ref,如果是,那么我使用自定义元数据向用户发送一条短信用户参考。当用户收到消息时,webhook 会以上述给定格式向我发送 json 数据。为了确定我收到了哪个 user_ref,我设置了自定义元数据,它是一些 string+user_ref 的组合。使用它,我可以识别我之前使用 user_ref 为其发送消息的用户的 sender.id。 sender.id 是我的 pageid,receiver.id 是您尝试获取和使用的用户 id,我们通常将消息发送给用户,也称为 psid。
希望这会有所帮助,如果您在使用上述解决方案时仍然遇到问题,请进行更新:)