Panduan memulai: Membuat webhook

Panduan ini menunjukkan cara menggunakan webhook, sehingga agen Anda bisa lebih dinamis. Cloud Functions digunakan untuk menghosting webhook karena kemudahannya, tetapi ada banyak cara lain yang dapat Anda lakukan untuk menghosting layanan webhook. Contoh ini juga menggunakan bahasa pemrograman Go, tetapi Anda dapat menggunakan bahasa apa pun yang didukung oleh Cloud Functions. Anda tidak perlu mengedit kode untuk panduan ini.

Contoh kode webhook melakukan hal berikut:

  • Membaca parameter value dari permintaan webhook.
  • Menulis nilai parameter ke respons webhook.
  • Memberikan respons teks di respons webhook.

Sebelum memulai

Jika tidak berencana menggunakan webhook, Anda dapat melewati panduan memulai ini.

Anda harus melakukan hal berikut sebelum membaca panduan ini:

  1. Baca Dasar-dasar Dialogflow CX.
  2. Lakukan langkah-langkah penyiapan.
  3. Lakukan langkah-langkah dalam panduan memulai Membangun agen. Langkah-langkah di bawah ini akan dilanjutkan dengan agen yang sama. Jika tidak lagi memiliki agen tersebut, Anda dapat mendownload agen dan memulihkannya.

Membuat Cloud Function

Cloud Functions dapat dibuat dengan Konsol Google Cloud (buka dokumentasi, buka konsol). Cara membuat fungsi untuk panduan ini:

  1. Agen Dialogflow Anda dan fungsinya harus berada dalam project yang sama. Ini adalah cara termudah bagi Dialogflow untuk memiliki akses yang aman ke fungsi Anda. Untuk memilih project, buka pemilih project.
  2. Buka halaman ringkasan Cloud Functions.
  3. Klik Create Function, dan tetapkan kolom berikut:
    • Lingkungan: generasi ke-1
    • Nama fungsi: shirts-agent-webhook
    • Region: Jika Anda menentukan wilayah untuk agen, gunakan wilayah yang sama.
    • Jenis Pemicu HTTP: HTTP
    • URL: Klik tombol salin di sini dan simpan nilainya. Anda akan memerlukan URL ini saat mengonfigurasi webhook.
    • Autentikasi: Memerlukan autentikasi
    • Wajibkan HTTPS: dicentang
  4. Klik Simpan.
  5. Klik Next (Anda tidak memerlukan setelan runtime, build, koneksi, atau keamanan khusus).
  6. Tetapkan kolom berikut:
    • Runtime: Pilih runtime Go terbaru.
    • Kode sumber: Editor Inline
    • Titik entri: HandleWebhookRequest
  7. Ganti kode dengan kode berikut:
    // 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]interface{} `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 need to be defined--just those that you need to process.
    // As an alternative, you could use the types provided by the Dialogflow protocol buffers:
    // https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3#WebhookRequest
    type webhookRequest struct {
    	FulfillmentInfo fulfillmentInfo `json:"fulfillmentInfo"`
    	SessionInfo     sessionInfo     `json:"sessionInfo"`
    }
    
    // webhookResponse is used to marshal a WebhookResponse JSON object. Note that
    // not all members need to be defined--just those that you need to process.
    // As an alternative, you could use the types provided by the Dialogflow protocol buffers:
    // https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3#WebhookResponse
    type webhookResponse struct {
    	FulfillmentResponse fulfillmentResponse `json:"fulfillmentResponse"`
    	SessionInfo         sessionInfo         `json:"sessionInfo"`
    }
    
    // confirm handles webhook calls using the "confirm" tag.
    func confirm(request webhookRequest) (webhookResponse, error) {
    	// Create a text message that utilizes the "size" and "color"
    	// parameters provided by the end-user.
    	// This text message is used in the response below.
    	t := fmt.Sprintf("You can pick up your order for a %s %s shirt in 5 days.",
    		request.SessionInfo.Parameters["size"],
    		request.SessionInfo.Parameters["color"])
    
    	// Create session parameters that are populated in the response.
    	// The "cancel-period" parameter is referenced by the agent.
    	// This example hard codes the value 2, but a real system
    	// might look up this value in a database.
    	p := map[string]interface{}{"cancel-period": "2"}
    
    	// Build and return the response.
    	response := webhookResponse{
    		FulfillmentResponse: fulfillmentResponse{
    			Messages: []responseMessage{
    				{
    					Text: text{
    						Text: []string{t},
    					},
    				},
    			},
    		},
    		SessionInfo: sessionInfo{
    			Parameters: p,
    		},
    	}
    	return response, nil
    }
    
    // handleError handles internal errors.
    func handleError(w http.ResponseWriter, err error) {
    	w.WriteHeader(http.StatusInternalServerError)
    	fmt.Fprintf(w, "ERROR: %v", err)
    }
    
    // HandleWebhookRequest handles WebhookRequest and sends the WebhookResponse.
    func HandleWebhookRequest(w http.ResponseWriter, r *http.Request) {
    	var request webhookRequest
    	var response webhookResponse
    	var err error
    
    	// Read input JSON
    	if err = json.NewDecoder(r.Body).Decode(&request); err != nil {
    		handleError(w, err)
    		return
    	}
    	log.Printf("Request: %+v", request)
    
    	// Get the tag from the request, and call the corresponding
    	// function that handles that tag.
    	// This example only has one possible tag,
    	// but most agents would have many.
    	switch tag := request.FulfillmentInfo.Tag; tag {
    	case "confirm":
    		response, err = confirm(request)
    	default:
    		err = fmt.Errorf("Unknown tag: %s", tag)
    	}
    	if err != nil {
    		handleError(w, err)
    		return
    	}
    	log.Printf("Response: %+v", response)
    
    	// Send response
    	if err = json.NewEncoder(w).Encode(&response); err != nil {
    		handleError(w, err)
    		return
    	}
    }
    
    
  8. Klik Deploy.
  9. Tunggu hingga indikator status menunjukkan bahwa fungsi telah berhasil di-deploy. Sambil menunggu, periksa kode yang baru saja Anda deploy. Komentar kode menjelaskan detail-detail penting.

Membuat webhook

Setelah webhook ada sebagai fungsi Cloud, Anda akan mengaitkan webhook ini dengan agen Anda. Untuk membuat webhook untuk agen Anda:

  1. Buka Dialogflow CX Console.
  2. Pilih project Google Cloud Anda.
  3. Pilih agen Anda.
  4. Pilih tab Kelola.
  5. Klik Webhook.
  6. Klik Create.
  7. Lengkapi kolom berikut:
    • Nama tampilan: shirts-agent-webhook
    • URL webhook: Berikan URL webhook yang Anda simpan saat membuat fungsi.
    • Subjenis: Standar.
    • Semua kolom lainnya menggunakan nilai default.
  8. Klik Simpan.

Gunakan webhook

Setelah webhook tersedia untuk agen, Anda akan menggunakan webhook dalam fulfillment. Halaman Konfirmasi Pesanan memiliki fulfillment entri, yang saat ini memiliki respons teks statis. Untuk memperbarui fulfillment agar menggunakan webhook Anda:

  1. Pilih tab Build.
  2. Klik halaman Konfirmasi Pesanan untuk meluaskan halaman di grafik builder agen.
  3. Klik kolom Entry Fulfillment di halaman untuk membuka panel fulfillment.
  4. Hapus tanggapan teks yang ada di bagian judul Agen mengatakan. Saat Anda mengarahkan teks ke atas, tombol hapus akan muncul.
  5. Klik Aktifkan webhook.
  6. Pilih opsi shirts-agent-webhook dari menu dropdown Webhook.
  7. Masukkan confirm untuk kolom Tag.
  8. Klik Simpan.
  9. Tutup panel fulfillment.

Screenshot grafik agen

Kode webhook yang di-deploy mengirimkan respons yang membuat parameter bernama cancel-period. Perbarui agen untuk mereferensikan parameter ini di respons agen akhir untuk halaman Konfirmasi Pesanan yang sama:

  1. Klik rute kondisi yang ditunjukkan dengan kondisi true untuk membuka panel rute.
  2. Scroll ke bawah ke bagian Fulfillment di panel rute, dan tambahkan respons teks berikut di bagian judul Agent say: You can cancel your order within $session.params.cancel-period days. Goodbye.
  3. Klik Simpan.
  4. Tutup panel rute.

Screenshot grafik agen

Menguji agen di simulator

Agen dan webhook Anda siap diuji dengan simulator:

  1. Klik Test Agent.
  2. Masukkan I want to buy a large red shirt, lalu tekan enter.

Karena Anda memberikan ukuran dan warna, Anda telah memberikan semua yang diperlukan agen untuk membuat pesanan kemeja, sehingga langsung beralih ke halaman Konfirmasi Pesanan.

Screenshot grafik agen

Berikut ini penjelasan respons agen:

Respons Penjelasan
Oke, mari kita mulai urutan baru. Saat halaman Pesanan Baru menjadi aktif, fulfillment entri dipanggil. Respons dipicu dari fulfillment ini.
Anda telah memilih kemeja besar berwarna merah. Jika semua parameter formulir telah diberikan untuk halaman Pesanan Baru, pemeriksaan rute kondisi untuk pelengkapan formulir akan dipanggil. Respons dipicu dari fulfillment untuk rute ini. Rute ini juga bertransisi ke halaman Konfirmasi Pesanan.
Anda dapat mengambil pesanan untuk kemeja merah besar dalam 5 hari. Fulfillment entri untuk halaman Konfirmasi Pesanan memanggil webhook. Lihat fungsi confirm di kode webhook. Fungsi tersebut membuat respons teks ini, dan menggunakan parameter yang disediakan di permintaan webhook.
Anda dapat membatalkan pesanan Anda dalam waktu 2 hari. Sampai jumpa. Halaman Konfirmasi Pesanan memiliki rute kondisi dengan kondisi yang selalu benar. Respons ini dipicu oleh fulfillment untuk rute tersebut. Perlu diperhatikan bahwa respons memanfaatkan parameter yang ditetapkan oleh webhook di respons webhook.