Dialogflow(api.ai)Webhook JSON响应解析失败问题求助
Fixing "Cannot find field: speech in message google.cloud.dialogflow.v2.WebhookResponse" Error
Hey there! The error you're hitting is because Dialogflow v2 no longer uses the speech field in webhook responses—this was a holdover from the older v1 API. Let's walk through the fixes you need to make to your PHP code:
Key Issues in Your Current Code
- Dialogflow v2's request structure uses
queryResultinstead ofresult(so your$json->result->parameters->textwon't correctly fetch user input) - The
speechandreturnfields aren't valid in v2'sWebhookResponseschema; the correct field for text responses isfulfillmentText - Your
elsebranch doesn't initialize the$responseobject, which would throw an undefined variable error
Modified Working Code
<?php $method = $_SERVER['REQUEST_METHOD']; // Process only when method is POST if($method == 'POST'){ $requestBody = file_get_contents('php://input'); $json = json_decode($requestBody); // v2 uses queryResult instead of result; add fallback for missing text parameter $text = $json->queryResult->parameters->text ?? ''; switch ($text) { case 'hi': $fulfillmentText = "Hi, Nice to meet you"; break; case 'bye': $fulfillmentText = "Bye, good night"; break; case 'anything': $fulfillmentText = "Yes, you can type anything here."; break; default: $fulfillmentText = "Sorry"; break; } $response = new \stdClass(); // Only include fields valid for Dialogflow v2 $response->fulfillmentText = $fulfillmentText; $response->source = 'source-of-the-response'; echo json_encode($response); } else { $fulfillmentText = "Ok"; $response = new \stdClass(); // Initialize response object to avoid errors $response->fulfillmentText = $fulfillmentText; echo json_encode($response); } ?>
What Changed?
- Request Parsing: Swapped
$json->resultto$json->queryResultto match v2's request schema, plus added?? ''to safely handle cases where thetextparameter might be missing - Response Cleanup: Removed invalid
speechandreturnfields, kept onlyfulfillmentText(the v2 equivalent for sending text responses) - Error Prevention: Initialized the
$responseobject in theelsebranch to fix undefined variable issues - Code Simplification: Removed redundant quotes around variables (e.g.,
$fulfillmentTextinstead of"$fulfillmentText") since they're unnecessary here
This should resolve the JSON parsing error and get your webhook working smoothly with Dialogflow v2.
内容的提问来源于stack exchange,提问作者Phani
相关产品推荐
相关产品推荐

