Search code examples
phpjsoncurlwebhooksdialogflow-es

DialogFlow PHP cURL


I try to get a response from my DialogFlow Agent (v2!) via PHP curl... So I copied the normal curl command from DialogFlow:

curl -H "Content-Type: application/json; charset=utf-8"  -H "Authorization: Bearer ya29.xxxxhWdzg3rA"  -d "{\"queryInput\":{\"text\":{\"text\":\"Gib mir Informationen über meine Dienstreise von Hamburg\",\"languageCode\":\"de\"}},\"queryParams\":{\"timeZone\":\"Europe/Berlin\"}}" "https://dialogflow.googleapis.com/v2/projects/xxxx/agent/sessions/edd016e1-9xxxxxf3787f:detectIntent"

and "converted" it into PHP:

$query = "Gib mir Informationen über meine Dienstreise nach Hamburg";

$postData = array(
  'queryInput' => array(
    'text' => array(
      'text' => $query,
      'languageCode' => 'de'
    )),

    'queryParams' => array(
      'timeZone' => 'Europe/Berlin'
    )
);

$jsonData = json_encode($postData);

$ch = curl_init('https://dialogflow.googleapis.com/v2/projects/xxxx/agent/sessions/edd016e1xxxxx7f:detectIntent');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Bearer 6cXXXXfe'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

echo $result;
curl_close($ch);

"6cXXXXfe" theres my "Client access token" from DialogFlow. The URL in curl_init() is from the curl command before - I'm pretty sure the mistake is there but I just can't figure out which URL should be there...

I get an error as result:

{
    "error":
    {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

Hope someone could help me with that. Thanks!


Solution

  • The Client Access Token method is no longer used with the V2 API.

    Instead, you should be using OAuth 2 for Server-Server Applications. In this scheme, you will have created a Service Account and downloaded the keys for this account. If you're doing it manually (which you would if you're using curl) before your request you would

    • Using the private key, create a JWT request and send this to Google's auth server to get a limited-time auth token.

    • Include this token in the Authentication: Bearer header in the HTTPS request to Dialogflow.

    You can also do this using the gcloud command once you've downloaded the keys.

    You might be better off looking into a client library for Dialogflow which will also take care of this. You will still need to get the Google Cloud Service Account and download the key file, but it will take care of the rest.