1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsにLINEのapiを用いてメッセージを送信する

Posted at

こちらでLINEログインを導入した前提で進めてまいります。

LINE公式アカウントの作成

Messaging API channelを作成するにはLINEビジネスIDが必要なのでこちらをあらかじめ作っておきます。その後、以下のようにLINE公式アカウントを作成します。
FireShot Capture 017 - LINE Official Account - entry.line.biz.png

LINE Official Account Managerにアクセスし、「設定」→「Messaging APIを利用する」を選択します。

スクリーンショット 2025-01-18 203053.png

スクリーンショット 2025-01-18 203248.png

そして、プロバイダーを選択し「同意する」を選択します。その後も任意の項目を必要に応じて入力します。
スクリーンショット 2025-01-18 203401.png

APIが有効化されると以下のような画面になります。
スクリーンショット 2025-01-18 203706.png

LINE Developer consoleに戻ってChannel access tokenを発行します。以下の${process.env.NEXT_PUBLIC_CHANNEL_ACCESS_TOKEN}にChannel access tokenを設定します。
スクリーンショット 2025-01-19 181053.png

@/app/test.page.tsx
'use client';

import {
  getLinProfileServerComponent,
  sendLineMessageAction,
  updateTokenServerComponent,
} from '@/app/actions/set-cookie';
import { Button } from '@mui/material';
export default function ClientComponent() {

  const sendLine = async () => {
    const data = await updateTokenServerComponent();
    console.log(data);
    const profile = await getLinProfileServerComponent(data.access_token);
    console.log(profile);
    await sendLineMessageAction(profile.userId);
  };
  return (
    <>
      <Button color='inherit' onClick={sendLine}>
        sendLine
      </Button>
    </>
  );
}
@/app/actions/set-cookie.ts
import { v4 as uuidv4 } from 'uuid';

export async function sendLineMessageAction(uid: string) {
  console.log(uid);
  const messagePayload = {
    to: uid, // Replace with actual user ID
    messages: [
      { type: 'text', text: 'test' },
    ],
  };

  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.NEXT_PUBLIC_CHANNEL_ACCESS_TOKEN}`,
      'X-Line-Retry-Key': uuidv4(), // Replace with a valid UUID
    },
    body: JSON.stringify(messagePayload),
  };

  try {
    const response = await fetch('https://api.line.me/v2/bot/message/push', requestOptions);

    if (response.ok) {
      console.log('Message sent successfully');
    } else {
      const errorData = await response.json();
      console.error('Error sending message:', errorData);
    }
  } catch (error) {
    console.error('Network Error during message send:', error);
  }
}

以上でButtonを押すとメッセージが送信されるはずです。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?