使用Facebook Messenger使用基於官方文檔的通用模板發送結構化消息here。使用Java構建JSON對象。每當我將JSON發送到Facebook,我都會得到一個響應「400-錯誤的請求」。我試着用一個在線工具進行比較,java生成的JSON與文檔中提供的JSON相比,除了變量名之外別無其他。無法理解我在構建JSON時出錯的地方。Facebook Messenger API:發送結構化消息(Java)
JSON從Java代碼..
{
"message": {
"attachment": {
"payload": {
"elements": [
{
"buttons": [
{
"title": "show website",
"type": "web_url",
"url": "https://google.com"
},
{
"payload": "sample payload",
"title": "Hi There",
"type": "postback"
}
],
"default_action": {
"fallback_url": "https://www.google.com/",
"messenger_extensions": true,
"type": "web_url",
"url": "https://www.google.com/",
"webview_height_ratio": "tall"
},
"image_url": "https://s3-ap-southeast-1.amazonaws.com/primary-4495.png",
"subtitle": "Sample Sub Title",
"title": "Sample Title"
}
],
"template_type": "generic"
},
"type": "template"
}
},
"recipient": {
"id": "988459377921053"
}
}
相應的Java代碼..
JSONObject root1 = new JSONObject();
JSONObject c01 = new JSONObject();
JSONObject c11 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONArray arrayButton= new JSONArray();
JSONArray arrayelements= new JSONArray();
JSONObject elementsObj = new JSONObject();
JSONObject defaultAction = new JSONObject();
JSONObject buttons1 = new JSONObject();
JSONObject buttons2 = new JSONObject();
root1.put("recipient", c01);
c01.put("id", userId);
root1.put("message", c11);
c11.put("attachment", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "generic");
payload.put("elements", arrayelements);
arrayelements.put(elementsObj);
elementsObj.put("title", "Sample Title");
elementsObj.put("image_url", "https://s3-ap-southeast-1.amazonaws.com/primary-4495.png");
elementsObj.put("subtitle", "Sample Sub Title");
elementsObj.put("default_action", defaultAction);
defaultAction.put("type", "web_url");
defaultAction.put("url", "https://www.google.com/");
defaultAction.put("messenger_extensions", true);
defaultAction.put("webview_height_ratio", "tall");
defaultAction.put("fallback_url", "https://www.google.com/");
buttons1.put("type", "web_url");
buttons1.put("url", "https://google.com");
buttons1.put("title", "show website");
arrayButton.put(buttons1);
buttons2.put("type", "postback");
buttons2.put("title", "Hi There");
buttons2.put("payload", "sample payload");
arrayButton.put(buttons2);
elementsObj.put("buttons", arrayButton);
正如你可以在提供的樣品的相比上述JSON時看到官方文件中,只有元素的順序是不同的。過去2天卡住這個問題..請幫助..
我從來沒有使用Messenger的API,但是,你有沒有嘗試創建的相同順序/名稱的元素?也許API正在按照文檔中提供的相同順序等待名稱......並且您正在請求中發送access_token? –
我試過仍然得到相同的錯誤 – Lucy
所以,我建議你記錄你的回答中的錯誤。我認爲'400錯誤請求'不是整個錯誤信息。可能你有更多關於可能對你有幫助的錯誤的信息。此外,嘗試在發佈之前將[root1]轉換爲JSON,如[據此]所述(http://stackoverflow.com/questions/36634453/facebook-messenger-api-send-structured-message?rq=1) –