フリーランスWebエンジニア Omori

Next.js Logo

LINE Messaging API 事始め1

Webhook URLを設定し、イベントを受信する方法を確認します。

準備

ドキュメントに従い準備(リンク

  1. ビジネスIDに登録し、LINE公式アカウントを作成する
  2. LINE公式アカウントのLINE Messaging APIを有効にする ※LINE Developersコンソールのログインも必要

Goを使って実装

bash
mkdir line-messaging-api-go
cd line-messaging-api-go
 
go mod init line-messaging-api-go
main.go
package main
 
import (
	"encoding/json"
	"io"
	"log"
	"net/http"
)
 
const (
	port = "8080"
)
 
func main() {
	http.HandleFunc("/webhook", webhookHandler)
 
	log.Printf("server started: http://localhost:$s", port)
	log.Printf("webhook endpoint: http://localhost:$s/webhook", port)
 
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}
 
func webhookHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
 
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("LINE webhook endpoint is running."))
		return
	}
 
	rawBody, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read body", http.StatusBadRequest)
		return
	}
 
	defer r.Body.Close()
 
	var decodedBody any
	_ = json.Unmarshal(rawBody, &decodedBody)
 
	log.Printf(
		"signature=%s body=%s decoded=%v",
		r.Header.Get("X-Line-Signature"),
		string(rawBody),
		decodedBody,
	)
 
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OK"))
}
 

Cloud RunにGithub経由でデプロイし、発行されたURLを「Messaging API設定>Webhook URL>編集」で設定します。

Cloud Run上のログで、イベント受信を確認できました。

©Omori

MEOW!