Create a webhook

This guide shows you how to use a webhook, so your agent can be more dynamic. Cloud Functions are used to host the webhook due to their simplicity, but there are many other ways that you could host a webhook service. The example also uses the Go programming language, but you can use any language supported by Cloud Functions. You will not need to edit the code for this guide.

The example webhook code does the following:

  • Reads parameter values from the webhook request.
  • Writes a parameter value to the webhook response.
  • Provides a text response in the webhook response.

Before you begin

If you don't plan on using webhooks, you can skip this quickstart.

You should do the following before reading this guide:

  1. Read flow basics.
  2. Perform setup steps.
  3. Perform steps in the Build an agent using flows quickstart guide. Steps below continue working on the same agent. If you no longer have that agent, you can download the agent and restore it.

Create the Cloud Function

Cloud Functions can be created with the Google Cloud console (visit documentation, open console). To create a function for this guide:

  1. It is important that your Dialogflow CX agent and the function are both in the same project. This is the easiest way for Dialogflow CX to have secure access to your function. To select your project, go to the project selector.
  2. Go to the Cloud Functions overview page.
  3. Click Create Function, and set the following fields:
    • Environment: 1st gen
    • Function name: shirts-agent-webhook
    • Region: If you specified a region for your agent, use the same region.
    • HTTP Trigger type: HTTP
    • URL: Click the copy button here and save the value. You will need this URL when configuring the webhook.
    • Authentication: Require authentication
    • Require HTTPS: checked
  4. Click Save.
  5. Click Next (You do not need special runtime, build, connections, or security settings).
  6. Set the following fields:
    • Runtime: Select the latest Go runtime.
    • Source code: Inline Editor
    • Entry point: HandleWebhookRequest
  7. Replace the code with the following:

    // Package cxwh contains an example Dialogflow CX webhook
    package cxwh
    
    import (
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    )
    
    type fulfillmentInfo struct {
    	Tag string `json:"tag"`
    }
    
    type sessionInfo struct {
    	Session    string         `json:"session"`
    	Parameters map[string]any `json:"parameters"`
    }
    
    type text struct {
    	Text []string `json:"text"`
    }
    
    type responseMessage struct {
    	Text text `json:"text"`
    }
    
    type fulfillmentResponse struct {
    	Messages []responseMessage `json:"messages"`
    }
    
    // webhookRequest is used to unmarshal a WebhookRequest JSON object. Note that
    // not all members