Files
homaroma/apps/spa/src/lib/liff.ts
T
2026-06-08 06:17:50 +07:00

62 lines
1.6 KiB
TypeScript

import liff from "@line/liff";
import { useAuthStore } from "../store/authStore";
const API_URL = import.meta.env.VITE_API_URL || "http://localhost:3000/api";
export const initLiff = async (liffId: string) => {
try {
await liff.init({ liffId });
useAuthStore.getState().setLiffInitialized(true);
if (liff.isLoggedIn()) {
const profile = await liff.getProfile();
await authenticateWithBackend(profile);
} else if (liff.isInClient()) {
// เปิดเว็บผ่านเบราว์เซอร์ของ LINE (In-App Browser) แต่ยังไม่ได้ล็อกอิน
liff.login();
}
} catch (error) {
console.error("LIFF Initialization failed", error);
}
};
const authenticateWithBackend = async (profile: any) => {
try {
const response = await fetch(`${API_URL}/auth/line`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
lineUserId: profile.userId,
displayName: profile.displayName,
pictureUrl: profile.pictureUrl,
}),
});
if (response.ok) {
const data = await response.json();
if (data.success && data.token) {
useAuthStore.getState().setAuth(data.token, data.customer);
}
} else {
console.error("Backend authentication failed");
}
} catch (error) {
console.error("Error authenticating with backend", error);
}
};
export const loginLiff = () => {
if (!liff.isLoggedIn()) {
liff.login();
}
};
export const logoutLiff = () => {
if (liff.isLoggedIn()) {
liff.logout();
useAuthStore.getState().logout();
}
};