こちらでLINEログインを導入した前提で進めてまいります。
LINE公式アカウントの作成
Messaging API channelを作成するにはLINEビジネスIDが必要なのでこちらをあらかじめ作っておきます。その後、以下のようにLINE公式アカウントを作成します。
LINE Official Account Managerにアクセスし、「設定」→「Messaging APIを利用する」を選択します。
そして、プロバイダーを選択し「同意する」を選択します。その後も任意の項目を必要に応じて入力します。
LINE Developer consoleに戻ってChannel access tokenを発行します。以下の${process.env.NEXT_PUBLIC_CHANNEL_ACCESS_TOKEN}にChannel access tokenを設定します。
@/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を押すとメッセージが送信されるはずです。
参考