You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 queryResult instead of result (so your $json->result->parameters->text won't correctly fetch user input)
  • The speech and return fields aren't valid in v2's WebhookResponse schema; the correct field for text responses is fulfillmentText
  • Your else branch doesn't initialize the $response object, 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?

  1. Request Parsing: Swapped $json->result to $json->queryResult to match v2's request schema, plus added ?? '' to safely handle cases where the text parameter might be missing
  2. Response Cleanup: Removed invalid speech and return fields, kept only fulfillmentText (the v2 equivalent for sending text responses)
  3. Error Prevention: Initialized the $response object in the else branch to fix undefined variable issues
  4. Code Simplification: Removed redundant quotes around variables (e.g., $fulfillmentText instead 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:55:59